diff --git a/.gitattributes b/.gitattributes index 2a377d08a..e69de29bb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,8 +0,0 @@ -*.png filter=lfs diff=lfs merge=lfs -text -*.jpg filter=lfs diff=lfs merge=lfs -text -*.ogg filter=lfs diff=lfs merge=lfs -text -*.binka filter=lfs diff=lfs merge=lfs -text -*.arc filter=lfs diff=lfs merge=lfs -text -*.ttf filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.ico filter=lfs diff=lfs merge=lfs -text diff --git a/.github/banner.png b/.github/banner.png new file mode 100644 index 000000000..bde6e0b12 Binary files /dev/null and b/.github/banner.png differ diff --git a/.github/workflows/docker-nightly.yml b/.github/workflows/docker-nightly.yml new file mode 100644 index 000000000..78d5256cb --- /dev/null +++ b/.github/workflows/docker-nightly.yml @@ -0,0 +1,160 @@ +name: Docker Nightly Dedicated Server + +on: + workflow_dispatch: + push: + branches: + - "main" + - 'feature/dedicated-server' + paths-ignore: + - ".gitignore" + - "*.md" + - ".github/*.md" + +permissions: + contents: read + packages: write + +concurrency: + group: docker-nightly-dedicated-server + cancel-in-progress: true + +jobs: + build-runtime: + name: Build Dedicated Server Runtime + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup msbuild + uses: microsoft/setup-msbuild@v2 + + - name: Build Dedicated Server Runtime Only + shell: pwsh + run: | + MSBuild.exe Minecraft.World\Minecraft.World.vcxproj /p:Configuration=Release /p:Platform=x64 /m + MSBuild.exe Minecraft.Server\Minecraft.Server.vcxproj /p:Configuration=Release /p:Platform=x64 /m + + - name: Stage dedicated server runtime + shell: pwsh + run: | + $serverOut = "Minecraft.Server/x64/Minecraft.Server/Release" + $stage = ".artifacts/dedicated-server-runtime" + + if (Test-Path $stage) { + Remove-Item -Path $stage -Recurse -Force + } + + New-Item -ItemType Directory -Path (Join-Path $stage "Windows64") -Force | Out-Null + + # Minimum required runtime files + $required = @( + "Minecraft.Server.exe", + "iggy_w64.dll", + "Common" + ) + + foreach ($entry in $required) { + $src = Join-Path $serverOut $entry + if (-not (Test-Path $src)) { + throw "Missing required runtime path: $src" + } + } + + # Copy required files + Copy-Item -Path (Join-Path $serverOut "Minecraft.Server.exe") -Destination (Join-Path $stage "Minecraft.Server.exe") -Force + Copy-Item -Path (Join-Path $serverOut "iggy_w64.dll") -Destination (Join-Path $stage "iggy_w64.dll") -Force + Copy-Item -Path (Join-Path $serverOut "Common") -Destination (Join-Path $stage "Common") -Recurse -Force + if (Test-Path (Join-Path $serverOut "Windows64")) { + Copy-Item -Path (Join-Path $serverOut "Windows64/*") -Destination (Join-Path $stage "Windows64") -Recurse -Force + } else { + Write-Host "Windows64 directory is not present in build output; staging without it." + } + + Get-ChildItem -Path $stage -Recurse -File | Select-Object -First 20 | ForEach-Object { + Write-Host "Staged: $($_.FullName)" + } + + - name: Upload dedicated server runtime to artifacts + uses: actions/upload-artifact@v4 + with: + name: dedicated-server-runtime + if-no-files-found: error + path: | + .artifacts/dedicated-server-runtime/** + + docker-publish: + name: Build and Push Docker Image + runs-on: ubuntu-latest + needs: build-runtime + + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Download dedicated server runtime from artifacts + uses: actions/download-artifact@v4 + with: + name: dedicated-server-runtime + path: .artifacts/runtime + + - name: Prepare Docker runtime directory + shell: bash + run: | + set -euo pipefail + + rm -rf runtime + mkdir -p runtime + cp .artifacts/runtime/Minecraft.Server.exe runtime/Minecraft.Server.exe + cp .artifacts/runtime/iggy_w64.dll runtime/iggy_w64.dll + cp -R .artifacts/runtime/Common runtime/Common + mkdir -p runtime/Windows64 + if [[ -d ".artifacts/runtime/Windows64" ]]; then + cp -R .artifacts/runtime/Windows64/. runtime/Windows64/ + fi + + test -f runtime/Minecraft.Server.exe + test -f runtime/iggy_w64.dll + test -d runtime/Common + test -d runtime/Windows64 + + - name: Compute image name + id: image + shell: bash + run: | + owner="$(echo "${{ vars.CONTAINER_REGISTRY_OWNER || github.repository_owner }}" | tr '[:upper:]' '[:lower:]')" + image_tag="nightly" + # if [[ "${{ github.ref }}" != "refs/heads/main" ]]; then + # image_tag="nightly-test" + # fi + echo "owner=$owner" >> "$GITHUB_OUTPUT" + echo "image=ghcr.io/$owner/minecraft-lce-dedicated-server" >> "$GITHUB_OUTPUT" + echo "image_tag=$image_tag" >> "$GITHUB_OUTPUT" + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.image.outputs.image }} + tags: | + type=raw,value=${{ steps.image.outputs.image_tag }} + + - name: Login to GHCR + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ secrets.GHCR_USERNAME || github.actor }} + password: ${{ secrets.GHCR_TOKEN || secrets.GITHUB_TOKEN }} + + - name: Build and push image + uses: docker/build-push-action@v6 + with: + context: . + file: docker/dedicated-server/Dockerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: | + MC_RUNTIME_DIR=runtime \ No newline at end of file diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 402f3cb62..5af23fe60 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,15 +1,19 @@ -name: Nightly Release +name: Nightly Releases on: workflow_dispatch: push: branches: - 'main' + - 'feature/dedicated-server' paths-ignore: - '.gitignore' - '*.md' - '.github/*.md' +permissions: + contents: write + jobs: build: name: Build Windows64 @@ -28,13 +32,16 @@ jobs: - name: Zip Build run: 7z a -r LCEWindows64.zip ./x64/Release/* - - name: Update release + - name: Zip Dedicated Server Build + run: 7z a -r LCEServerWindows64.zip ./x64/Minecraft.Server/Release/* + + - name: Update Client release uses: andelf/nightly-release@main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: nightly - name: Nightly Release + name: Nightly Client Release body: | Requires at least Windows 7 and DirectX 11 compatible GPU to run. Compiled with MSVC v14.44.35207 in Release mode with Whole Program Optimization, as well as `/O2 /Ot /Oi /Ob3 /GF /fp:precise`. @@ -44,3 +51,19 @@ jobs: LCEWindows64.zip ./x64/Release/Minecraft.Client.exe ./x64/Release/Minecraft.Client.pdb + + - name: Update Dedicated Server release + uses: andelf/nightly-release@main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: nightly-dedicated-server + name: Nightly Dedicated Server Release + body: | + Dedicated Server runtime for Windows64. + + Download `LCEServerWindows64.zip` and extract it to a folder where you'd like to keep the server runtime. + files: | + LCEServerWindows64.zip + ./x64/Minecraft.Server/Release/Minecraft.Server.exe + ./x64/Minecraft.Server/Release/Minecraft.Server.pdb diff --git a/.gitignore b/.gitignore index 9abf75075..40a690b02 100644 --- a/.gitignore +++ b/.gitignore @@ -379,11 +379,8 @@ MigrationBackup/ FodyWeavers.xsd # VS Code files for those working on multiple tools -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json +.vscode/ +!.vscode/*.example.json *.code-workspace # Local History for Visual Studio Code @@ -423,6 +420,12 @@ Minecraft.World/x64_Debug/ Minecraft.World/Release/ Minecraft.World/x64_Release/ +Minecraft.Server/x64/ +Minecraft.Server/Debug/ +Minecraft.Server/x64_Debug/ +Minecraft.Server/Release/ +Minecraft.Server/x64_Release/ + build/* # Existing build output files @@ -434,6 +437,9 @@ build/* # Local saves Minecraft.Client/Saves/ +tmp*/ +_server_asset_probe/ +server-data/ # Visual Studio Per-User Config *.user /out diff --git a/.vscode/settings.json b/.vscode/settings.example.json similarity index 100% rename from .vscode/settings.json rename to .vscode/settings.example.json diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c6eb80ed..ceb15951a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -92,6 +92,91 @@ target_link_libraries(MinecraftClient PRIVATE > ) +set(MINECRAFT_SERVER_SOURCES ${MINECRAFT_CLIENT_SOURCES}) +list(APPEND MINECRAFT_SERVER_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Windows64/ServerMain.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Access/Access.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Access/BanManager.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Access/WhitelistManager.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/ServerCli.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/ServerCliInput.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/ServerCliParser.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/ServerCliEngine.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/ServerCliRegistry.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/ban/CliCommandBan.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/help/CliCommandHelp.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/pardon/CliCommandPardon.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/stop/CliCommandStop.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/list/CliCommandList.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/tp/CliCommandTp.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/time/CliCommandTime.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/weather/CliCommandWeather.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/give/CliCommandGive.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/kill/CliCommandKill.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Console/commands/experience/CliCommandExperience.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Common/FileUtils.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Common/StringUtils.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/ServerLogger.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/ServerLogManager.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/ServerProperties.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/vendor/linenoise/linenoise.c" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/WorldManager.cpp" +) + +add_executable(MinecraftServer ${MINECRAFT_SERVER_SOURCES}) +target_include_directories(MinecraftServer PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/Iggy/include" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Xbox/Sentient/Include" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.World/x64headers" + "${CMAKE_CURRENT_SOURCE_DIR}/include/" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Server/Windows64" +) +target_compile_definitions(MinecraftServer PRIVATE + $<$:_LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_DEBUG;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64;MINECRAFT_SERVER_BUILD> + $<$>:_LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64;MINECRAFT_SERVER_BUILD> +) +if(MSVC) + configure_msvc_target(MinecraftServer) + target_link_options(MinecraftServer PRIVATE + $<$:/LTCG /INCREMENTAL:NO> + ) +endif() + +set_target_properties(MinecraftServer PROPERTIES + OUTPUT_NAME "Minecraft.Server" + VS_DEBUGGER_WORKING_DIRECTORY "$" + VS_DEBUGGER_COMMAND_ARGUMENTS "-port 25565 -bind 0.0.0.0 -name DedicatedServer" +) + +target_link_libraries(MinecraftServer PRIVATE + MinecraftWorld + d3d11 + XInput9_1_0 + wsock32 + legacy_stdio_definitions + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/Iggy/lib/iggy_w64.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/Iggy/lib/iggyperfmon_w64.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/Iggy/lib/iggyexpruntime_w64.lib" + $<$: + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Input_d.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Storage_d.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Render_PC_d.lib" + > + $<$>: + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Input.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Storage.lib" + "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Windows64/4JLibs/libs/4J_Render_PC.lib" + > +) + if(CMAKE_HOST_WIN32) message(STATUS "Starting redist copy...") execute_process( @@ -147,4 +232,13 @@ else() message(FATAL_ERROR "Redist and asset copying is only supported on Windows (Robocopy) and Unix systems (rsync).") endif() -set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT MinecraftClient) +add_custom_command(TARGET MinecraftServer POST_BUILD + COMMAND "${CMAKE_COMMAND}" + -DPROJECT_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}" + -DOUTPUT_DIR="$" + -DCONFIGURATION=$ + -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/CopyServerAssets.cmake" + VERBATIM +) + +set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT MinecraftServer) diff --git a/COMPILE.md b/COMPILE.md index b62c95754..86fb5cee3 100644 --- a/COMPILE.md +++ b/COMPILE.md @@ -3,7 +3,9 @@ ## Visual Studio (`.sln`) 1. Open `MinecraftConsoles.sln` in Visual Studio 2022. -2. Set `Minecraft.Client` as the Startup Project. +2. Set Startup Project: + - Client: `Minecraft.Client` + - Dedicated server: `Minecraft.Server` 3. Select configuration: - `Debug` (recommended), or - `Release` @@ -12,6 +14,17 @@ - `Build > Build Solution` (or `Ctrl+Shift+B`) - Start debugging with `F5`. +### Dedicated server debug arguments + +- Default debugger arguments for `Minecraft.Server`: + - `-port 25565 -bind 0.0.0.0 -name DedicatedServer` +- You can override arguments in: + - `Project Properties > Debugging > Command Arguments` +- `Minecraft.Server` post-build copies only the dedicated-server asset set: + - `Common/Media/MediaWindows64.arc` + - `Common/res` + - `Windows64/GameHDD` + ## CMake (Windows x64) Configure (use your VS Community instance explicitly): @@ -32,6 +45,18 @@ Build Release: cmake --build build --config Release --target MinecraftClient ``` +Build Dedicated Server (Debug): + +```powershell +cmake --build build --config Debug --target MinecraftServer +``` + +Build Dedicated Server (Release): + +```powershell +cmake --build build --config Release --target MinecraftServer +``` + Run executable: ```powershell @@ -39,6 +64,13 @@ cd .\build\Debug .\MinecraftClient.exe ``` +Run dedicated server: + +```powershell +cd .\build\Debug +.\Minecraft.Server.exe -port 25565 -bind 0.0.0.0 -name DedicatedServer +``` + Notes: - The CMake build is Windows-only and x64-only. - Contributors on macOS or Linux need a Windows machine or VM to build the project. Running the game via Wine is separate from having a supported build environment. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c75279d7d..855491da1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,6 +46,13 @@ However, we would accept changes that... - Having workable multi-platform compilation for ARM, Consoles, Linux - Being a good base for further expansion and modding of LCE, such as backports and "modpacks". +# Scope of PRs +All Pull Requests should fully document the changes they include in their file changes. They should also be limited to one general topic and not touch all over the codebase unless its justifiable. + +For example, we would not accept a PR that reworks UI, multiplayer code, and furnace ticking even if its a "fixup" PR as its too difficult to review a ton of code changes that are all irrelevant from each other. However, a PR focused on adding a bunch of commands or fixes several crashes that are otherwise irrelevant to each other would be accepted. + +If your PR includes any undocumented changes it will be closed. + # Use of AI and LLMs We currently do not accept any new code into the project that was written largely, entirely, or even noticably by an LLM. All contributions should be made by humans that understand the codebase. diff --git a/Minecraft.Client/AbstractContainerScreen.cpp b/Minecraft.Client/AbstractContainerScreen.cpp index fbf1331d0..c2de6dc9a 100644 --- a/Minecraft.Client/AbstractContainerScreen.cpp +++ b/Minecraft.Client/AbstractContainerScreen.cpp @@ -51,7 +51,7 @@ void AbstractContainerScreen::render(int xm, int ym, float a) glColor4f(1, 1, 1, 1); glEnable(GL_RESCALE_NORMAL); - Slot *hoveredSlot = NULL; + Slot *hoveredSlot = nullptr; for ( Slot *slot : *menu->slots ) { @@ -73,7 +73,7 @@ void AbstractContainerScreen::render(int xm, int ym, float a) } shared_ptr inventory = minecraft->player->inventory; - if (inventory->getCarried() != NULL) + if (inventory->getCarried() != nullptr) { glTranslatef(0, 0, 32); // Slot old = carriedSlot; @@ -90,7 +90,7 @@ void AbstractContainerScreen::render(int xm, int ym, float a) renderLabels(); - if (inventory->getCarried() == NULL && hoveredSlot != NULL && hoveredSlot->hasItem()) + if (inventory->getCarried() == nullptr && hoveredSlot != nullptr && hoveredSlot->hasItem()) { wstring elementName = trimString(Language::getInstance()->getElementName(hoveredSlot->getItem()->getDescriptionId())); @@ -127,7 +127,7 @@ void AbstractContainerScreen::renderSlot(Slot *slot) int y = slot->y; shared_ptr item = slot->getItem(); - if (item == NULL) + if (item == nullptr) { int icon = slot->getNoItemIcon(); if (icon >= 0) @@ -151,7 +151,7 @@ Slot *AbstractContainerScreen::findSlot(int x, int y) { if (isHovering(slot, x, y)) return slot; } - return NULL; + return nullptr; } bool AbstractContainerScreen::isHovering(Slot *slot, int xm, int ym) @@ -177,7 +177,7 @@ void AbstractContainerScreen::mouseClicked(int x, int y, int buttonNum) bool clickedOutside = (x < xo || y < yo || x >= xo + imageWidth || y >= yo + imageHeight); int slotId = -1; - if (slot != NULL) slotId = slot->index; + if (slot != nullptr) slotId = slot->index; if (clickedOutside) { @@ -210,7 +210,7 @@ void AbstractContainerScreen::keyPressed(wchar_t eventCharacter, int eventKey) void AbstractContainerScreen::removed() { - if (minecraft->player == NULL) return; + if (minecraft->player == nullptr) return; } void AbstractContainerScreen::slotsChanged(shared_ptr container) diff --git a/Minecraft.Client/AbstractTexturePack.cpp b/Minecraft.Client/AbstractTexturePack.cpp index 80799a4c5..a3c677272 100644 --- a/Minecraft.Client/AbstractTexturePack.cpp +++ b/Minecraft.Client/AbstractTexturePack.cpp @@ -3,21 +3,22 @@ #include "AbstractTexturePack.h" #include "..\Minecraft.World\InputOutputStream.h" #include "..\Minecraft.World\StringHelpers.h" +#include "Common/UI/UI.h" AbstractTexturePack::AbstractTexturePack(DWORD id, File *file, const wstring &name, TexturePack *fallback) : id(id), name(name) { // 4J init textureId = -1; - m_colourTable = NULL; + m_colourTable = nullptr; this->file = file; this->fallback = fallback; - m_iconData = NULL; + m_iconData = nullptr; m_iconSize = 0; - m_comparisonData = NULL; + m_comparisonData = nullptr; m_comparisonSize = 0; // 4J Stu - These calls need to be in the most derived version of the class @@ -41,7 +42,7 @@ void AbstractTexturePack::loadIcon() 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); UINT size = 0; @@ -57,7 +58,7 @@ void AbstractTexturePack::loadComparison() 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/DefaultPack_Comparison.png"); UINT size = 0; @@ -70,8 +71,8 @@ void AbstractTexturePack::loadDescription() { // 4J Unused currently #if 0 - InputStream *inputStream = NULL; - BufferedReader *br = NULL; + InputStream *inputStream = nullptr; + BufferedReader *br = nullptr; //try { inputStream = getResourceImplementation(L"/pack.txt"); br = new BufferedReader(new InputStreamReader(inputStream)); @@ -81,12 +82,12 @@ void AbstractTexturePack::loadDescription() //} finally { // TODO [EB]: use IOUtils.closeSilently() // try { - if (br != NULL) + if (br != nullptr) { br->close(); delete br; } - if (inputStream != NULL) + if (inputStream != nullptr) { inputStream->close(); delete inputStream; @@ -105,7 +106,7 @@ InputStream *AbstractTexturePack::getResource(const wstring &name, bool allowFal { app.DebugPrintf("texture - %ls\n",name.c_str()); InputStream *is = getResourceImplementation(name); - if (is == NULL && fallback != NULL && allowFallback) + if (is == nullptr && fallback != nullptr && allowFallback) { is = fallback->getResource(name, true); } @@ -121,7 +122,7 @@ InputStream *AbstractTexturePack::getResource(const wstring &name, bool allowFal void AbstractTexturePack::unload(Textures *textures) { - if (iconImage != NULL && textureId != -1) + if (iconImage != nullptr && textureId != -1) { textures->releaseTexture(textureId); } @@ -129,7 +130,7 @@ void AbstractTexturePack::unload(Textures *textures) void AbstractTexturePack::load(Textures *textures) { - if (iconImage != NULL) + if (iconImage != nullptr) { if (textureId == -1) { @@ -149,7 +150,7 @@ bool AbstractTexturePack::hasFile(const wstring &name, bool allowFallback) { bool hasFile = this->hasFile(name); - return !hasFile && (allowFallback && fallback != NULL) ? fallback->hasFile(name, allowFallback) : hasFile; + return !hasFile && (allowFallback && fallback != nullptr) ? fallback->hasFile(name, allowFallback) : hasFile; } DWORD AbstractTexturePack::getId() @@ -231,7 +232,7 @@ void AbstractTexturePack::loadDefaultUI() { #ifdef _XBOX // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); // Load new skin const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string @@ -240,7 +241,7 @@ void AbstractTexturePack::loadDefaultUI() swprintf(szResourceLocator, LOCATOR_SIZE,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/skin_Minecraft.xur"); XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); + app.LoadSkin(szResourceLocator,nullptr);//L"TexturePack"); //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); #else @@ -259,7 +260,7 @@ void AbstractTexturePack::loadDefaultColourTable() // Load the file #ifdef __PS3__ // need to check if it's a BD build, so pass in the name - File coloursFile(AbstractTexturePack::getPath(true,app.GetBootedFromDiscPatch()?"colours.col":NULL).append(L"res/colours.col")); + File coloursFile(AbstractTexturePack::getPath(true,app.GetBootedFromDiscPatch()?"colours.col":nullptr).append(L"res/colours.col")); #else File coloursFile(AbstractTexturePack::getPath(true).append(L"res/colours.col")); @@ -269,12 +270,12 @@ void AbstractTexturePack::loadDefaultColourTable() if(coloursFile.exists()) { DWORD dwLength = coloursFile.length(); - byteArray data(dwLength); + byteArray data(static_cast(dwLength)); FileInputStream fis(coloursFile); fis.read(data,0,dwLength); fis.close(); - if(m_colourTable != NULL) delete m_colourTable; + if(m_colourTable != nullptr) delete m_colourTable; m_colourTable = new ColourTable(data.data, dwLength); delete [] data.data; @@ -290,7 +291,7 @@ void AbstractTexturePack::loadDefaultHTMLColourTable() { #ifdef _XBOX // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; @@ -309,7 +310,7 @@ void AbstractTexturePack::loadDefaultHTMLColourTable() { wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,L"xuiscene_colourtable.xur", NULL, &hScene); + HRESULT hr = XuiSceneCreate(szResourceLocator,L"xuiscene_colourtable.xur", nullptr, &hScene); if(HRESULT_SUCCEEDED(hr)) { @@ -333,7 +334,7 @@ void AbstractTexturePack::loadHTMLColourTableFromXuiScene(HXUIOBJ hObj) HXUIOBJ child; HRESULT hr = XuiElementGetFirstChild(hObj, &child); - while(HRESULT_SUCCEEDED(hr) && child != NULL) + while(HRESULT_SUCCEEDED(hr) && child != nullptr) { LPCWSTR childName; XuiElementGetId(child,&childName); @@ -374,7 +375,7 @@ void AbstractTexturePack::unloadUI() wstring AbstractTexturePack::getXuiRootPath() { - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); // Load new skin const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string @@ -386,14 +387,14 @@ wstring AbstractTexturePack::getXuiRootPath() PBYTE AbstractTexturePack::getPackIcon(DWORD &dwImageBytes) { - if(m_iconSize == 0 || m_iconData == NULL) loadIcon(); + if(m_iconSize == 0 || m_iconData == nullptr) loadIcon(); dwImageBytes = m_iconSize; return m_iconData; } PBYTE AbstractTexturePack::getPackComparison(DWORD &dwImageBytes) { - if(m_comparisonSize == 0 || m_comparisonData == NULL) loadComparison(); + if(m_comparisonSize == 0 || m_comparisonData == nullptr) loadComparison(); dwImageBytes = m_comparisonSize; return m_comparisonData; diff --git a/Minecraft.Client/AbstractTexturePack.h b/Minecraft.Client/AbstractTexturePack.h index e6410c193..6386ecf1e 100644 --- a/Minecraft.Client/AbstractTexturePack.h +++ b/Minecraft.Client/AbstractTexturePack.h @@ -89,5 +89,5 @@ public: virtual unsigned int getDLCParentPackId(); virtual unsigned char getDLCSubPackId(); virtual ColourTable *getColourTable() { return m_colourTable; } - virtual ArchiveFile *getArchiveFile() { return NULL; } + virtual ArchiveFile *getArchiveFile() { return nullptr; } }; diff --git a/Minecraft.Client/AchievementPopup.cpp b/Minecraft.Client/AchievementPopup.cpp index 04f822aba..4e08f3b81 100644 --- a/Minecraft.Client/AchievementPopup.cpp +++ b/Minecraft.Client/AchievementPopup.cpp @@ -14,7 +14,7 @@ AchievementPopup::AchievementPopup(Minecraft *mc) // 4J - added initialisers width = 0; height = 0; - ach = NULL; + ach = nullptr; startTime = 0; isHelper = false; @@ -59,7 +59,7 @@ void AchievementPopup::prepareWindow() glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0, (float)width, (float)height, 0, 1000, 3000); + glOrtho(0, static_cast(width), static_cast(height), 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -2000); @@ -88,7 +88,7 @@ void AchievementPopup::render() glDepthMask(true); glEnable(GL_DEPTH_TEST); } - if (ach == NULL || startTime == 0) return; + if (ach == nullptr || startTime == 0) return; double time = (System::currentTimeMillis() - startTime) / 3000.0; if (isHelper) diff --git a/Minecraft.Client/AchievementScreen.cpp b/Minecraft.Client/AchievementScreen.cpp index 902aed174..baafce30a 100644 --- a/Minecraft.Client/AchievementScreen.cpp +++ b/Minecraft.Client/AchievementScreen.cpp @@ -52,7 +52,7 @@ void AchievementScreen::buttonClicked(Button *button) { if (button->id == 1) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft->grabMouse(); // 4J removed } Screen::buttonClicked(button); @@ -62,7 +62,7 @@ void AchievementScreen::keyPressed(char eventCharacter, int eventKey) { if (eventKey == minecraft->options->keyBuild->key) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft->grabMouse(); // 4J removed } else @@ -286,7 +286,7 @@ void AchievementScreen::renderBg(int xm, int ym, float a) vLine(x2, y1, y2, color); } - Achievement *hoveredAchievement = NULL; + Achievement *hoveredAchievement = nullptr; ItemRenderer *ir = new ItemRenderer(); glPushMatrix(); @@ -372,7 +372,7 @@ void AchievementScreen::renderBg(int xm, int ym, float a) glEnable(GL_TEXTURE_2D); Screen::render(xm, ym, a); - if (hoveredAchievement != NULL) + if (hoveredAchievement != nullptr) { Achievement *ach = hoveredAchievement; wstring name = ach->name; diff --git a/Minecraft.Client/ArchiveFile.cpp b/Minecraft.Client/ArchiveFile.cpp index 2e57a5bb7..608428b6e 100644 --- a/Minecraft.Client/ArchiveFile.cpp +++ b/Minecraft.Client/ArchiveFile.cpp @@ -30,7 +30,7 @@ void ArchiveFile::_readHeader(DataInputStream *dis) ArchiveFile::ArchiveFile(File file) { - m_cachedData = NULL; + m_cachedData = nullptr; m_sourcefile = file; app.DebugPrintf("Loading archive file...\n"); #ifndef _CONTENT_PACKAGE @@ -48,7 +48,7 @@ ArchiveFile::ArchiveFile(File file) FileInputStream fis(file); #if defined _XBOX_ONE || defined __ORBIS__ || defined _WINDOWS64 - byteArray readArray(file.length()); + byteArray readArray(static_cast(file.length())); fis.read(readArray,0,file.length()); ByteArrayInputStream bais(readArray); @@ -122,20 +122,20 @@ byteArray ArchiveFile::getFile(const wstring &filename) HANDLE hfile = CreateFile( m_sourcefile.getPath().c_str(), GENERIC_READ, 0, - NULL, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, - NULL + nullptr ); #else app.DebugPrintf("Createfile archive\n"); HANDLE hfile = CreateFile( wstringtofilename(m_sourcefile.getPath()), GENERIC_READ, 0, - NULL, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, - NULL + nullptr ); #endif @@ -144,7 +144,7 @@ byteArray ArchiveFile::getFile(const wstring &filename) app.DebugPrintf("hfile ok\n"); DWORD ok = SetFilePointer( hfile, data->ptr, - NULL, + nullptr, FILE_BEGIN ); @@ -157,7 +157,7 @@ byteArray ArchiveFile::getFile(const wstring &filename) (LPVOID) pbData, data->filesize, &bytesRead, - NULL + nullptr ); if(bSuccess==FALSE) @@ -182,7 +182,7 @@ byteArray ArchiveFile::getFile(const wstring &filename) #endif // Compressed filenames are preceeded with an asterisk. - if ( data->isCompressed && out.data != NULL ) + if ( data->isCompressed && out.data != nullptr ) { /* 4J-JEV: * If a compressed file is accessed before compression object is @@ -204,7 +204,7 @@ byteArray ArchiveFile::getFile(const wstring &filename) out.length = decompressedSize; } - assert(out.data != NULL); // THERE IS NO FILE WITH THIS NAME! + assert(out.data != nullptr); // THERE IS NO FILE WITH THIS NAME! } diff --git a/Minecraft.Client/ArrowRenderer.cpp b/Minecraft.Client/ArrowRenderer.cpp index 4698cd6e3..a7dd6efdd 100644 --- a/Minecraft.Client/ArrowRenderer.cpp +++ b/Minecraft.Client/ArrowRenderer.cpp @@ -23,7 +23,7 @@ void ArrowRenderer::render(shared_ptr _arrow, double x, double y, double if( ( xRot - xRotO ) > 180.0f ) xRot -= 360.0f; else if( ( xRot - xRotO ) < -180.0f ) xRot += 360.0f; - glTranslatef((float)x, (float)y, (float)z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glRotatef(yRotO + (yRot - yRotO) * a - 90, 0, 1, 0); glRotatef(xRotO + (xRot - xRotO) * a, 0, 0, 1); @@ -55,19 +55,19 @@ void ArrowRenderer::render(shared_ptr _arrow, double x, double y, double // glNormal3f(ss, 0, 0); // 4J - changed to use tesselator t->begin(); t->normal(1,0,0); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v12)); + t->vertexUV(static_cast(-7), static_cast(-2), static_cast(-2), (float)( u02), (float)( v02)); + t->vertexUV(static_cast(-7), static_cast(-2), static_cast(+2), (float)( u12), (float)( v02)); + t->vertexUV(static_cast(-7), static_cast(+2), static_cast(+2), (float)( u12), (float)( v12)); + t->vertexUV(static_cast(-7), static_cast(+2), static_cast(-2), (float)( u02), (float)( v12)); t->end(); // glNormal3f(-ss, 0, 0); // 4J - changed to use tesselator t->begin(); t->normal(-1,0,0); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v12)); + t->vertexUV(static_cast(-7), static_cast(+2), static_cast(-2), (float)( u02), (float)( v02)); + t->vertexUV(static_cast(-7), static_cast(+2), static_cast(+2), (float)( u12), (float)( v02)); + t->vertexUV(static_cast(-7), static_cast(-2), static_cast(+2), (float)( u12), (float)( v12)); + t->vertexUV(static_cast(-7), static_cast(-2), static_cast(-2), (float)( u02), (float)( v12)); t->end(); for (int i = 0; i < 4; i++) @@ -77,10 +77,10 @@ void ArrowRenderer::render(shared_ptr _arrow, double x, double y, double // glNormal3f(0, 0, ss); // 4J - changed to use tesselator t->begin(); t->normal(0,0,1); - t->vertexUV((float)(-8), (float)( -2), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+8), (float)( -2), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+8), (float)( +2), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-8), (float)( +2), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV(static_cast(-8), static_cast(-2), static_cast(0), (float)( u0), (float)( v0)); + t->vertexUV(static_cast(+8), static_cast(-2), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV(static_cast(+8), static_cast(+2), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV(static_cast(-8), static_cast(+2), static_cast(0), (float)( u0), (float)( v1)); t->end(); } glDisable(GL_RESCALE_NORMAL); diff --git a/Minecraft.Client/BatRenderer.cpp b/Minecraft.Client/BatRenderer.cpp index 629fe014a..97c6412d7 100644 --- a/Minecraft.Client/BatRenderer.cpp +++ b/Minecraft.Client/BatRenderer.cpp @@ -7,7 +7,7 @@ ResourceLocation BatRenderer::BAT_LOCATION = ResourceLocation(TN_MOB_BAT); BatRenderer::BatRenderer() : MobRenderer(new BatModel(), 0.25f) { - modelVersion = ((BatModel *)model)->modelVersion(); + modelVersion = static_cast(model)->modelVersion(); } void BatRenderer::render(shared_ptr _mob, double x, double y, double z, float rot, float a) diff --git a/Minecraft.Client/BlazeRenderer.cpp b/Minecraft.Client/BlazeRenderer.cpp index 8e0da036b..f8426a2f3 100644 --- a/Minecraft.Client/BlazeRenderer.cpp +++ b/Minecraft.Client/BlazeRenderer.cpp @@ -7,7 +7,7 @@ ResourceLocation BlazeRenderer::BLAZE_LOCATION = ResourceLocation(TN_MOB_BLAZE); BlazeRenderer::BlazeRenderer() : MobRenderer(new BlazeModel(), 0.5f) { - modelVersion = ((BlazeModel *) model)->modelVersion(); + modelVersion = static_cast(model)->modelVersion(); } void BlazeRenderer::render(shared_ptr _mob, double x, double y, double z, float rot, float a) @@ -16,7 +16,7 @@ void BlazeRenderer::render(shared_ptr _mob, double x, double y, double z // do some casting around instead shared_ptr mob = dynamic_pointer_cast(_mob); - int modelVersion = ((BlazeModel *) model)->modelVersion(); + int modelVersion = static_cast(model)->modelVersion(); if (modelVersion != this->modelVersion) { this->modelVersion = modelVersion; diff --git a/Minecraft.Client/BoatModel.cpp b/Minecraft.Client/BoatModel.cpp index d0d465e52..5a55e7e84 100644 --- a/Minecraft.Client/BoatModel.cpp +++ b/Minecraft.Client/BoatModel.cpp @@ -14,20 +14,20 @@ BoatModel::BoatModel() : Model() int h = 20; int yOff = 4; - cubes[0]->addBox((float)(-w / 2), (float)(-h / 2 + 2), -3, w, h - 4, 4, 0); - cubes[0]->setPos(0, (float)(0 + yOff), 0); + cubes[0]->addBox(static_cast(-w / 2), static_cast(-h / 2 + 2), -3, w, h - 4, 4, 0); + cubes[0]->setPos(0, static_cast(0 + yOff), 0); - cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); + cubes[1]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[1]->setPos(static_cast(-w / 2 + 1), static_cast(0 + yOff), 0); - cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); + cubes[2]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[2]->setPos(static_cast(+w / 2 - 1), static_cast(0 + yOff), 0); - cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); + cubes[3]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[3]->setPos(0, static_cast(0 + yOff), static_cast(-h / 2 + 1)); - cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); + cubes[4]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[4]->setPos(0, static_cast(0 + yOff), static_cast(+h / 2 - 1)); cubes[0]->xRot = PI / 2; cubes[1]->yRot = PI / 2 * 3; diff --git a/Minecraft.Client/BoatRenderer.cpp b/Minecraft.Client/BoatRenderer.cpp index 4c2e9baf9..c012168a4 100644 --- a/Minecraft.Client/BoatRenderer.cpp +++ b/Minecraft.Client/BoatRenderer.cpp @@ -20,7 +20,7 @@ void BoatRenderer::render(shared_ptr _boat, double x, double y, double z glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glRotatef(180-rot, 0, 1, 0); float hurt = boat->getHurtTime() - a; diff --git a/Minecraft.Client/BreakingItemParticle.cpp b/Minecraft.Client/BreakingItemParticle.cpp index 51b721f51..8842209b8 100644 --- a/Minecraft.Client/BreakingItemParticle.cpp +++ b/Minecraft.Client/BreakingItemParticle.cpp @@ -42,7 +42,7 @@ void BreakingItemParticle::render(Tesselator *t, float a, float xa, float ya, fl float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) + if (tex != nullptr) { u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); @@ -50,9 +50,9 @@ void BreakingItemParticle::render(Tesselator *t, float a, float xa, float ya, fl v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); float br = SharedConstants::TEXTURE_LIGHTING ? 1 : getBrightness(a); // 4J - change brought forward from 1.8.2 t->color(br * rCol, br * gCol, br * bCol); diff --git a/Minecraft.Client/BubbleParticle.cpp b/Minecraft.Client/BubbleParticle.cpp index 2d1380eb5..29dd12029 100644 --- a/Minecraft.Client/BubbleParticle.cpp +++ b/Minecraft.Client/BubbleParticle.cpp @@ -16,11 +16,11 @@ BubbleParticle::BubbleParticle(Level *level, double x, double y, double z, doubl size = size*(random->nextFloat()*0.6f+0.2f); - xd = xa*0.2f+(float)(Math::random()*2-1)*0.02f; - yd = ya*0.2f+(float)(Math::random()*2-1)*0.02f; - zd = za*0.2f+(float)(Math::random()*2-1)*0.02f; + xd = xa*0.2f+static_cast(Math::random() * 2 - 1)*0.02f; + yd = ya*0.2f+static_cast(Math::random() * 2 - 1)*0.02f; + zd = za*0.2f+static_cast(Math::random() * 2 - 1)*0.02f; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); } void BubbleParticle::tick() diff --git a/Minecraft.Client/BufferedImage.cpp b/Minecraft.Client/BufferedImage.cpp index 89e37e4f4..8777d307b 100644 --- a/Minecraft.Client/BufferedImage.cpp +++ b/Minecraft.Client/BufferedImage.cpp @@ -31,7 +31,7 @@ BufferedImage::BufferedImage(int width,int height,int type) for( int i = 1 ; i < 10; i++ ) { - data[i] = NULL; + data[i] = nullptr; } this->width = width; this->height = height; @@ -140,7 +140,7 @@ BufferedImage::BufferedImage(const wstring& File, bool filenameHasExtension /*=f for( int l = 0 ; l < 10; l++ ) { - data[l] = NULL; + data[l] = nullptr; } for( int l = 0; l < 10; l++ ) @@ -193,12 +193,12 @@ BufferedImage::BufferedImage(DLCPack *dlcPack, const wstring& File, bool filenam { HRESULT hr; wstring filePath = File; - BYTE *pbData = NULL; + BYTE *pbData = nullptr; DWORD dwBytes = 0; for( int l = 0 ; l < 10; l++ ) { - data[l] = NULL; + data[l] = nullptr; } for( int l = 0; l < 10; l++ ) @@ -230,7 +230,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) + if(pbData == nullptr || dwBytes == 0) { // 4J - If we haven't loaded the non-mipmap version then exit the game if( l == 0 ) @@ -269,7 +269,7 @@ BufferedImage::BufferedImage(BYTE *pbData, DWORD dwBytes) int iCurrentByte=0; for( int l = 0 ; l < 10; l++ ) { - data[l] = NULL; + data[l] = nullptr; } D3DXIMAGE_INFO ImageInfo; @@ -329,7 +329,7 @@ int *BufferedImage::getData(int level) Graphics *BufferedImage::getGraphics() { - return NULL; + return nullptr; } //Returns the transparency. Returns either OPAQUE, BITMASK, or TRANSLUCENT. @@ -359,7 +359,7 @@ BufferedImage *BufferedImage::getSubimage(int x ,int y, int w, int h) this->getRGB(x, y, w, h, arrayWrapper,0,w); int level = 1; - while(getData(level) != NULL) + while(getData(level) != nullptr) { int ww = w >> level; int hh = h >> level; @@ -391,9 +391,9 @@ void BufferedImage::preMultiplyAlpha() { cur = curData[i]; alpha = (cur >> 24) & 0xff; - r = ((cur >> 16) & 0xff) * (float)alpha/255; - g = ((cur >> 8) & 0xff) * (float)alpha/255; - b = (cur & 0xff) * (float)alpha/255; + r = ((cur >> 16) & 0xff) * static_cast(alpha)/255; + g = ((cur >> 8) & 0xff) * static_cast(alpha)/255; + b = (cur & 0xff) * static_cast(alpha)/255; curData[i] = (r << 16) | (g << 8) | (b ) | (alpha << 24); } diff --git a/Minecraft.Client/BufferedImage.h b/Minecraft.Client/BufferedImage.h index a0227fe29..3a08383fc 100644 --- a/Minecraft.Client/BufferedImage.h +++ b/Minecraft.Client/BufferedImage.h @@ -7,7 +7,7 @@ class DLCPack; class BufferedImage { private: - int *data[10]; // Arrays for mipmaps - NULL if not used + int *data[10]; // Arrays for mipmaps - nullptr if not used int width; int height; void ByteFlip4(unsigned int &data); // 4J added diff --git a/Minecraft.Client/ChatScreen.cpp b/Minecraft.Client/ChatScreen.cpp index 543cab76c..53c907224 100644 --- a/Minecraft.Client/ChatScreen.cpp +++ b/Minecraft.Client/ChatScreen.cpp @@ -87,7 +87,7 @@ void ChatScreen::keyPressed(wchar_t ch, int eventKey) { if (eventKey == Keyboard::KEY_ESCAPE) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); return; } if (eventKey == Keyboard::KEY_RETURN) @@ -108,7 +108,7 @@ void ChatScreen::keyPressed(wchar_t ch, int eventKey) s_chatHistory.erase(s_chatHistory.begin()); } } - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); return; } if (eventKey == Keyboard::KEY_UP) { handleHistoryUp(); return; } @@ -160,7 +160,7 @@ void ChatScreen::mouseClicked(int x, int y, int buttonNum) { if (buttonNum == 0) { - if (minecraft->gui->selectedName != L"") // 4J - was NULL comparison + if (minecraft->gui->selectedName != L"") // 4J - was nullptr comparison { if (message.length() > 0 && message[message.length()-1]!=L' ') { diff --git a/Minecraft.Client/ChestRenderer.cpp b/Minecraft.Client/ChestRenderer.cpp index 97954b55a..7d306f45d 100644 --- a/Minecraft.Client/ChestRenderer.cpp +++ b/Minecraft.Client/ChestRenderer.cpp @@ -52,19 +52,19 @@ void ChestRenderer::render(shared_ptr _chest, double x, double y, d Tile *tile = chest->getTile(); data = chest->getData(); - if (dynamic_cast(tile) != NULL && data == 0) + if (dynamic_cast(tile) != nullptr && data == 0) { - ((ChestTile *) tile)->recalcLockDir(chest->getLevel(), chest->x, chest->y, chest->z); + static_cast(tile)->recalcLockDir(chest->getLevel(), chest->x, chest->y, chest->z); data = chest->getData(); } chest->checkNeighbors(); } - if (chest->n.lock() != NULL || chest->w.lock() != NULL) return; + if (chest->n.lock() != nullptr || chest->w.lock() != nullptr) return; ChestModel *model; - if (chest->e.lock() != NULL || chest->s.lock() != NULL) + if (chest->e.lock() != nullptr || chest->s.lock() != nullptr) { model = largeChestModel; @@ -102,7 +102,7 @@ void ChestRenderer::render(shared_ptr _chest, double x, double y, d glEnable(GL_RESCALE_NORMAL); //if( setColor ) glColor4f(1, 1, 1, 1); if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); + glTranslatef(static_cast(x), static_cast(y) + 1, static_cast(z) + 1); glScalef(1, -1, -1); glTranslatef(0.5f, 0.5f, 0.5f); @@ -112,11 +112,11 @@ void ChestRenderer::render(shared_ptr _chest, double x, double y, d if (data == 4) rot = 90; if (data == 5) rot = -90; - if (data == 2 && chest->e.lock() != NULL) + if (data == 2 && chest->e.lock() != nullptr) { glTranslatef(1, 0, 0); } - if (data == 5 && chest->s.lock() != NULL) + if (data == 5 && chest->s.lock() != nullptr) { glTranslatef(0, 0, -1); } @@ -124,12 +124,12 @@ void ChestRenderer::render(shared_ptr _chest, double x, double y, d glTranslatef(-0.5f, -0.5f, -0.5f); float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; - if (chest->n.lock() != NULL) + if (chest->n.lock() != nullptr) { float open2 = chest->n.lock()->oOpenness + (chest->n.lock()->openness - chest->n.lock()->oOpenness) * a; if (open2 > open) open = open2; } - if (chest->w.lock() != NULL) + if (chest->w.lock() != nullptr) { float open2 = chest->w.lock()->oOpenness + (chest->w.lock()->openness - chest->w.lock()->oOpenness) * a; if (open2 > open) open = open2; diff --git a/Minecraft.Client/ChickenModel.cpp b/Minecraft.Client/ChickenModel.cpp index 98ef93587..14eb61270 100644 --- a/Minecraft.Client/ChickenModel.cpp +++ b/Minecraft.Client/ChickenModel.cpp @@ -8,35 +8,35 @@ ChickenModel::ChickenModel() : Model() int yo = 16; head = new ModelPart(this, 0, 0); head->addBox(-2.0f, -6.0f, -2.0f, 4, 6, 3, 0.0f); // Head - head->setPos(0, (float)(-1 + yo), -4); + head->setPos(0, static_cast(-1 + yo), -4); beak = new ModelPart(this, 14, 0); beak->addBox(-2.0f, -4.0f, -4.0f, 4, 2, 2, 0.0f); // Beak - beak->setPos(0, (float)(-1 + yo), -4); + beak->setPos(0, static_cast(-1 + yo), -4); redThing = new ModelPart(this, 14, 4); redThing->addBox(-1.0f, -2.0f, -3.0f, 2, 2, 2, 0.0f); // Beak - redThing->setPos(0, (float)(-1 + yo), -4); + redThing->setPos(0, static_cast(-1 + yo), -4); body = new ModelPart(this, 0, 9); body->addBox(-3.0f, -4.0f, -3.0f, 6, 8, 6, 0.0f); // Body - body->setPos(0, (float)(0 + yo), 0); + body->setPos(0, static_cast(0 + yo), 0); leg0 = new ModelPart(this, 26, 0); leg0->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg0 - leg0->setPos(-2, (float)(3 + yo), 1); + leg0->setPos(-2, static_cast(3 + yo), 1); leg1 = new ModelPart(this, 26, 0); leg1->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg1 - leg1->setPos(1, (float)(3 + yo), 1); + leg1->setPos(1, static_cast(3 + yo), 1); wing0 = new ModelPart(this, 24, 13); wing0->addBox(0.0f, 0.0f, -3.0f, 1, 4, 6); // Wing0 - wing0->setPos(-4, (float)(-3 + yo), 0); + wing0->setPos(-4, static_cast(-3 + yo), 0); wing1 = new ModelPart(this, 24, 13); wing1->addBox(-1.0f, 0.0f, -3.0f, 1, 4, 6); // Wing1 - wing1->setPos(4, (float)(-3 + yo), 0); + wing1->setPos(4, static_cast(-3 + yo), 0); // 4J added - compile now to avoid random performance hit first time cubes are rendered head->compile(1.0f/16.0f); diff --git a/Minecraft.Client/Chunk.cpp b/Minecraft.Client/Chunk.cpp index 850b79fb3..0a63b8747 100644 --- a/Minecraft.Client/Chunk.cpp +++ b/Minecraft.Client/Chunk.cpp @@ -32,13 +32,13 @@ void Chunk::CreateNewThreadStorage() void Chunk::ReleaseThreadStorage() { - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); + unsigned char *tileIds = static_cast(TlsGetValue(tlsIdx)); delete tileIds; } unsigned char *Chunk::GetTileIdsStorage() { - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); + unsigned char *tileIds = static_cast(TlsGetValue(tlsIdx)); return tileIds; } #else @@ -148,7 +148,7 @@ void Chunk::setPos(int x, int y, int z) void Chunk::translateToPos() { - glTranslatef((float)xRenderOffs, (float)yRenderOffs, (float)zRenderOffs); + glTranslatef(static_cast(xRenderOffs), static_cast(yRenderOffs), static_cast(zRenderOffs)); } @@ -173,7 +173,7 @@ void Chunk::makeCopyForRebuild(Chunk *source) this->ym = source->ym; this->zm = source->zm; this->bb = source->bb; - this->clipChunk = NULL; + this->clipChunk = nullptr; this->id = source->id; this->globalRenderableTileEntities = source->globalRenderableTileEntities; this->globalRenderableTileEntities_cs = source->globalRenderableTileEntities_cs; @@ -399,7 +399,7 @@ void Chunk::rebuild() glTranslatef(zs / 2.0f, ys / 2.0f, zs / 2.0f); #endif t->begin(); - t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); + t->offset(static_cast(-this->x), static_cast(-this->y), static_cast(-this->z)); } Tile *tile = Tile::tiles[tileId]; @@ -521,7 +521,7 @@ void Chunk::rebuild() else { // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) + for( size_t i = 0; i < renderableTileEntities.size(); i++ ) { (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); } @@ -680,7 +680,7 @@ void Chunk::rebuild_SPU() // 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. - ChunkRebuildData* pOutData = NULL; + ChunkRebuildData* pOutData = nullptr; g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); Tesselator::Bounds bounds; @@ -739,9 +739,9 @@ void Chunk::rebuild_SPU() { // 4J - get tile from those copied into our local array in earlier optimisation unsigned char tileId = pOutData->getTile(x,y,z); - if (tileId > 0) + if (tileId > 0 && tileId != 0xff) { - if (currentLayer == 0 && Tile::tiles[tileId]->isEntityTile()) + if (currentLayer == 0 && Tile::tiles[tileId] && Tile::tiles[tileId]->isEntityTile()) { shared_ptr et = region.getTileEntity(x, y, z); if (TileEntityRenderDispatcher::instance->hasRenderer(et)) @@ -754,6 +754,7 @@ void Chunk::rebuild_SPU() { Tile *tile = Tile::tiles[tileId]; + if (!tile) continue; int renderLayer = tile->getRenderLayer(); if (renderLayer != currentLayer) @@ -826,7 +827,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++ ) + for( size_t i = 0; i < renderableTileEntities.size(); i++ ) { auto it2 = find( it->second.begin(), it->second.end(), renderableTileEntities[i] ); if( it2 == it->second.end() ) @@ -842,7 +843,7 @@ void Chunk::rebuild_SPU() else { // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) + for( size_t i = 0; i < renderableTileEntities.size(); i++ ) { (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); } @@ -936,17 +937,17 @@ void Chunk::rebuild_SPU() float Chunk::distanceToSqr(shared_ptr player) const { - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym); - float zd = (float) (player->z - zm); + float xd = static_cast(player->x - xm); + float yd = static_cast(player->y - ym); + float zd = static_cast(player->z - zm); return xd * xd + yd * yd + zd * zd; } float Chunk::squishedDistanceToSqr(shared_ptr player) { - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym) * 2; - float zd = (float) (player->z - zm); + float xd = static_cast(player->x - xm); + float yd = static_cast(player->y - ym) * 2; + float zd = static_cast(player->z - zm); return xd * xd + yd * yd + zd * zd; } @@ -981,7 +982,7 @@ void Chunk::reset() void Chunk::_delete() { reset(); - level = NULL; + level = nullptr; } int Chunk::getList(int layer) diff --git a/Minecraft.Client/ClientConnection.cpp b/Minecraft.Client/ClientConnection.cpp index c9e7bac2c..325e949bb 100644 --- a/Minecraft.Client/ClientConnection.cpp +++ b/Minecraft.Client/ClientConnection.cpp @@ -95,7 +95,7 @@ ClientConnection::ClientConnection(Minecraft *minecraft, const wstring& ip, int } else { - connection = NULL; + connection = nullptr; delete socket; } #endif @@ -106,9 +106,9 @@ ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUs // 4J - added initiliasers random = new Random(); done = false; - level = NULL; + level = nullptr; started = false; - savedDataStorage = new SavedDataStorage(NULL); + savedDataStorage = new SavedDataStorage(nullptr); maxPlayers = 20; this->minecraft = minecraft; @@ -122,7 +122,7 @@ ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUs m_userIndex = iUserIndex; } - if( socket == NULL ) + if( socket == nullptr ) { socket = new Socket(); // 4J - Local connection } @@ -134,7 +134,7 @@ ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUs } else { - connection = NULL; + connection = nullptr; // TODO 4J Stu - This will cause issues since the session player owns the socket //delete socket; } @@ -142,8 +142,63 @@ ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUs deferredEntityLinkPackets = vector(); } +bool ClientConnection::isPrimaryConnection() const +{ + // On host, all connections are primary (server is authoritative). + // On non-host, only the primary pad processes shared entity state. + return g_NetworkManager.IsHost() || m_userIndex == ProfileManager.GetPrimaryPad(); +} + +ClientConnection* ClientConnection::findPrimaryConnection() const +{ + if (level == nullptr) return nullptr; + int primaryPad = ProfileManager.GetPrimaryPad(); + MultiPlayerLevel* mpLevel = (MultiPlayerLevel*)level; + for (ClientConnection* conn : mpLevel->connections) + { + if (conn != this && conn->m_userIndex == primaryPad) + return conn; + } + return nullptr; +} + +bool ClientConnection::shouldProcessForEntity(int entityId) const +{ + if (g_NetworkManager.IsHost()) return true; + if (m_userIndex == ProfileManager.GetPrimaryPad()) return true; + + ClientConnection* primary = findPrimaryConnection(); + if (primary == nullptr) return true; + return !primary->isTrackingEntity(entityId); +} + +bool ClientConnection::shouldProcessForPosition(int blockX, int blockZ) const +{ + if (g_NetworkManager.IsHost()) return true; + if (m_userIndex == ProfileManager.GetPrimaryPad()) return true; + + ClientConnection* primary = findPrimaryConnection(); + if (primary == nullptr) return true; + return !primary->m_visibleChunks.count(chunkKey(blockX >> 4, blockZ >> 4)); +} + +bool ClientConnection::anyOtherConnectionHasChunk(int x, int z) const +{ + if (level == nullptr) return false; + MultiPlayerLevel* mpLevel = (MultiPlayerLevel*)level; + int64_t key = chunkKey(x, z); + for (ClientConnection* conn : mpLevel->connections) + { + if (conn != this && conn->m_visibleChunks.count(key)) + return true; + } + return false; +} + ClientConnection::~ClientConnection() { + m_trackedEntityIds.clear(); + m_visibleChunks.clear(); delete connection; delete random; delete savedDataStorage; @@ -157,8 +212,8 @@ void ClientConnection::tick() INetworkPlayer *ClientConnection::getNetworkPlayer() { - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; + if( connection != nullptr && connection->getSocket() != nullptr) return connection->getSocket()->getPlayer(); + else return nullptr; } void ClientConnection::handleLogin(shared_ptr packet) @@ -167,7 +222,7 @@ void ClientConnection::handleLogin(shared_ptr packet) PlayerUID OnlineXuid; ProfileManager.GetXUID(m_userIndex,&OnlineXuid,true); // online xuid - MOJANG_DATA *pMojangData = NULL; + MOJANG_DATA *pMojangData = nullptr; if(!g_NetworkManager.IsLocalGame()) { @@ -208,7 +263,7 @@ void ClientConnection::handleLogin(shared_ptr packet) if(iUserID!=-1) { - BYTE *pBuffer=NULL; + BYTE *pBuffer=nullptr; DWORD dwSize=0; bool bRes; @@ -285,17 +340,17 @@ void ClientConnection::handleLogin(shared_ptr packet) Level *dimensionLevel = minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) + if( dimensionLevel == nullptr ) { level = new MultiPlayerLevel(this, new LevelSettings(packet->seed, GameType::byId(packet->gameType), false, false, packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); // 4J Stu - We want to share the SavedDataStorage between levels int otherDimensionId = packet->dimension == 0 ? -1 : 0; Level *activeLevel = minecraft->getLevel(otherDimensionId); - if( activeLevel != NULL ) + if( activeLevel != nullptr ) { // Don't need to delete it here as it belongs to a client connection while will delete it when it's done - //if( level->savedDataStorage != NULL ) delete level->savedDataStorage; + //if( level->savedDataStorage != nullptr ) delete level->savedDataStorage; level->savedDataStorage = activeLevel->savedDataStorage; } @@ -304,6 +359,10 @@ void ClientConnection::handleLogin(shared_ptr packet) level->isClientSide = true; minecraft->setLevel(level); } + else + { + level = (MultiPlayerLevel *)dimensionLevel; + } minecraft->player->setPlayerIndex( packet->m_playerIndex ); minecraft->player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); @@ -341,12 +400,12 @@ void ClientConnection::handleLogin(shared_ptr packet) level = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); shared_ptr player; - if(level==NULL) + if(level==nullptr) { int otherDimensionId = packet->dimension == 0 ? -1 : 0; MultiPlayerLevel *activeLevel = minecraft->getLevel(otherDimensionId); - if(activeLevel == NULL) + if(activeLevel == nullptr) { otherDimensionId = packet->dimension == 0 ? 1 : (packet->dimension == -1 ? 1 : -1); activeLevel = minecraft->getLevel(otherDimensionId); @@ -434,7 +493,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) shared_ptr owner = getEntity(packet->data); // 4J - check all local players to find match - if( owner == NULL ) + if( owner == nullptr ) { for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { @@ -450,10 +509,10 @@ void ClientConnection::handleAddEntity(shared_ptr packet) } } - if (owner != NULL && owner->instanceof(eTYPE_PLAYER)) + if (owner != nullptr && owner->instanceof(eTYPE_PLAYER)) { shared_ptr player = dynamic_pointer_cast(owner); - shared_ptr hook = shared_ptr( new FishingHook(level, x, y, z, player) ); + shared_ptr hook = std::make_shared(level, x, y, z, player); e = hook; // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' player->fishing = hook; @@ -462,10 +521,10 @@ void ClientConnection::handleAddEntity(shared_ptr packet) } break; case AddEntityPacket::ARROW: - e = shared_ptr( new Arrow(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::SNOWBALL: - e = shared_ptr( new Snowball(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::ITEM_FRAME: { @@ -474,64 +533,64 @@ void ClientConnection::handleAddEntity(shared_ptr packet) int iz = (int) z; app.DebugPrintf("ClientConnection ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); } - e = shared_ptr(new ItemFrame(level, (int) x, (int) y, (int) z, packet->data)); + e = std::make_shared(level, (int)x, (int)y, (int)z, packet->data); packet->data = 0; setRot = false; break; case AddEntityPacket::THROWN_ENDERPEARL: - e = shared_ptr( new ThrownEnderpearl(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::EYEOFENDERSIGNAL: - e = shared_ptr( new EyeOfEnderSignal(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::FIREBALL: - e = shared_ptr( new LargeFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); + e = std::make_shared(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); packet->data = 0; break; case AddEntityPacket::SMALL_FIREBALL: - e = shared_ptr( new SmallFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); + e = std::make_shared(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); packet->data = 0; break; case AddEntityPacket::DRAGON_FIRE_BALL: - e = shared_ptr( new DragonFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); + e = std::make_shared(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); packet->data = 0; break; case AddEntityPacket::EGG: - e = shared_ptr( new ThrownEgg(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::THROWN_POTION: - e = shared_ptr( new ThrownPotion(level, x, y, z, packet->data) ); + e = std::make_shared(level, x, y, z, packet->data); packet->data = 0; break; case AddEntityPacket::THROWN_EXPBOTTLE: - e = shared_ptr( new ThrownExpBottle(level, x, y, z) ); + e = std::make_shared(level, x, y, z); packet->data = 0; break; case AddEntityPacket::BOAT: - e = shared_ptr( new Boat(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::PRIMED_TNT: - e = shared_ptr( new PrimedTnt(level, x, y, z, nullptr) ); + e = std::make_shared(level, x, y, z, std::shared_ptr()); break; case AddEntityPacket::ENDER_CRYSTAL: - e = shared_ptr( new EnderCrystal(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::ITEM: - e = shared_ptr( new ItemEntity(level, x, y, z) ); + e = std::make_shared(level, x, y, z); break; case AddEntityPacket::FALLING: - e = shared_ptr( new FallingTile(level, x, y, z, packet->data & 0xFFFF, packet->data >> 16) ); + e = std::make_shared(level, x, y, z, packet->data & 0xFFFF, packet->data >> 16); packet->data = 0; break; case AddEntityPacket::WITHER_SKULL: - e = shared_ptr(new WitherSkull(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0)); + e = std::make_shared(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); packet->data = 0; break; case AddEntityPacket::FIREWORKS: - e = shared_ptr(new FireworksRocketEntity(level, x, y, z, nullptr)); + e = std::make_shared(level, x, y, z, std::shared_ptr()); break; case AddEntityPacket::LEASH_KNOT: - e = shared_ptr(new LeashFenceKnotEntity(level, (int) x, (int) y, (int) z)); + e = std::make_shared(level, (int)x, (int)y, (int)z); packet->data = 0; break; #ifndef _FINAL_BUILD @@ -550,7 +609,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) shared_ptr owner = getEntity(packet->data); // 4J - check all local players to find match - if( owner == NULL ) + if( owner == nullptr ) { for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { @@ -566,7 +625,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) } } shared_ptr player = dynamic_pointer_cast(owner); - if (player != NULL) + if (player != nullptr) { shared_ptr hook = shared_ptr( new FishingHook(level, x, y, z, player) ); e = hook; @@ -610,7 +669,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) */ - if (e != NULL) + if (e != nullptr) { e->xp = packet->x; e->yp = packet->y; @@ -653,6 +712,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) } e->entityId = packet->id; level->putEntity(packet->id, e); + m_trackedEntityIds.insert(packet->id); if (packet->data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 { @@ -662,7 +722,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) shared_ptr owner = getEntity(packet->data); // 4J - check all local players to find match - if( owner == NULL ) + if( owner == nullptr ) { for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { @@ -677,7 +737,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) } } - if ( owner != NULL && owner->instanceof(eTYPE_LIVINGENTITY) ) + if ( owner != nullptr && owner->instanceof(eTYPE_LIVINGENTITY) ) { dynamic_pointer_cast(e)->owner = dynamic_pointer_cast(owner); } @@ -693,7 +753,7 @@ void ClientConnection::handleAddEntity(shared_ptr packet) void ClientConnection::handleAddExperienceOrb(shared_ptr packet) { - shared_ptr e = shared_ptr( new ExperienceOrb(level, packet->x / 32.0, packet->y / 32.0, packet->z / 32.0, packet->value) ); + shared_ptr e = std::make_shared(level, packet->x / 32.0, packet->y / 32.0, packet->z / 32.0, packet->value); e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; @@ -701,16 +761,18 @@ void ClientConnection::handleAddExperienceOrb(shared_ptr e->xRot = 0; e->entityId = packet->id; level->putEntity(packet->id, e); + m_trackedEntityIds.insert(packet->id); } void ClientConnection::handleAddGlobalEntity(shared_ptr packet) { + if (!isPrimaryConnection()) return; double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; shared_ptr e;// = nullptr; - if (packet->type == AddGlobalEntityPacket::LIGHTNING) e = shared_ptr( new LightningBolt(level, x, y, z) ); - if (e != NULL) + if (packet->type == AddGlobalEntityPacket::LIGHTNING) e = std::make_shared(level, x, y, z); + if (e != nullptr) { e->xp = packet->x; e->yp = packet->y; @@ -724,21 +786,28 @@ void ClientConnection::handleAddGlobalEntity(shared_ptr p void ClientConnection::handleAddPainting(shared_ptr packet) { - shared_ptr painting = shared_ptr( new Painting(level, packet->x, packet->y, packet->z, packet->dir, packet->motive) ); + shared_ptr painting = std::make_shared(level, packet->x, packet->y, packet->z, packet->dir, packet->motive); level->putEntity(packet->id, painting); + m_trackedEntityIds.insert(packet->id); } void ClientConnection::handleSetEntityMotion(shared_ptr packet) { + if (!shouldProcessForEntity(packet->id)) + { + if (minecraft->localplayers[m_userIndex] == NULL || + packet->id != minecraft->localplayers[m_userIndex]->entityId) + return; + } shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); } void ClientConnection::handleSetEntityData(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e != NULL && packet->getUnpackedData() != NULL) + if (e != nullptr && packet->getUnpackedData() != nullptr) { e->getEntityData()->assignValues(packet->getUnpackedData()); } @@ -765,7 +834,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) // a duplicate remote player for a local slot by checking the username directly. for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if (minecraft->localplayers[idx] != NULL && minecraft->localplayers[idx]->name == packet->name) + if (minecraft->localplayers[idx] != nullptr && minecraft->localplayers[idx]->name == packet->name) { app.DebugPrintf("AddPlayerPacket received for local player name %ls\n", packet->name.c_str()); return; @@ -779,7 +848,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) // their stored server index rather than using it directly as an array subscript. for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(minecraft->localplayers[idx] != NULL && + if(minecraft->localplayers[idx] != nullptr && minecraft->localplayers[idx]->getPlayerIndex() == packet->m_playerIndex) { app.DebugPrintf("AddPlayerPacket received for local player (controller %d, server index %d), skipping RemotePlayer creation\n", idx, packet->m_playerIndex); @@ -793,7 +862,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) double z = packet->z / 32.0; float yRot = packet->yRot * 360 / 256.0f; float xRot = packet->xRot * 360 / 256.0f; - shared_ptr player = shared_ptr( new RemotePlayer(minecraft->level, packet->name) ); + shared_ptr player = std::make_shared(minecraft->level, packet->name); player->xo = player->xOld = player->xp = packet->x; player->yo = player->yOld = player->yp = packet->y; player->zo = player->zOld = player->zp = packet->z; @@ -805,7 +874,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) #ifdef _DURANGO // On Durango request player display name from network manager INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerByXuid(player->getXuid()); - if (networkPlayer != NULL) player->m_displayName = networkPlayer->GetDisplayName(); + if (networkPlayer != nullptr) player->m_displayName = networkPlayer->GetDisplayName(); #else // On all other platforms display name is just gamertag so don't check with the network manager player->m_displayName = player->getName(); @@ -813,7 +882,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) #ifdef _WINDOWS64 { - IQNetPlayer* matchedQNetPlayer = NULL; + IQNetPlayer* matchedQNetPlayer = nullptr; PlayerUID pktXuid = player->getXuid(); const PlayerUID WIN64_XUID_BASE = (PlayerUID)0xe000d45248242f2e; // Legacy compatibility path for peers still using embedded smallId XUIDs. @@ -821,7 +890,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) { BYTE smallId = (BYTE)(pktXuid - WIN64_XUID_BASE); INetworkPlayer* np = g_NetworkManager.GetPlayerBySmallId(smallId); - if (np != NULL) + if (np != nullptr) { NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np; matchedQNetPlayer = npx->GetQNetPlayer(); @@ -829,18 +898,18 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) } // Current Win64 path: identify QNet player by name and attach packet XUID. - if (matchedQNetPlayer == NULL) + if (matchedQNetPlayer == nullptr) { for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { BYTE smallId = static_cast(i); INetworkPlayer* np = g_NetworkManager.GetPlayerBySmallId(smallId); - if (np == NULL) + if (np == nullptr) continue; NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np; IQNetPlayer* qp = npx->GetQNetPlayer(); - if (qp != NULL && _wcsicmp(qp->m_gamertag, packet->name.c_str()) == 0) + if (qp != nullptr && _wcsicmp(qp->m_gamertag, packet->name.c_str()) == 0) { matchedQNetPlayer = qp; break; @@ -848,7 +917,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) } } - if (matchedQNetPlayer != NULL) + if (matchedQNetPlayer != nullptr) { // Store packet-authoritative XUID on this network slot so later lookups by XUID // (e.g. remove player, display mapping) work for both legacy and uid.dat clients. @@ -866,11 +935,11 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) int item = packet->carriedItem; if (item == 0) { - player->inventory->items[player->inventory->selected] = shared_ptr(); // NULL; + player->inventory->items[player->inventory->selected] = shared_ptr(); // nullptr; } else { - player->inventory->items[player->inventory->selected] = shared_ptr( new ItemInstance(item, 1, 0) ); + player->inventory->items[player->inventory->selected] = std::make_shared(item, 1, 0); } player->absMoveTo(x, y, z, yRot, xRot); @@ -879,19 +948,22 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) 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) ) - { - app.DebugPrintf("Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + if (!player->customTextureUrl.empty() && player->customTextureUrl.substr(0, 3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) + { + if (minecraft->addPendingClientTextureRequest(player->customTextureUrl)) + { + app.DebugPrintf("Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n", player->customTextureUrl.c_str(), player->name.c_str()); - send(shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); - } - } + send(std::make_shared( + player->customTextureUrl, + nullptr, + static_cast(0))); + } + } else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); + app.AddMemoryTextureFile(player->customTextureUrl,nullptr,0); } app.DebugPrintf("Custom skin for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl.c_str()); @@ -901,21 +973,26 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) if( minecraft->addPendingClientTextureRequest(player->customTextureUrl2) ) { app.DebugPrintf("Client sending texture packet to get custom cape %ls for player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); - send(shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); + send(std::make_shared( + player->customTextureUrl2, + nullptr, + static_cast(0) + )); } } else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); + app.AddMemoryTextureFile(player->customTextureUrl2,nullptr,0); } app.DebugPrintf("Custom cape for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl2.c_str()); level->putEntity(packet->id, player); + m_trackedEntityIds.insert(packet->id); vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) + if (unpackedData != nullptr) { player->getEntityData()->assignValues(unpackedData); } @@ -925,7 +1002,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) void ClientConnection::handleTeleportEntity(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; @@ -953,8 +1030,9 @@ void ClientConnection::handleSetCarriedItem(shared_ptr pac void ClientConnection::handleMoveEntity(shared_ptr packet) { + if (!shouldProcessForEntity(packet->id)) return; shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; @@ -975,15 +1053,16 @@ void ClientConnection::handleMoveEntity(shared_ptr packet) void ClientConnection::handleRotateMob(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; float yHeadRot = packet->yHeadRot * 360 / 256.f; e->setYHeadRot(yHeadRot); } void ClientConnection::handleMoveEntitySmall(shared_ptr packet) { + if (!shouldProcessForEntity(packet->id)) return; shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; @@ -1009,18 +1088,18 @@ void ClientConnection::handleRemoveEntity(shared_ptr packe for (int i = 0; i < packet->ids.length; i++) { shared_ptr entity = getEntity(packet->ids[i]); - if (entity != NULL && entity->GetType() == eTYPE_PLAYER) + if (entity != nullptr && entity->GetType() == eTYPE_PLAYER) { shared_ptr player = dynamic_pointer_cast(entity); - if (player != NULL) + if (player != nullptr) { PlayerUID xuid = player->getXuid(); INetworkPlayer* np = g_NetworkManager.GetPlayerByXuid(xuid); - if (np != NULL) + if (np != nullptr) { NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np; IQNetPlayer* qp = npx->GetQNetPlayer(); - if (qp != NULL) + if (qp != nullptr) { extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; g_pPlatformNetworkManager->NotifyPlayerLeaving(qp); @@ -1040,6 +1119,7 @@ void ClientConnection::handleRemoveEntity(shared_ptr packe #endif for (int i = 0; i < packet->ids.length; i++) { + m_trackedEntityIds.erase(packet->ids[i]); level->removeEntity(packet->ids[i]); } } @@ -1090,7 +1170,7 @@ void ClientConnection::handleMovePlayer(shared_ptr packet) player->zOld = player->z; started = true; - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // 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 @@ -1106,14 +1186,33 @@ void ClientConnection::handleMovePlayer(shared_ptr packet) // 4J Added void ClientConnection::handleChunkVisibilityArea(shared_ptr packet) { + if (level == NULL) return; for(int z = packet->m_minZ; z <= packet->m_maxZ; ++z) + { for(int x = packet->m_minX; x <= packet->m_maxX; ++x) + { + m_visibleChunks.insert(chunkKey(x, z)); level->setChunkVisible(x, z, true); + } + } } void ClientConnection::handleChunkVisibility(shared_ptr packet) { - level->setChunkVisible(packet->x, packet->z, packet->visible); + if (level == NULL) return; + if (packet->visible) + { + m_visibleChunks.insert(chunkKey(packet->x, packet->z)); + level->setChunkVisible(packet->x, packet->z, true); + } + else + { + m_visibleChunks.erase(chunkKey(packet->x, packet->z)); + if (!anyOtherConnectionHasChunk(packet->x, packet->z)) + { + level->setChunkVisible(packet->x, packet->z, false); + } + } } void ClientConnection::handleChunkTilesUpdate(shared_ptr packet) @@ -1193,10 +1292,22 @@ void ClientConnection::handleBlockRegionUpdate(shared_ptrbIsFullChunk && packet->ys == 0) + { + app.DebugPrintf("[BRUP-CLIENT] *** EMPTY FULL CHUNK received at (%d,%d)! Buffer length=%d\n", + packet->x>>4, packet->z>>4, packet->buffer.length); + } + int y1 = packet->y + packet->ys; if(packet->bIsFullChunk) { y1 = Level::maxBuildHeight; + + // Ensure the chunk exists in the cache before writing data. + // The ChunkVisibilityAreaPacket that creates chunks can arrive AFTER the first BRUP, + // causing getChunk() to return EmptyLevelChunk (whose setBlocksAndData is a no-op). + dimensionLevel->setChunkVisible(packet->x >> 4, packet->z >> 4, true); + if(packet->buffer.length > 0) { PIXBeginNamedEvent(0, "Reordering to XZY"); @@ -1300,7 +1411,7 @@ void ClientConnection::handleDisconnect(shared_ptr packet) app.SetDisconnectReason( packet->reason ); app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); - //minecraft->setLevel(NULL); + //minecraft->setLevel(nullptr); //minecraft->setScreen(new DisconnectedScreen(L"disconnect.disconnected", L"disconnect.genericReason", &packet->reason)); } @@ -1323,14 +1434,14 @@ void ClientConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, ProfileManager.GetPrimaryPad(),&ClientConnection::HostDisconnectReturned,NULL); + ui.RequestErrorMessage(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, ProfileManager.GetPrimaryPad(),&ClientConnection::HostDisconnectReturned,nullptr); } else { app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); } - //minecraft->setLevel(NULL); + //minecraft->setLevel(nullptr); //minecraft->setScreen(new DisconnectedScreen(L"disconnect.lost", reason, reasonObjects)); } @@ -1349,6 +1460,7 @@ void ClientConnection::send(shared_ptr packet) void ClientConnection::handleTakeItemEntity(shared_ptr packet) { + if (!shouldProcessForEntity(packet->itemId)) return; shared_ptr from = getEntity(packet->itemId); shared_ptr to = dynamic_pointer_cast(getEntity(packet->playerId)); @@ -1368,7 +1480,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr pac } } - if (to == NULL) + if (to == nullptr) { // Don't know if this should ever really happen, but seems safest to try and remove the entity that has been collected even if we can't // create a particle as we don't know what really collected it @@ -1376,7 +1488,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr pac return; } - if (from != NULL) + if (from != nullptr) { // 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 @@ -1390,7 +1502,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr pac // the tutorial for the player that actually picked up the item int playerPad = player->GetXboxPad(); - if( minecraft->localgameModes[playerPad] != NULL ) + if( minecraft->localgameModes[playerPad] != nullptr ) { // 4J-PB - add in the XP orb sound if(from->GetType() == eTYPE_EXPERIENCEORB) @@ -1404,7 +1516,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr pac level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); } - minecraft->particleEngine->add( shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); + minecraft->particleEngine->add(std::make_shared(minecraft->level, from, to, -0.5f)); level->removeEntity(packet->itemId); } else @@ -1417,7 +1529,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr pac else { level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - minecraft->particleEngine->add( shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); + minecraft->particleEngine->add(std::make_shared(minecraft->level, from, to, -0.5f)); level->removeEntity(packet->itemId); } } @@ -1835,7 +1947,7 @@ void ClientConnection::handleChat(shared_ptr packet) void ClientConnection::handleAnimate(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; if (packet->action == AnimatePacket::SWING) { if (e->instanceof(eTYPE_LIVINGENTITY)) dynamic_pointer_cast(e)->swing(); @@ -1853,13 +1965,13 @@ void ClientConnection::handleAnimate(shared_ptr packet) } else if (packet->action == AnimatePacket::CRITICAL_HIT) { - shared_ptr critParticle = shared_ptr( new CritParticle(minecraft->level, e) ); + shared_ptr critParticle = std::make_shared(minecraft->level, e); critParticle->CritParticlePostConstructor(); minecraft->particleEngine->add( critParticle ); } else if (packet->action == AnimatePacket::MAGIC_CRITICAL_HIT) { - shared_ptr critParticle = shared_ptr( new CritParticle(minecraft->level, e, eParticleType_magicCrit) ); + shared_ptr critParticle = std::make_shared(minecraft->level, e, eParticleType_magicCrit); critParticle->CritParticlePostConstructor(); minecraft->particleEngine->add(critParticle); } @@ -1872,7 +1984,7 @@ void ClientConnection::handleAnimate(shared_ptr packet) void ClientConnection::handleEntityActionAtPosition(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; if (packet->action == EntityActionAtPositionPacket::START_SLEEP) { shared_ptr player = dynamic_pointer_cast(e); @@ -1932,7 +2044,7 @@ void ClientConnection::handlePreLogin(shared_ptr packet) // Is this user friends with the host player? BOOL result; DWORD error; - error = XUserAreUsersFriends(idx,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); + error = XUserAreUsersFriends(idx,&packet->m_playerXuids[packet->m_hostIndex],1,&result,nullptr); if(error == ERROR_SUCCESS && result != TRUE) { canPlay = FALSE; @@ -1962,7 +2074,7 @@ void ClientConnection::handlePreLogin(shared_ptr packet) // 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); + error = XUserAreUsersFriends(m_userIndex,&packet->m_playerXuids[packet->m_hostIndex],1,&result,nullptr); if(error == ERROR_SUCCESS && result != TRUE) { canPlay = FALSE; @@ -2014,7 +2126,7 @@ void ClientConnection::handlePreLogin(shared_ptr packet) { if( ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) { - error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); + error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,nullptr); if(error == ERROR_SUCCESS && result == TRUE) isAtLeastOneFriend = TRUE; } } @@ -2042,7 +2154,7 @@ void ClientConnection::handlePreLogin(shared_ptr packet) { if( (!thisQuadrantOnly || m_userIndex == idx) && ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) { - error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); + error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,nullptr); if(error == ERROR_SUCCESS) canPlay &= result; } if(!canPlay) break; @@ -2065,7 +2177,7 @@ void ClientConnection::handlePreLogin(shared_ptr packet) { bool bChatRestricted=false; - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,nullptr,nullptr); // Chat restricted orbis players can still play online #ifndef __ORBIS__ @@ -2154,11 +2266,11 @@ void ClientConnection::handlePreLogin(shared_ptr packet) // which seems to be very unstable at the point of starting up the game if(m_userIndex == ProfileManager.GetPrimaryPad()) { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,false,&bChatRestricted,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(m_userIndex,false,&bChatRestricted,&bContentRestricted,nullptr); } else { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,&bContentRestricted,nullptr); } // Chat restricted orbis players can still play online @@ -2331,8 +2443,8 @@ void ClientConnection::handlePreLogin(shared_ptr packet) } BOOL allAllowed, friendsAllowed; ProfileManager.AllowedPlayerCreatedContent(m_userIndex,true,&allAllowed,&friendsAllowed); - send( shared_ptr( 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 )))); + send(std::make_shared(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() ) { @@ -2368,6 +2480,8 @@ void ClientConnection::close() // If it's already done, then we don't need to do anything here. And in fact trying to do something could cause a crash if(done) return; done = true; + m_trackedEntityIds.clear(); + m_visibleChunks.clear(); connection->flush(); connection->close(DisconnectPacket::eDisconnect_Closed); } @@ -2407,9 +2521,10 @@ void ClientConnection::handleAddMob(shared_ptr packet) mob->yd = packet->yd / 8000.0f; mob->zd = packet->zd / 8000.0f; level->putEntity(packet->id, mob); + m_trackedEntityIds.insert(packet->id); vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) + if (unpackedData != nullptr) { mob->getEntityData()->assignValues(unpackedData); } @@ -2444,10 +2559,10 @@ void ClientConnection::handleEntityLinkPacket(shared_ptr pa // 4J: If the destination entity couldn't be found, defer handling of this packet // This was added to support leashing (the entity link packet is sent before the add entity packet) - if (destEntity == NULL && packet->destId >= 0) + if (destEntity == nullptr && packet->destId >= 0) { // We don't handle missing source entities because it shouldn't happen - assert(!(sourceEntity == NULL && packet->sourceId >= 0)); + assert(!(sourceEntity == nullptr && packet->sourceId >= 0)); deferredEntityLinkPackets.push_back(DeferredEntityLinkPacket(packet)); return; @@ -2460,16 +2575,16 @@ void ClientConnection::handleEntityLinkPacket(shared_ptr pa { sourceEntity = Minecraft::GetInstance()->localplayers[m_userIndex]; - if (destEntity != NULL && destEntity->instanceof(eTYPE_BOAT)) (dynamic_pointer_cast(destEntity))->setDoLerp(false); + if (destEntity != nullptr && destEntity->instanceof(eTYPE_BOAT)) (dynamic_pointer_cast(destEntity))->setDoLerp(false); - displayMountMessage = (sourceEntity->riding == NULL && destEntity != NULL); + displayMountMessage = (sourceEntity->riding == nullptr && destEntity != nullptr); } - else if (destEntity != NULL && destEntity->instanceof(eTYPE_BOAT)) + else if (destEntity != nullptr && destEntity->instanceof(eTYPE_BOAT)) { (dynamic_pointer_cast(destEntity))->setDoLerp(true); } - if (sourceEntity == NULL) return; + if (sourceEntity == nullptr) return; sourceEntity->ride(destEntity); @@ -2483,9 +2598,9 @@ void ClientConnection::handleEntityLinkPacket(shared_ptr pa } else if (packet->type == SetEntityLinkPacket::LEASH) { - if ( (sourceEntity != NULL) && sourceEntity->instanceof(eTYPE_MOB) ) + if ( (sourceEntity != nullptr) && sourceEntity->instanceof(eTYPE_MOB) ) { - if (destEntity != NULL) + if (destEntity != nullptr) { (dynamic_pointer_cast(sourceEntity))->setLeashedTo(destEntity, false); @@ -2501,7 +2616,7 @@ void ClientConnection::handleEntityLinkPacket(shared_ptr pa void ClientConnection::handleEntityEvent(shared_ptr packet) { shared_ptr e = getEntity(packet->entityId); - if (e != NULL) e->handleEntityEvent(packet->eventId); + if (e != nullptr) e->handleEntityEvent(packet->eventId); } shared_ptr ClientConnection::getEntity(int entityId) @@ -2525,7 +2640,7 @@ void ClientConnection::handleSetHealth(shared_ptr packet) // We need food if(packet->food < FoodConstants::HEAL_LEVEL - 1) { - if(minecraft->localgameModes[m_userIndex] != NULL && !minecraft->localgameModes[m_userIndex]->hasInfiniteItems() ) + if(minecraft->localgameModes[m_userIndex] != nullptr && !minecraft->localgameModes[m_userIndex]->hasInfiniteItems() ) { minecraft->localgameModes[m_userIndex]->getTutorial()->changeTutorialState(e_Tutorial_State_Food_Bar); } @@ -2549,13 +2664,13 @@ void ClientConnection::handleTexture(shared_ptr packet) #ifndef _CONTENT_PACKAGE wprintf(L"Client received request for custom texture %ls\n",packet->textureName.c_str()); #endif - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); if(dwBytes!=0) { - send( shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); + send(std::make_shared(packet->textureName, pbData, dwBytes)); } } else @@ -2581,7 +2696,7 @@ void ClientConnection::handleTextureAndGeometry(shared_ptrtextureName.c_str()); #endif - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); @@ -2592,18 +2707,18 @@ void ClientConnection::handleTextureAndGeometry(shared_ptrgetAdditionalBoxesCount()!=0) { - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,pDLCSkinFile) ) ); + send(std::make_shared(packet->textureName, pbData, dwBytes, pDLCSkinFile)); } else { - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes) ) ); + send(std::make_shared(packet->textureName, pbData, dwBytes)); } } else { unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,app.GetAdditionalSkinBoxes(packet->dwSkinID),uiAnimOverrideBitmask) ) ); + send(std::make_shared(packet->textureName, pbData, dwBytes, app.GetAdditionalSkinBoxes(packet->dwSkinID), uiAnimOverrideBitmask)); } } } @@ -2631,7 +2746,7 @@ void ClientConnection::handleTextureAndGeometry(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if ( (e == NULL) || !e->instanceof(eTYPE_PLAYER) ) return; + if ( (e == nullptr) || !e->instanceof(eTYPE_PLAYER) ) return; shared_ptr player = dynamic_pointer_cast(e); bool isLocalPlayer = false; @@ -2672,22 +2787,25 @@ void ClientConnection::handleTextureChange(shared_ptr packe #ifndef _CONTENT_PACKAGE wprintf(L"handleTextureChange - Client sending texture packet to get custom skin %ls for player %ls\n",packet->path.c_str(), player->name.c_str()); #endif - send(shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); + send(std::make_shared( + player->customTextureUrl, + nullptr, + static_cast(0))); } } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); + app.AddMemoryTextureFile(packet->path,nullptr,0); } } void ClientConnection::handleTextureAndGeometryChange(shared_ptr packet) { shared_ptr e = getEntity(packet->id); - if (e == NULL) return; + if (e == nullptr) return; shared_ptr player = dynamic_pointer_cast(e); - if( e == NULL) return; + if( e == nullptr) return; bool isLocalPlayer = false; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) @@ -2717,13 +2835,16 @@ void ClientConnection::handleTextureAndGeometryChange(shared_ptrpath.c_str(), player->name.c_str()); #endif - send(shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); + send(std::make_shared( + packet->path, + nullptr, + static_cast(0))); } } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); + app.AddMemoryTextureFile(packet->path,nullptr,0); } } @@ -2740,16 +2861,19 @@ void ClientConnection::handleRespawn(shared_ptr packet) // so it doesn't leak into the new dimension level->playStreamingMusic(L"", 0, 0, 0); + m_trackedEntityIds.clear(); + m_visibleChunks.clear(); + // Remove client connection from this level level->removeClientConnection(this, false); MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) + if( dimensionLevel == nullptr ) { dimensionLevel = new MultiPlayerLevel(this, new LevelSettings(packet->mapSeed, packet->playerGameType, false, minecraft->level->getLevelData()->isHardcore(), packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); // 4J Stu - We want to shared the savedDataStorage between both levels - //if( dimensionLevel->savedDataStorage != NULL ) + //if( dimensionLevel->savedDataStorage != nullptr ) //{ // Don't need to delete it here as it belongs to a client connection while will delete it when it's done // delete dimensionLevel->savedDataStorage;+ @@ -2789,7 +2913,7 @@ void ClientConnection::handleRespawn(shared_ptr packet) 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()); #endif - if( minecraft->localgameModes[m_userIndex] != NULL ) + if( minecraft->localgameModes[m_userIndex] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_userIndex]; gameMode->getTutorial()->showTutorialPopup(false); @@ -2847,31 +2971,33 @@ void ClientConnection::handleRespawn(shared_ptr packet) void ClientConnection::handleExplosion(shared_ptr packet) { - if(!packet->m_bKnockbackOnly) + if (shouldProcessForPosition((int)packet->x, (int)packet->z)) { - //app.DebugPrintf("Received ExplodePacket with explosion data\n"); - PIXBeginNamedEvent(0,"Handling explosion"); - Explosion *e = new Explosion(minecraft->level, nullptr, packet->x, packet->y, packet->z, packet->r); - PIXBeginNamedEvent(0,"Finalizing"); + if(!packet->m_bKnockbackOnly) + { + //app.DebugPrintf("Received ExplodePacket with explosion data\n"); + PIXBeginNamedEvent(0,"Handling explosion"); + Explosion *e = new Explosion(minecraft->level, nullptr, packet->x, packet->y, packet->z, packet->r); + PIXBeginNamedEvent(0,"Finalizing"); - // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: Gameplay: After detonating bunch of TNT, game enters unresponsive state for couple of seconds. - // The changes we are making here have been decided by the server, so we don't need to add them to the vector that resets tiles changes made - // on the client as we KNOW that the server is matching these changes - 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); - mpLevel->enableResetChanges(true); - PIXEndNamedEvent(); - PIXEndNamedEvent(); - delete e; - } - else - { - //app.DebugPrintf("Received ExplodePacket with knockback only data\n"); + // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: Gameplay: After detonating bunch of TNT, game enters unresponsive state for couple of seconds. + // The changes we are making here have been decided by the server, so we don't need to add them to the vector that resets tiles changes made + // on the client as we KNOW that the server is matching these changes + 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); + mpLevel->enableResetChanges(true); + PIXEndNamedEvent(); + PIXEndNamedEvent(); + delete e; + } } + // Per-player knockback — each connection applies to its own local player //app.DebugPrintf("Adding knockback (%f,%f,%f) for player %d\n", packet->getKnockbackX(), packet->getKnockbackY(), packet->getKnockbackZ(), m_userIndex); + if (minecraft->localplayers[m_userIndex] == NULL) + return; minecraft->localplayers[m_userIndex]->xd += packet->getKnockbackX(); minecraft->localplayers[m_userIndex]->yd += packet->getKnockbackY(); minecraft->localplayers[m_userIndex]->zd += packet->getKnockbackZ(); @@ -2881,6 +3007,8 @@ void ClientConnection::handleContainerOpen(shared_ptr packe { bool failed = false; shared_ptr player = minecraft->localplayers[m_userIndex]; + if (player == NULL) + return; switch(packet->type) { case ContainerOpenPacket::BONUS_CHEST: @@ -2900,7 +3028,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe default: assert(false); chestString = -1; break; } - if( player->openContainer(shared_ptr( new SimpleContainer(chestString, packet->title, packet->customName, packet->size) ))) + if( player->openContainer(std::make_shared(chestString, packet->title, packet->customName, packet->size))) { player->containerMenu->containerId = packet->containerId; } @@ -2912,7 +3040,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::HOPPER: { - shared_ptr hopper = shared_ptr(new HopperTileEntity()); + shared_ptr hopper = std::make_shared(); if (packet->customName) hopper->setCustomName(packet->title); if(player->openHopper(hopper)) { @@ -2926,7 +3054,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::FURNACE: { - shared_ptr furnace = shared_ptr(new FurnaceTileEntity()); + shared_ptr furnace = std::make_shared(); if (packet->customName) furnace->setCustomName(packet->title); if(player->openFurnace(furnace)) { @@ -2940,7 +3068,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::BREWING_STAND: { - shared_ptr brewingStand = shared_ptr(new BrewingStandTileEntity()); + shared_ptr brewingStand = std::make_shared(); if (packet->customName) brewingStand->setCustomName(packet->title); if( player->openBrewingStand(brewingStand)) @@ -2955,7 +3083,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::DROPPER: { - shared_ptr dropper = shared_ptr(new DropperTileEntity()); + shared_ptr dropper = std::make_shared(); if (packet->customName) dropper->setCustomName(packet->title); if( player->openTrap(dropper)) @@ -2970,7 +3098,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::TRAP: { - shared_ptr dispenser = shared_ptr(new DispenserTileEntity()); + shared_ptr dispenser = std::make_shared(); if (packet->customName) dispenser->setCustomName(packet->title); if( player->openTrap(dispenser)) @@ -3009,7 +3137,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::TRADER_NPC: { - shared_ptr csm = shared_ptr(new ClientSideMerchant(player, packet->title)); + shared_ptr csm = std::make_shared(player, packet->title); csm->createContainer(); if(player->openTrading(csm, packet->customName ? packet->title : L"")) { @@ -3023,7 +3151,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe break; case ContainerOpenPacket::BEACON: { - shared_ptr beacon = shared_ptr(new BeaconTileEntity()); + shared_ptr beacon = std::make_shared(); if (packet->customName) beacon->setCustomName(packet->title); if(player->openBeacon(beacon)) @@ -3061,7 +3189,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe iTitle = IDS_MULE; break; }; - if(player->openHorseInventory(dynamic_pointer_cast(entity), shared_ptr(new AnimalChest(iTitle, packet->title, packet->customName, packet->size)))) + if(player->openHorseInventory(dynamic_pointer_cast(entity), std::make_shared(iTitle, packet->title, packet->customName, packet->size))) { player->containerMenu->containerId = packet->containerId; } @@ -3096,7 +3224,7 @@ void ClientConnection::handleContainerOpen(shared_ptr packe } else { - send(shared_ptr(new ContainerClosePacket(packet->containerId))); + send(std::make_shared(packet->containerId)); } } } @@ -3116,9 +3244,9 @@ void ClientConnection::handleContainerSetSlot(shared_ptr if(packet->slot >= 36 && packet->slot < 36 + 9) { shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) + if (packet->item != nullptr) { - if (lastItem == NULL || lastItem->count < packet->item->count) + if (lastItem == nullptr || lastItem->count < packet->item->count) { packet->item->popTime = Inventory::POP_TIME_DURATION; } @@ -3136,7 +3264,7 @@ void ClientConnection::handleContainerSetSlot(shared_ptr void ClientConnection::handleContainerAck(shared_ptr packet) { shared_ptr player = minecraft->localplayers[m_userIndex]; - AbstractContainerMenu *menu = NULL; + AbstractContainerMenu *menu = nullptr; if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { menu = player->inventoryMenu; @@ -3145,11 +3273,11 @@ void ClientConnection::handleContainerAck(shared_ptr packet) { menu = player->containerMenu; } - if (menu != NULL) + if (menu != nullptr) { if (!packet->accepted) { - send( shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) )); + send(std::make_shared(packet->containerId, packet->uid, true)); } } } @@ -3170,13 +3298,13 @@ void ClientConnection::handleContainerContent(shared_ptr packet) { shared_ptr tileEntity = level->getTileEntity(packet->x, packet->y, packet->z); - if (tileEntity != NULL) + if (tileEntity != nullptr) { minecraft->localplayers[m_userIndex]->openTextEdit(tileEntity); } else if (packet->editorType == TileEditorOpenPacket::SIGN) { - shared_ptr localSignDummy = shared_ptr(new SignTileEntity()); + shared_ptr localSignDummy = std::make_shared(); localSignDummy->setLevel(level); localSignDummy->x = packet->x; localSignDummy->y = packet->y; @@ -3193,7 +3321,7 @@ void ClientConnection::handleSignUpdate(shared_ptr packet) shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); // 4J-PB - on a client connecting, the line below fails - if (dynamic_pointer_cast(te) != NULL) + if (dynamic_pointer_cast(te) != nullptr) { shared_ptr ste = dynamic_pointer_cast(te); for (int i = 0; i < MAX_SIGN_LINES; i++) @@ -3209,7 +3337,7 @@ void ClientConnection::handleSignUpdate(shared_ptr packet) } else { - app.DebugPrintf("dynamic_pointer_cast(te) == NULL\n"); + app.DebugPrintf("dynamic_pointer_cast(te) == nullptr\n"); } } else @@ -3224,21 +3352,21 @@ void ClientConnection::handleTileEntityData(shared_ptr pac { shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); - if (te != NULL) + if (te != nullptr) { - if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && dynamic_pointer_cast(te) != NULL) + if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && dynamic_pointer_cast(te) != nullptr) { dynamic_pointer_cast(te)->load(packet->tag); } - else if (packet->type == TileEntityDataPacket::TYPE_ADV_COMMAND && dynamic_pointer_cast(te) != NULL) + else if (packet->type == TileEntityDataPacket::TYPE_ADV_COMMAND && dynamic_pointer_cast(te) != nullptr) { dynamic_pointer_cast(te)->load(packet->tag); } - else if (packet->type == TileEntityDataPacket::TYPE_BEACON && dynamic_pointer_cast(te) != NULL) + else if (packet->type == TileEntityDataPacket::TYPE_BEACON && dynamic_pointer_cast(te) != nullptr) { dynamic_pointer_cast(te)->load(packet->tag); } - else if (packet->type == TileEntityDataPacket::TYPE_SKULL && dynamic_pointer_cast(te) != NULL) + else if (packet->type == TileEntityDataPacket::TYPE_SKULL && dynamic_pointer_cast(te) != nullptr) { dynamic_pointer_cast(te)->load(packet->tag); } @@ -3249,7 +3377,7 @@ void ClientConnection::handleTileEntityData(shared_ptr pac void ClientConnection::handleContainerSetData(shared_ptr packet) { onUnhandledPacket(packet); - if (minecraft->localplayers[m_userIndex]->containerMenu != NULL && minecraft->localplayers[m_userIndex]->containerMenu->containerId == packet->containerId) + if (minecraft->localplayers[m_userIndex]->containerMenu != nullptr && minecraft->localplayers[m_userIndex]->containerMenu->containerId == packet->containerId) { minecraft->localplayers[m_userIndex]->containerMenu->setData(packet->id, packet->value); } @@ -3258,7 +3386,7 @@ void ClientConnection::handleContainerSetData(shared_ptr void ClientConnection::handleSetEquippedItem(shared_ptr packet) { shared_ptr entity = getEntity(packet->entity); - if (entity != NULL) + if (entity != nullptr) { // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game entity->setEquippedSlot(packet->slot, packet->getItem() ); @@ -3284,7 +3412,7 @@ void ClientConnection::handleTileDestruction(shared_ptr p bool ClientConnection::canHandleAsyncPackets() { - return minecraft != NULL && minecraft->level != NULL && minecraft->localplayers[m_userIndex] != NULL && level != NULL; + return minecraft != nullptr && minecraft->level != nullptr && minecraft->localplayers[m_userIndex] != nullptr && level != nullptr; } void ClientConnection::handleGameEvent(shared_ptr gameEventPacket) @@ -3293,7 +3421,7 @@ void ClientConnection::handleGameEvent(shared_ptr gameEventPack int param = gameEventPacket->param; if (event >= 0 && event < GameEventPacket::EVENT_LANGUAGE_ID_LENGTH) { - if (GameEventPacket::EVENT_LANGUAGE_ID[event] > 0) // 4J - was NULL check + if (GameEventPacket::EVENT_LANGUAGE_ID[event] > 0) // 4J - was nullptr check { minecraft->localplayers[m_userIndex]->displayClientMessage(GameEventPacket::EVENT_LANGUAGE_ID[event]); } @@ -3325,7 +3453,7 @@ void ClientConnection::handleGameEvent(shared_ptr gameEventPack ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); + if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); // Temporarily make this scene fullscreen CXuiSceneBase::SetPlayerBaseScenePosition( ProfileManager.GetPrimaryPad(), CXuiSceneBase::e_BaseScene_Fullscreen ); @@ -3333,8 +3461,8 @@ void ClientConnection::handleGameEvent(shared_ptr gameEventPack #else app.DebugPrintf("handleGameEvent packet for WIN_GAME - %d\n", m_userIndex); // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); - ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, NULL, eUILayer_Scene, eUIGroup_Fullscreen); + if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, nullptr, eUILayer_Scene, eUIGroup_Fullscreen); #endif } else if( event == GameEventPacket::START_SAVING ) @@ -3374,11 +3502,12 @@ void ClientConnection::handleComplexItemData(shared_ptr p void ClientConnection::handleLevelEvent(shared_ptr packet) { + if (!shouldProcessForPosition(packet->x, packet->z)) return; if (packet->type == LevelEvent::SOUND_DRAGON_DEATH) { for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { - if(minecraft->localplayers[i] != NULL && minecraft->localplayers[i]->level != NULL && minecraft->localplayers[i]->level->dimension->id == 1) + if(minecraft->localplayers[i] != nullptr && minecraft->localplayers[i]->level != nullptr && minecraft->localplayers[i]->level->dimension->id == 1) { minecraft->localplayers[i]->awardStat(GenericStats::completeTheEnd(),GenericStats::param_noArgs()); } @@ -3393,8 +3522,6 @@ void ClientConnection::handleLevelEvent(shared_ptr packet) { minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); } - - minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); } void ClientConnection::handleAwardStat(shared_ptr packet) @@ -3405,7 +3532,7 @@ void ClientConnection::handleAwardStat(shared_ptr packet) void ClientConnection::handleUpdateMobEffect(shared_ptr packet) { shared_ptr e = getEntity(packet->entityId); - if ( (e == NULL) || !e->instanceof(eTYPE_LIVINGENTITY) ) return; + if ( (e == nullptr) || !e->instanceof(eTYPE_LIVINGENTITY) ) return; //( dynamic_pointer_cast(e) )->addEffect(new MobEffectInstance(packet->effectId, packet->effectDurationTicks, packet->effectAmplifier)); @@ -3417,7 +3544,7 @@ void ClientConnection::handleUpdateMobEffect(shared_ptr p void ClientConnection::handleRemoveMobEffect(shared_ptr packet) { shared_ptr e = getEntity(packet->entityId); - if ( (e == NULL) || !e->instanceof(eTYPE_LIVINGENTITY) ) return; + if ( (e == nullptr) || !e->instanceof(eTYPE_LIVINGENTITY) ) return; ( dynamic_pointer_cast(e) )->removeEffectNoUpdate(packet->effectId); } @@ -3433,7 +3560,7 @@ void ClientConnection::handlePlayerInfo(shared_ptr packet) INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerBySmallId(packet->m_networkSmallId); - if(networkPlayer != NULL && networkPlayer->IsHost()) + if(networkPlayer != nullptr && networkPlayer->IsHost()) { // Some settings should always be considered on for the host player Player::enableAllPlayerPrivileges(startingPrivileges,true); @@ -3444,17 +3571,17 @@ void ClientConnection::handlePlayerInfo(shared_ptr packet) app.UpdatePlayerInfo(packet->m_networkSmallId, packet->m_playerColourIndex, packet->m_playerPrivileges); shared_ptr entity = getEntity(packet->m_entityId); - if(entity != NULL && entity->instanceof(eTYPE_PLAYER)) + if(entity != nullptr && entity->instanceof(eTYPE_PLAYER)) { shared_ptr player = dynamic_pointer_cast(entity); player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_playerPrivileges); } - if(networkPlayer != NULL && networkPlayer->IsLocal()) + if(networkPlayer != nullptr && networkPlayer->IsLocal()) { for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { shared_ptr localPlayer = minecraft->localplayers[i]; - if(localPlayer != NULL && localPlayer->connection != NULL && localPlayer->connection->getNetworkPlayer() == networkPlayer ) + if(localPlayer != nullptr && localPlayer->connection != nullptr && localPlayer->connection->getNetworkPlayer() == networkPlayer ) { localPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All,packet->m_playerPrivileges); displayPrivilegeChanges(localPlayer,startingPrivileges); @@ -3581,7 +3708,7 @@ void ClientConnection::displayPrivilegeChanges(shared_ptr packet) { - send(shared_ptr(new KeepAlivePacket(packet->id))); + send(std::make_shared(packet->id)); } void ClientConnection::handlePlayerAbilities(shared_ptr playerAbilitiesPacket) @@ -3652,7 +3779,7 @@ void ClientConnection::handleServerSettingsChanged(shared_ptrlevels.length; ++i) { - if( minecraft->levels[i] != NULL ) + if( minecraft->levels[i] != nullptr ) { app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); minecraft->levels[i]->difficulty = packet->data; @@ -3686,11 +3813,11 @@ void ClientConnection::handleUpdateProgress(shared_ptr pac void ClientConnection::handleUpdateGameRuleProgressPacket(shared_ptr packet) { LPCWSTR string = app.GetGameRulesString(packet->m_messageId); - if(string != NULL) + if(string != nullptr) { wstring message(string); message = GameRuleDefinition::generateDescriptionString(packet->m_definitionType,message,packet->m_data.data,packet->m_data.length); - if(minecraft->localgameModes[m_userIndex]!=NULL) + if(minecraft->localgameModes[m_userIndex]!=nullptr) { minecraft->localgameModes[m_userIndex]->getTutorial()->setMessage(message, packet->m_icon, packet->m_auxValue); } @@ -3736,7 +3863,7 @@ int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::E UINT uiIDA[2]; uiIDA[0]=IDS_CONFIRM_CANCEL; uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL); + ui.RequestErrorMessage(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,nullptr); } else #else @@ -3751,7 +3878,7 @@ int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::E UINT uiIDA[2]; uiIDA[0]=IDS_CONFIRM_CANCEL; uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL); + ui.RequestErrorMessage(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,nullptr); } else #endif @@ -3886,7 +4013,7 @@ void ClientConnection::handleSetPlayerTeamPacket(shared_ptr if (packet->method == SetPlayerTeamPacket::METHOD_ADD || packet->method == SetPlayerTeamPacket::METHOD_JOIN) { - for (int i = 0; i < packet->players.size(); i++) + for (size_t i = 0; i < packet->players.size(); i++) { scoreboard->addPlayerToTeam(packet->players[i], team); } @@ -3894,7 +4021,7 @@ void ClientConnection::handleSetPlayerTeamPacket(shared_ptr if (packet->method == SetPlayerTeamPacket::METHOD_LEAVE) { - for (int i = 0; i < packet->players.size(); i++) + for (size_t i = 0; i < packet->players.size(); i++) { scoreboard->removePlayerFromTeam(packet->players[i], team); } @@ -3929,7 +4056,7 @@ void ClientConnection::handleParticleEvent(shared_ptr pack void ClientConnection::handleUpdateAttributes(shared_ptr packet) { shared_ptr entity = getEntity(packet->getEntityId()); - if (entity == NULL) return; + if (entity == nullptr) return; if ( !entity->instanceof(eTYPE_LIVINGENTITY) ) { @@ -3968,7 +4095,7 @@ void ClientConnection::checkDeferredEntityLinkPackets(int newEntityId) { if (deferredEntityLinkPackets.empty()) return; - for (int i = 0; i < deferredEntityLinkPackets.size(); i++) + for (size_t i = 0; i < deferredEntityLinkPackets.size(); i++) { DeferredEntityLinkPacket *deferred = &deferredEntityLinkPackets[i]; diff --git a/Minecraft.Client/ClientConnection.h b/Minecraft.Client/ClientConnection.h index a80c10f78..3448496d0 100644 --- a/Minecraft.Client/ClientConnection.h +++ b/Minecraft.Client/ClientConnection.h @@ -1,4 +1,5 @@ #pragma once +#include #include "..\Minecraft.World\net.minecraft.network.h" class Minecraft; class MultiPlayerLevel; @@ -43,6 +44,21 @@ public: private: DWORD m_userIndex; // 4J Added + bool isPrimaryConnection() const; + + std::unordered_set m_trackedEntityIds; + std::unordered_set m_visibleChunks; + + static int64_t chunkKey(int x, int z) { return ((int64_t)x << 32) | ((int64_t)z & 0xFFFFFFFF); } + + ClientConnection* findPrimaryConnection() const; + bool shouldProcessForEntity(int entityId) const; + bool shouldProcessForPosition(int blockX, int blockZ) const; + bool anyOtherConnectionHasChunk(int x, int z) const; + +public: + bool isTrackingEntity(int entityId) const { return m_trackedEntityIds.count(entityId) > 0; } + public: SavedDataStorage *savedDataStorage; ClientConnection(Minecraft *minecraft, const wstring& ip, int port); diff --git a/Minecraft.Client/ClientConstants.cpp b/Minecraft.Client/ClientConstants.cpp index 43da4360b..d1d80aa9e 100644 --- a/Minecraft.Client/ClientConstants.cpp +++ b/Minecraft.Client/ClientConstants.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" #include "ClientConstants.h" -const wstring ClientConstants::VERSION_STRING = wstring(L"Minecraft LCE ") + VER_FILEVERSION_STR_W;//+ SharedConstants::VERSION_STRING; \ No newline at end of file +const wstring ClientConstants::VERSION_STRING = wstring(L"Minecraft LCE ") + VER_FILEVERSION_STR_W;//+ SharedConstants::VERSION_STRING; +const wstring ClientConstants::BRANCH_STRING = VER_BRANCHVERSION_STR_W; diff --git a/Minecraft.Client/ClientConstants.h b/Minecraft.Client/ClientConstants.h index 82bba386f..1476e51bf 100644 --- a/Minecraft.Client/ClientConstants.h +++ b/Minecraft.Client/ClientConstants.h @@ -13,6 +13,7 @@ class ClientConstants // INTERNAL DEVELOPMENT SETTINGS public: static const wstring VERSION_STRING; + static const wstring BRANCH_STRING; static const bool DEADMAU5_CAMERA_CHEATS = false; }; \ No newline at end of file diff --git a/Minecraft.Client/ClockTexture.cpp b/Minecraft.Client/ClockTexture.cpp index 837532fb7..5febeff34 100644 --- a/Minecraft.Client/ClockTexture.cpp +++ b/Minecraft.Client/ClockTexture.cpp @@ -10,7 +10,7 @@ ClockTexture::ClockTexture() : StitchedTexture(L"clock", L"clock") { rot = rota = 0.0; - m_dataTexture = NULL; + m_dataTexture = nullptr; m_iPad = XUSER_INDEX_ANY; } @@ -27,7 +27,7 @@ void ClockTexture::cycleFrames() Minecraft *mc = Minecraft::GetInstance(); double rott = 0; - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != nullptr && mc->localplayers[m_iPad] != nullptr) { float time = mc->localplayers[m_iPad]->level->getTimeOfDay(1); rott = time; @@ -55,9 +55,9 @@ void ClockTexture::cycleFrames() rot += rota; // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) + if(m_dataTexture != nullptr) { - int newFrame = (int) ((rot + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); + int newFrame = static_cast((rot + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); while (newFrame < 0) { newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); @@ -70,7 +70,7 @@ void ClockTexture::cycleFrames() } else { - int newFrame = (int) ((rot + 1.0) * frames->size()) % frames->size(); + int newFrame = static_cast((rot + 1.0) * frames->size()) % frames->size(); while (newFrame < 0) { newFrame = (newFrame + frames->size()) % frames->size(); @@ -95,7 +95,7 @@ int ClockTexture::getSourceHeight() const int ClockTexture::getFrames() { - if(m_dataTexture == NULL) + if(m_dataTexture == nullptr) { return StitchedTexture::getFrames(); } @@ -107,7 +107,7 @@ int ClockTexture::getFrames() void ClockTexture::freeFrameTextures() { - if(m_dataTexture == NULL) + if(m_dataTexture == nullptr) { StitchedTexture::freeFrameTextures(); } @@ -115,5 +115,5 @@ void ClockTexture::freeFrameTextures() bool ClockTexture::hasOwnData() { - return m_dataTexture == NULL; + return m_dataTexture == nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/Common/Audio/SoundEngine.cpp b/Minecraft.Client/Common/Audio/SoundEngine.cpp index 4b8f5f5ba..cf140c780 100644 --- a/Minecraft.Client/Common/Audio/SoundEngine.cpp +++ b/Minecraft.Client/Common/Audio/SoundEngine.cpp @@ -57,7 +57,7 @@ void SoundEngine::updateSoundEffectVolume(float fVal) {} void SoundEngine::add(const wstring& name, File *file) {} void SoundEngine::addMusic(const wstring& name, File *file) {} void SoundEngine::addStreaming(const wstring& name, File *file) {} -char *SoundEngine::ConvertSoundPathToName(const wstring& name, bool bConvertSpaces) { return NULL; } +char *SoundEngine::ConvertSoundPathToName(const wstring& name, bool bConvertSpaces) { return nullptr; } bool SoundEngine::isStreamingWavebankReady() { return true; } void SoundEngine::playMusicTick() {}; @@ -260,9 +260,9 @@ void SoundEngine::updateMiniAudio() continue; } - float finalVolume = s->info.volume * m_MasterEffectsVolume; - if (finalVolume > 1.0f) - finalVolume = 1.0f; + float finalVolume = s->info.volume * m_MasterEffectsVolume * SFX_VOLUME_MULTIPLIER; + if (finalVolume > SFX_MAX_GAIN) + finalVolume = SFX_MAX_GAIN; ma_sound_set_volume(&s->sound, finalVolume); ma_sound_set_pitch(&s->sound, s->info.pitch); @@ -334,7 +334,7 @@ void SoundEngine::tick(shared_ptr *players, float a) bool bListenerPostionSet = false; for( size_t i = 0; i < MAX_LOCAL_PLAYERS; i++ ) { - if( players[i] != NULL ) + if( players[i] != nullptr ) { m_ListenerA[i].bValid=true; F32 x,y,z; @@ -401,7 +401,7 @@ SoundEngine::SoundEngine() m_iMusicDelay=0; m_validListenerCount=0; - m_bHeardTrackA=NULL; + m_bHeardTrackA=nullptr; // Start the streaming music playing some music from the overworld SetStreamingSounds(eStream_Overworld_Calm1,eStream_Overworld_piano3, @@ -547,8 +547,8 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa &m_engine, finalPath, MA_SOUND_FLAG_ASYNC, - NULL, - NULL, + nullptr, + nullptr, &s->sound) != MA_SUCCESS) { app.DebugPrintf("Failed to initialize sound from file: %s\n", finalPath); @@ -557,10 +557,13 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa } ma_sound_set_spatialization_enabled(&s->sound, MA_TRUE); + ma_sound_set_min_distance(&s->sound, SFX_3D_MIN_DISTANCE); + ma_sound_set_max_distance(&s->sound, SFX_3D_MAX_DISTANCE); + ma_sound_set_rolloff(&s->sound, SFX_3D_ROLLOFF); - float finalVolume = volume * m_MasterEffectsVolume; - if (finalVolume > 1.0f) - finalVolume = 1.0f; + float finalVolume = volume * m_MasterEffectsVolume * SFX_VOLUME_MULTIPLIER; + if (finalVolume > SFX_MAX_GAIN) + finalVolume = SFX_MAX_GAIN; ma_sound_set_volume(&s->sound, finalVolume); ma_sound_set_pitch(&s->sound, pitch); @@ -631,8 +634,8 @@ void SoundEngine::playUI(int iSound, float volume, float pitch) &m_engine, finalPath, MA_SOUND_FLAG_ASYNC, - NULL, - NULL, + nullptr, + nullptr, &s->sound) != MA_SUCCESS) { delete s; @@ -700,7 +703,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y , float z, for(unsigned int i=0;ilocalplayers[i]!=NULL) + if(pMinecraft->localplayers[i]!=nullptr) { if(pMinecraft->localplayers[i]->dimension==LevelData::DIMENSION_END) { @@ -794,7 +797,7 @@ int SoundEngine::getMusicID(int iDomain) Minecraft *pMinecraft=Minecraft::GetInstance(); // Before the game has started? - if(pMinecraft==NULL) + if(pMinecraft==nullptr) { // any track from the overworld return GetRandomishTrack(m_iStream_Overworld_Min,m_iStream_Overworld_Max); @@ -927,8 +930,8 @@ int SoundEngine::OpenStreamThreadProc(void* lpParameter) &soundEngine->m_engine, soundEngine->m_szStreamName, MA_SOUND_FLAG_STREAM, - NULL, - NULL, + nullptr, + nullptr, &soundEngine->m_musicStream); if (result != MA_SUCCESS) @@ -1186,7 +1189,7 @@ void SoundEngine::playMusicUpdate() if( !m_openStreamThread->isRunning() ) { delete m_openStreamThread; - m_openStreamThread = NULL; + m_openStreamThread = nullptr; app.DebugPrintf("OpenStreamThreadProc finished. m_musicStreamActive=%d\n", m_musicStreamActive); @@ -1243,7 +1246,7 @@ void SoundEngine::playMusicUpdate() if( !m_openStreamThread->isRunning() ) { delete m_openStreamThread; - m_openStreamThread = NULL; + m_openStreamThread = nullptr; m_StreamState = eMusicStreamState_Stop; } break; @@ -1279,14 +1282,14 @@ void SoundEngine::playMusicUpdate() } if(GetIsPlayingStreamingGameMusic()) { - //if(m_MusicInfo.pCue!=NULL) + //if(m_MusicInfo.pCue!=nullptr) { bool playerInEnd = false; bool playerInNether=false; Minecraft *pMinecraft = Minecraft::GetInstance(); for(unsigned int i = 0; i < MAX_LOCAL_PLAYERS; ++i) { - if(pMinecraft->localplayers[i]!=NULL) + if(pMinecraft->localplayers[i]!=nullptr) { if(pMinecraft->localplayers[i]->dimension==LevelData::DIMENSION_END) { @@ -1417,7 +1420,7 @@ void SoundEngine::playMusicUpdate() for(unsigned int i=0;ilocalplayers[i]!=NULL) + if(pMinecraft->localplayers[i]!=nullptr) { if(pMinecraft->localplayers[i]->dimension==LevelData::DIMENSION_END) { diff --git a/Minecraft.Client/Common/Audio/SoundEngine.h b/Minecraft.Client/Common/Audio/SoundEngine.h index 5417dcec9..38d70d414 100644 --- a/Minecraft.Client/Common/Audio/SoundEngine.h +++ b/Minecraft.Client/Common/Audio/SoundEngine.h @@ -6,6 +6,12 @@ using namespace std; #include "miniaudio.h" +constexpr float SFX_3D_MIN_DISTANCE = 1.0f; +constexpr float SFX_3D_MAX_DISTANCE = 16.0f; +constexpr float SFX_3D_ROLLOFF = 0.5f; +constexpr float SFX_VOLUME_MULTIPLIER = 1.5f; +constexpr float SFX_MAX_GAIN = 1.5f; + enum eMUSICFILES { eStream_Overworld_Calm1 = 0, @@ -108,23 +114,23 @@ class SoundEngine : public ConsoleSoundEngine static const int MAX_SAME_SOUNDS_PLAYING = 8; // 4J added public: SoundEngine(); - virtual void destroy(); + void destroy() override; #ifdef _DEBUG void GetSoundName(char *szSoundName,int iSound); #endif - virtual void play(int iSound, float x, float y, float z, float volume, float pitch); - virtual void playStreaming(const wstring& name, float x, float y , float z, float volume, float pitch, bool bMusicDelay=true); - virtual void playUI(int iSound, float volume, float pitch); - virtual void playMusicTick(); - virtual void updateMusicVolume(float fVal); - virtual void updateSystemMusicPlaying(bool isPlaying); - virtual void updateSoundEffectVolume(float fVal); - virtual void init(Options *); - virtual void tick(shared_ptr *players, float a); // 4J - updated to take array of local players rather than single one - virtual void add(const wstring& name, File *file); - virtual void addMusic(const wstring& name, File *file); - virtual void addStreaming(const wstring& name, File *file); - virtual char *ConvertSoundPathToName(const wstring& name, bool bConvertSpaces=false); + void play(int iSound, float x, float y, float z, float volume, float pitch) override; + void playStreaming(const wstring& name, float x, float y , float z, float volume, float pitch, bool bMusicDelay=true) override; + void playUI(int iSound, float volume, float pitch) override; + void playMusicTick() override; + void updateMusicVolume(float fVal) override; + void updateSystemMusicPlaying(bool isPlaying) override; + void updateSoundEffectVolume(float fVal) override; + void init(Options *) override; + void tick(shared_ptr *players, float a) override; // 4J - updated to take array of local players rather than single one + void add(const wstring& name, File *file) override; + void addMusic(const wstring& name, File *file) override; + void addStreaming(const wstring& name, File *file) override; + char *ConvertSoundPathToName(const wstring& name, bool bConvertSpaces=false) override; bool isStreamingWavebankReady(); // 4J Added int getMusicID(int iDomain); int getMusicID(const wstring& name); @@ -138,7 +144,8 @@ private: #ifdef __PS3__ int initAudioHardware(int iMinSpeakers); #else - int initAudioHardware(int iMinSpeakers) { return iMinSpeakers;} + int initAudioHardware(int iMinSpeakers) override + { return iMinSpeakers;} #endif int GetRandomishTrack(int iStart,int iEnd); diff --git a/Minecraft.Client/Common/Audio/stb_vorbis.h b/Minecraft.Client/Common/Audio/stb_vorbis.h index 9192b162a..0e5294136 100644 --- a/Minecraft.Client/Common/Audio/stb_vorbis.h +++ b/Minecraft.Client/Common/Audio/stb_vorbis.h @@ -112,8 +112,8 @@ extern "C" { // query get_info to find the exact amount required. yes I know // this is lame). // -// If you pass in a non-NULL buffer of the type below, allocation -// will occur from it as described above. Otherwise just pass NULL +// If you pass in a non-nullptr buffer of the type below, allocation +// will occur from it as described above. Otherwise just pass nullptr // to use malloc()/alloca() typedef struct @@ -191,8 +191,8 @@ extern stb_vorbis *stb_vorbis_open_pushdata( // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; -// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed -// if returns NULL and *error is VORBIS_need_more_data, then the input block was +// on failure, returns nullptr on error and sets *error, does not change *datablock_memory_consumed +// if returns nullptr and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( @@ -219,7 +219,7 @@ extern int stb_vorbis_decode_frame_pushdata( // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be -// NULL--it is always the same as the number of channels reported by +// nullptr--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from @@ -269,18 +269,18 @@ extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *chan extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note -// this must be the entire stream!). on failure, returns NULL and sets *error +// this must be the entire stream!). on failure, returns nullptr and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, -// returns NULL and sets *error (possibly to VORBIS_file_open_failure). +// returns nullptr and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at -// the _current_ seek point (ftell). on failure, returns NULL and sets *error. +// the _current_ seek point (ftell). on failure, returns nullptr and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it @@ -291,7 +291,7 @@ extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_cl int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. -// on failure, returns NULL and sets *error. note that stb_vorbis must "own" +// on failure, returns nullptr and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif @@ -314,7 +314,7 @@ extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of -// channels returned are stored in *channels (which can be NULL--it is always +// channels returned are stored in *channels (which can be nullptr--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. @@ -588,7 +588,7 @@ enum STBVorbisError #include #endif #else // STB_VORBIS_NO_CRT - #define NULL 0 + #define nullptr 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 @@ -949,11 +949,11 @@ static void *setup_malloc(vorb *f, int sz) f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; - if (f->setup_offset + sz > f->temp_offset) return NULL; + if (f->setup_offset + sz > f->temp_offset) return nullptr; f->setup_offset += sz; return p; } - return sz ? malloc(sz) : NULL; + return sz ? malloc(sz) : nullptr; } static void setup_free(vorb *f, void *p) @@ -966,7 +966,7 @@ static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs. if (f->alloc.alloc_buffer) { - if (f->temp_offset - sz < f->setup_offset) return NULL; + if (f->temp_offset - sz < f->setup_offset) return nullptr; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } @@ -1654,12 +1654,12 @@ static int codebook_decode_scalar_raw(vorb *f, Codebook *c) int i; prep_huffman(f); - if (c->codewords == NULL && c->sorted_codewords == NULL) + if (c->codewords == nullptr && c->sorted_codewords == nullptr) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 - if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { + if (c->entries > 8 ? c->sorted_codewords!=nullptr : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; @@ -2629,7 +2629,7 @@ static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); - float *u=NULL,*v=NULL; + float *u=nullptr,*v=nullptr; // twiddle factors float *A = f->A[blocktype]; @@ -3057,7 +3057,7 @@ static float *get_window(vorb *f, int len) len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; - return NULL; + return nullptr; } #ifndef STB_VORBIS_NO_DEFER_FLOOR @@ -3306,7 +3306,7 @@ static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; - residue_buffers[ch] = NULL; + residue_buffers[ch] = nullptr; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; @@ -3351,7 +3351,7 @@ static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { - do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); + do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], nullptr); } } #else @@ -3464,7 +3464,7 @@ static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); - if (w == NULL) return 0; + if (w == nullptr) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = @@ -3647,24 +3647,24 @@ static int start_decoder(vorb *f) //file vendor len = get32_packet(f); f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1)); - if (f->vendor == NULL) return error(f, VORBIS_outofmem); + if (f->vendor == nullptr) return error(f, VORBIS_outofmem); for(i=0; i < len; ++i) { f->vendor[i] = get8_packet(f); } f->vendor[len] = (char)'\0'; //user comments f->comment_list_length = get32_packet(f); - f->comment_list = NULL; + f->comment_list = nullptr; if (f->comment_list_length > 0) { f->comment_list = (char**) setup_malloc(f, sizeof(char*) * (f->comment_list_length)); - if (f->comment_list == NULL) return error(f, VORBIS_outofmem); + if (f->comment_list == nullptr) return error(f, VORBIS_outofmem); } for(i=0; i < f->comment_list_length; ++i) { len = get32_packet(f); f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1)); - if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem); + if (f->comment_list[i] == nullptr) return error(f, VORBIS_outofmem); for(j=0; j < len; ++j) { f->comment_list[i][j] = get8_packet(f); @@ -3710,7 +3710,7 @@ static int start_decoder(vorb *f) f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); - if (f->codebooks == NULL) return error(f, VORBIS_outofmem); + if (f->codebooks == nullptr) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; @@ -3771,7 +3771,7 @@ static int start_decoder(vorb *f) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); - if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); + if (c->codeword_lengths == nullptr) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; @@ -3791,7 +3791,7 @@ static int start_decoder(vorb *f) } c->sorted_entries = sorted_count; - values = NULL; + values = nullptr; CHECK(f); if (!c->sparse) { @@ -3820,11 +3820,11 @@ static int start_decoder(vorb *f) if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); - if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); + if (c->sorted_codewords == nullptr) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); - if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); + if (c->sorted_values == nullptr) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); @@ -3834,7 +3834,7 @@ static int start_decoder(vorb *f) setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); - c->codewords = NULL; + c->codewords = nullptr; } compute_accelerated_huffman(c); @@ -3857,7 +3857,7 @@ static int start_decoder(vorb *f) } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); - if (mults == NULL) return error(f, VORBIS_outofmem); + if (mults == nullptr) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } @@ -3874,7 +3874,7 @@ static int start_decoder(vorb *f) c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); - if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } + if (c->multiplicands == nullptr) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; @@ -3902,7 +3902,7 @@ static int start_decoder(vorb *f) float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); - if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } + if (c->multiplicands == nullptr) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; @@ -3931,7 +3931,7 @@ static int start_decoder(vorb *f) // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); - if (f->floor_config == NULL) return error(f, VORBIS_outofmem); + if (f->floor_config == nullptr) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); @@ -4007,7 +4007,7 @@ static int start_decoder(vorb *f) // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); - if (f->residue_config == NULL) return error(f, VORBIS_outofmem); + if (f->residue_config == nullptr) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; @@ -4029,7 +4029,7 @@ static int start_decoder(vorb *f) residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); - if (r->residue_books == NULL) return error(f, VORBIS_outofmem); + if (r->residue_books == nullptr) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { @@ -4049,7 +4049,7 @@ static int start_decoder(vorb *f) int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); - if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); + if (r->classdata[j] == nullptr) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; @@ -4059,14 +4059,14 @@ static int start_decoder(vorb *f) f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); - if (f->mapping == NULL) return error(f, VORBIS_outofmem); + if (f->mapping == nullptr) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); - if (m->chan == NULL) return error(f, VORBIS_outofmem); + if (m->chan == nullptr) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else @@ -4128,11 +4128,11 @@ static int start_decoder(vorb *f) f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); - if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); + if (f->channel_buffers[i] == nullptr || f->previous_window[i] == nullptr || f->finalY[i] == nullptr) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); - if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); + if (f->floor_buffers[i] == nullptr) return error(f, VORBIS_outofmem); #endif } @@ -4232,7 +4232,7 @@ static void vorbis_deinit(stb_vorbis *p) setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array - setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); + setup_free(p, c->sorted_values ? c->sorted_values-1 : nullptr); } setup_free(p, p->codebooks); } @@ -4266,14 +4266,14 @@ static void vorbis_deinit(stb_vorbis *p) void stb_vorbis_close(stb_vorbis *p) { - if (p == NULL) return; + if (p == nullptr) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { - memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start + memset(p, 0, sizeof(*p)); // nullptr out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes &= ~7; @@ -4281,12 +4281,12 @@ static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) } p->eof = 0; p->error = VORBIS__no_error; - p->stream = NULL; - p->codebooks = NULL; + p->stream = nullptr; + p->codebooks = nullptr; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; - p->f = NULL; + p->f = nullptr; #endif } @@ -4509,7 +4509,7 @@ int stb_vorbis_decode_frame_pushdata( stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding - int *data_used, // only defined if result is not NULL + int *data_used, // only defined if result is not nullptr int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; @@ -4523,7 +4523,7 @@ stb_vorbis *stb_vorbis_open_pushdata( else *error = p.error; vorbis_deinit(&p); - return NULL; + return nullptr; } f = vorbis_alloc(&p); if (f) { @@ -4533,7 +4533,7 @@ stb_vorbis *stb_vorbis_open_pushdata( return f; } else { vorbis_deinit(&p); - return NULL; + return nullptr; } } #endif // STB_VORBIS_NO_PUSHDATA_API @@ -4680,7 +4680,7 @@ static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) set_file_offset(f, previous_safe); - while (vorbis_find_page(f, &end, NULL)) { + while (vorbis_find_page(f, &end, nullptr)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); @@ -4770,7 +4770,7 @@ static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) set_file_offset(f, left.page_end + (delta / 2) - 32768); } - if (!vorbis_find_page(f, NULL, NULL)) goto error; + if (!vorbis_find_page(f, nullptr, nullptr)) goto error; } for (;;) { @@ -4920,7 +4920,7 @@ int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; - stb_vorbis_get_frame_float(f, &n, NULL); + stb_vorbis_get_frame_float(f, &n, nullptr); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); @@ -5063,7 +5063,7 @@ stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *er } if (error) *error = p.error; vorbis_deinit(&p); - return NULL; + return nullptr; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) @@ -5081,14 +5081,14 @@ stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const st FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) - f = NULL; + f = nullptr; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; - return NULL; + return nullptr; } #endif // STB_VORBIS_NO_STDIO @@ -5097,7 +5097,7 @@ stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *err stb_vorbis *f, p; if (!data) { if (error) *error = VORBIS_unexpected_eof; - return NULL; + return nullptr; } vorbis_init(&p, alloc); p.stream = (uint8 *) data; @@ -5116,7 +5116,7 @@ stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *err } if (error) *error = p.error; vorbis_deinit(&p); - return NULL; + return nullptr; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION @@ -5255,8 +5255,8 @@ static void convert_samples_short(int buf_c, short **buffer, int b_offset, int d int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { - float **output = NULL; - int len = stb_vorbis_get_frame_float(f, NULL, &output); + float **output = nullptr; + int len = stb_vorbis_get_frame_float(f, nullptr, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); @@ -5294,7 +5294,7 @@ int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buff float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); - len = stb_vorbis_get_frame_float(f, NULL, &output); + len = stb_vorbis_get_frame_float(f, nullptr, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); @@ -5316,7 +5316,7 @@ int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short n += k; f->channel_buffer_start += k; if (n == len) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; + if (!stb_vorbis_get_frame_float(f, nullptr, &outputs)) break; } return n; } @@ -5333,7 +5333,7 @@ int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, in n += k; f->channel_buffer_start += k; if (n == len) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; + if (!stb_vorbis_get_frame_float(f, nullptr, &outputs)) break; } return n; } @@ -5343,8 +5343,8 @@ int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_ { int data_len, offset, total, limit, error; short *data; - stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); - if (v == NULL) return -1; + stb_vorbis *v = stb_vorbis_open_filename(filename, &error, nullptr); + if (v == nullptr) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) @@ -5352,7 +5352,7 @@ int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_ offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); - if (data == NULL) { + if (data == nullptr) { stb_vorbis_close(v); return -2; } @@ -5365,7 +5365,7 @@ int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_ short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); - if (data2 == NULL) { + if (data2 == nullptr) { free(data); stb_vorbis_close(v); return -2; @@ -5383,8 +5383,8 @@ int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *samp { int data_len, offset, total, limit, error; short *data; - stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); - if (v == NULL) return -1; + stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, nullptr); + if (v == nullptr) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) @@ -5392,7 +5392,7 @@ int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *samp offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); - if (data == NULL) { + if (data == nullptr) { stb_vorbis_close(v); return -2; } @@ -5405,7 +5405,7 @@ int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *samp short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); - if (data2 == NULL) { + if (data2 == nullptr) { free(data); stb_vorbis_close(v); return -2; @@ -5440,7 +5440,7 @@ int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float f->channel_buffer_start += k; if (n == len) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) + if (!stb_vorbis_get_frame_float(f, nullptr, &outputs)) break; } return n; @@ -5466,7 +5466,7 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in f->channel_buffer_start += k; if (n == num_samples) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) + if (!stb_vorbis_get_frame_float(f, nullptr, &outputs)) break; } return n; diff --git a/Minecraft.Client/Common/BuildVer.h b/Minecraft.Client/Common/BuildVer.h index babe75660..eaa77d26a 100644 --- a/Minecraft.Client/Common/BuildVer.h +++ b/Minecraft.Client/Common/BuildVer.h @@ -1,6 +1,7 @@ #pragma once #define VER_PRODUCTBUILD 560 -#define VER_PRODUCTVERSION_STR_W L"DEV (unknown)" +#define VER_PRODUCTVERSION_STR_W L"DEV (unknown version)" #define VER_FILEVERSION_STR_W VER_PRODUCTVERSION_STR_W +#define VER_BRANCHVERSION_STR_W L"UNKNOWN BRANCH" #define VER_NETWORK VER_PRODUCTBUILD diff --git a/Minecraft.Client/Common/Colours/ColourTable.cpp b/Minecraft.Client/Common/Colours/ColourTable.cpp index fa1e9d691..07326b8c1 100644 --- a/Minecraft.Client/Common/Colours/ColourTable.cpp +++ b/Minecraft.Client/Common/Colours/ColourTable.cpp @@ -325,7 +325,7 @@ void ColourTable::staticCtor() { for(unsigned int i = eMinecraftColour_NOT_SET; i < eMinecraftColour_COUNT; ++i) { - s_colourNamesMap.insert( unordered_map::value_type( ColourTableElements[i], (eMinecraftColour)i) ); + s_colourNamesMap.insert( unordered_map::value_type( ColourTableElements[i], static_cast(i)) ); } } @@ -366,7 +366,7 @@ void ColourTable::setColour(const wstring &colourName, int value) auto it = s_colourNamesMap.find(colourName); if(it != s_colourNamesMap.end()) { - m_colourValues[(int)it->second] = value; + m_colourValues[static_cast(it->second)] = value; } } @@ -377,5 +377,5 @@ void ColourTable::setColour(const wstring &colourName, const wstring &value) unsigned int ColourTable::getColour(eMinecraftColour id) { - return m_colourValues[(int)id]; + return m_colourValues[static_cast(id)]; } diff --git a/Minecraft.Client/Common/Console_Utils.cpp b/Minecraft.Client/Common/Console_Utils.cpp index cb0f1b583..9a64dbea3 100644 --- a/Minecraft.Client/Common/Console_Utils.cpp +++ b/Minecraft.Client/Common/Console_Utils.cpp @@ -1,21 +1,32 @@ #include "stdafx.h" +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include "..\..\Minecraft.Server\ServerLogManager.h" +#endif //-------------------------------------------------------------------------------------- // Name: DebugSpewV() // Desc: Internal helper function //-------------------------------------------------------------------------------------- #ifndef _CONTENT_PACKAGE -static VOID DebugSpewV( const CHAR* strFormat, const va_list pArgList ) +static VOID DebugSpewV( const CHAR* strFormat, va_list pArgList ) { #if defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - assert(0); + assert(0); #else - CHAR str[2048]; - // Use the secure CRT to avoid buffer overruns. Specify a count of - // _TRUNCATE so that too long strings will be silently truncated - // rather than triggering an error. - _vsnprintf_s( str, _TRUNCATE, strFormat, pArgList ); - OutputDebugStringA( str ); +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + // Dedicated server routes legacy debug spew through ServerLogger to preserve CLI prompt handling. + if (ServerRuntime::ServerLogManager::ShouldForwardClientDebugLogs()) + { + ServerRuntime::ServerLogManager::ForwardClientDebugSpewLogV(strFormat, pArgList); + return; + } +#endif + CHAR str[2048]; + // Use the secure CRT to avoid buffer overruns. Specify a count of + // _TRUNCATE so that too long strings will be silently truncated + // rather than triggering an error. + _vsnprintf_s( str, _TRUNCATE, strFormat, pArgList ); + OutputDebugStringA( str ); #endif } #endif @@ -31,10 +42,9 @@ VOID CDECL DebugPrintf( const CHAR* strFormat, ... ) #endif { #ifndef _CONTENT_PACKAGE - va_list pArgList; - va_start( pArgList, strFormat ); - DebugSpewV( strFormat, pArgList ); - va_end( pArgList ); + va_list pArgList; + va_start( pArgList, strFormat ); + DebugSpewV( strFormat, pArgList ); + va_end( pArgList ); #endif } - diff --git a/Minecraft.Client/Common/Consoles_App.cpp b/Minecraft.Client/Common/Consoles_App.cpp index 43cf73e15..0a2fd159a 100644 --- a/Minecraft.Client/Common/Consoles_App.cpp +++ b/Minecraft.Client/Common/Consoles_App.cpp @@ -38,6 +38,9 @@ #include "GameRules\ConsoleSchematicFile.h" #include "..\User.h" #include "..\..\Minecraft.World\LevelData.h" +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include "..\..\Minecraft.Server\ServerLogManager.h" +#endif #include "..\..\Minecraft.World\net.minecraft.world.entity.player.h" #include "..\EntityRenderDispatcher.h" #include "..\..\Minecraft.World\compression.h" @@ -100,7 +103,7 @@ CMinecraftApp::CMinecraftApp() { m_eTMSAction[i]=eTMSAction_Idle; m_eXuiAction[i]=eAppAction_Idle; - m_eXuiActionParam[i] = NULL; + m_eXuiActionParam[i] = nullptr; //m_dwAdditionalModelParts[i] = 0; if(FAILED(XUserGetSigninInfo(i,XUSER_GET_SIGNIN_INFO_OFFLINE_XUID_ONLY ,&m_currentSigninInfo[i]))) @@ -157,9 +160,9 @@ CMinecraftApp::CMinecraftApp() // m_bRead_TMS_XUIDS_XML=false; // m_bRead_TMS_DLCINFO_XML=false; - m_pDLCFileBuffer=NULL; + m_pDLCFileBuffer=nullptr; m_dwDLCFileSize=0; - m_pBannedListFileBuffer=NULL; + m_pBannedListFileBuffer=nullptr; m_dwBannedListFileSize=0; m_bDefaultCapeInstallAttempted=false; @@ -240,12 +243,21 @@ void CMinecraftApp::DebugPrintf(const char *szFormat, ...) { #ifndef _FINAL_BUILD - char buf[1024]; - va_list ap; - va_start(ap, szFormat); - vsnprintf(buf, sizeof(buf), szFormat, ap); - va_end(ap); - OutputDebugStringA(buf); + va_list ap; + va_start(ap, szFormat); +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + // Dedicated server routes client debug spew through ServerLogger so CLI output stays prompt-safe. + if (ServerRuntime::ServerLogManager::ShouldForwardClientDebugLogs()) + { + ServerRuntime::ServerLogManager::ForwardClientAppDebugLogV(szFormat, ap); + va_end(ap); + return; + } +#endif + char buf[1024]; + vsnprintf(buf, sizeof(buf), szFormat, ap); + va_end(ap); + OutputDebugStringA(buf); #endif } @@ -253,53 +265,62 @@ void CMinecraftApp::DebugPrintf(const char *szFormat, ...) void CMinecraftApp::DebugPrintf(int user, const char *szFormat, ...) { #ifndef _FINAL_BUILD - if(user == USER_NONE) - return; - char buf[1024]; - va_list ap; - va_start(ap, szFormat); - vsnprintf(buf, sizeof(buf), szFormat, ap); - va_end(ap); + if(user == USER_NONE) + return; + va_list ap; + va_start(ap, szFormat); +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + // Dedicated server routes client debug spew through ServerLogger so CLI output stays prompt-safe. + if (ServerRuntime::ServerLogManager::ShouldForwardClientDebugLogs()) + { + ServerRuntime::ServerLogManager::ForwardClientUserDebugLogV(user, szFormat, ap); + va_end(ap); + return; + } +#endif + char buf[1024]; + vsnprintf(buf, sizeof(buf), szFormat, ap); + va_end(ap); #ifdef __PS3__ - unsigned int writelen; - sys_tty_write(SYS_TTYP_USER1 + ( user - 1 ), buf, strlen(buf), &writelen ); + unsigned int writelen; + sys_tty_write(SYS_TTYP_USER1 + ( user - 1 ), buf, strlen(buf), &writelen ); #elif defined __PSVITA__ - switch(user) - { - case 0: - { - SceUID tty2 = sceIoOpen("tty2:", SCE_O_WRONLY, 0); - if(tty2>=0) - { - std::string string1(buf); - sceIoWrite(tty2, string1.c_str(), string1.length()); - sceIoClose(tty2); - } - } - break; - case 1: - { - SceUID tty3 = sceIoOpen("tty3:", SCE_O_WRONLY, 0); - if(tty3>=0) - { - std::string string1(buf); - sceIoWrite(tty3, string1.c_str(), string1.length()); - sceIoClose(tty3); - } - } - break; - default: - OutputDebugStringA(buf); - break; - } + switch(user) + { + case 0: + { + SceUID tty2 = sceIoOpen("tty2:", SCE_O_WRONLY, 0); + if(tty2>=0) + { + std::string string1(buf); + sceIoWrite(tty2, string1.c_str(), string1.length()); + sceIoClose(tty2); + } + } + break; + case 1: + { + SceUID tty3 = sceIoOpen("tty3:", SCE_O_WRONLY, 0); + if(tty3>=0) + { + std::string string1(buf); + sceIoWrite(tty3, string1.c_str(), string1.length()); + sceIoClose(tty3); + } + } + break; + default: + OutputDebugStringA(buf); + break; + } #else - OutputDebugStringA(buf); + OutputDebugStringA(buf); #endif #ifndef _XBOX - if(user == USER_UI) - { - ui.logDebugString(buf); - } + if(user == USER_UI) + { + ui.logDebugString(buf); + } #endif #endif } @@ -763,7 +784,7 @@ bool CMinecraftApp::LoadBeaconMenu(int iPad ,shared_ptr inventory, sh #ifdef _WINDOWS64 static void Win64_GetSettingsPath(char *outPath, DWORD size) { - GetModuleFileNameA(NULL, outPath, size); + GetModuleFileNameA(nullptr, outPath, size); char *lastSlash = strrchr(outPath, '\\'); if (lastSlash) *(lastSlash + 1) = '\0'; strncat_s(outPath, size, "settings.dat", _TRUNCATE); @@ -773,7 +794,7 @@ static void Win64_SaveSettings(GAME_SETTINGS *gs) if (!gs) return; char filePath[MAX_PATH] = {}; Win64_GetSettingsPath(filePath, MAX_PATH); - FILE *f = NULL; + FILE *f = nullptr; if (fopen_s(&f, filePath, "wb") == 0 && f) { fwrite(gs, sizeof(GAME_SETTINGS), 1, f); @@ -785,7 +806,7 @@ static void Win64_LoadSettings(GAME_SETTINGS *gs) if (!gs) return; char filePath[MAX_PATH] = {}; Win64_GetSettingsPath(filePath, MAX_PATH); - FILE *f = NULL; + FILE *f = nullptr; if (fopen_s(&f, filePath, "rb") == 0 && f) { GAME_SETTINGS temp = {}; @@ -803,7 +824,7 @@ void CMinecraftApp::InitGameSettings() #if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__) GameSettingsA[i]=(GAME_SETTINGS *)StorageManager.GetGameDefinedProfileData(i); #else - GameSettingsA[i]=(GAME_SETTINGS *)ProfileManager.GetGameDefinedProfileData(i); + GameSettingsA[i]=static_cast(ProfileManager.GetGameDefinedProfileData(i)); #endif // clear the flag to say the settings have changed GameSettingsA[i]->bSettingsChanged=false; @@ -840,7 +861,7 @@ int CMinecraftApp::SetDefaultOptions(C_4JProfile::PROFILESETTINGS *pSettings,con SetGameSettings(iPad,eGameSetting_FOV,0); // 4J-PB - Don't reset the difficult level if we're in-game - if(Minecraft::GetInstance()->level==NULL) + if(Minecraft::GetInstance()->level==nullptr) { app.DebugPrintf("SetDefaultOptions - Difficulty = 1\n"); SetGameSettings(iPad,eGameSetting_Difficulty,1); @@ -935,7 +956,7 @@ int CMinecraftApp::DefaultOptionsCallback(LPVOID pParam,C4JStorage::PROFILESETTI int CMinecraftApp::DefaultOptionsCallback(LPVOID pParam,C_4JProfile::PROFILESETTINGS *pSettings, const int iPad) #endif { - CMinecraftApp *pApp=(CMinecraftApp *)pParam; + CMinecraftApp *pApp=static_cast(pParam); // flag the default options to be set @@ -1372,29 +1393,29 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) case eGameSetting_MusicVolume: if(iPad==ProfileManager.GetPrimaryPad()) { - pMinecraft->options->set(Options::Option::MUSIC,((float)GameSettingsA[iPad]->ucMusicVolume)/100.0f); + pMinecraft->options->set(Options::Option::MUSIC,static_cast(GameSettingsA[iPad]->ucMusicVolume)/100.0f); } break; - case eGameSetting_SoundFXVolume: - if(iPad==ProfileManager.GetPrimaryPad()) - { - pMinecraft->options->set(Options::Option::SOUND,((float)GameSettingsA[iPad]->ucSoundFXVolume)/100.0f); - } + case eGameSetting_SoundFXVolume: + if (iPad == ProfileManager.GetPrimaryPad()) + { + pMinecraft->options->set(Options::Option::SOUND, static_cast(GameSettingsA[iPad]->ucSoundFXVolume) / 100.0f); + } break; case eGameSetting_RenderDistance: - if(iPad == ProfileManager.GetPrimaryPad()) - { - int dist = (GameSettingsA[iPad]->uiBitmaskValues >> 16) & 0xFF; + if (iPad == ProfileManager.GetPrimaryPad()) + { + int dist = (GameSettingsA[iPad]->uiBitmaskValues >> 16) & 0xFF; - int level = UIScene_SettingsGraphicsMenu::DistanceToLevel(dist); - pMinecraft->options->set(Options::Option::RENDER_DISTANCE, 3 - level); - } + int level = UIScene_SettingsGraphicsMenu::DistanceToLevel(dist); + pMinecraft->options->set(Options::Option::RENDER_DISTANCE, 3 - level); + }; break; case eGameSetting_Gamma: if(iPad==ProfileManager.GetPrimaryPad()) { #if defined(_WIN64) || defined(_WINDOWS64) - pMinecraft->options->set(Options::Option::GAMMA, ((float)GameSettingsA[iPad]->ucGamma) / 100.0f); + pMinecraft->options->set(Options::Option::GAMMA, static_cast(GameSettingsA[iPad]->ucGamma) / 100.0f); #else // ucGamma range is 0-100, UpdateGamma is 0 - 32768 float fVal=((float)GameSettingsA[iPad]->ucGamma)*327.68f; @@ -1421,7 +1442,7 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) app.SetGameHostOption(eGameHostOption_Difficulty,pMinecraft->options->difficulty); // send this to the other players if we are in-game - bool bInGame=pMinecraft->level!=NULL; + bool bInGame=pMinecraft->level!=nullptr; // Game Host only (and for now we can't change the diff while in game, so this shouldn't happen) if(bInGame && g_NetworkManager.IsHost() && (iPad==ProfileManager.GetPrimaryPad())) @@ -1438,7 +1459,7 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) case eGameSetting_Sensitivity_InGame: // 4J-PB - we don't use the options value // tell the input that we've changed the sensitivity - range of the slider is 0 to 200, default is 100 - pMinecraft->options->set(Options::Option::SENSITIVITY,((float)GameSettingsA[iPad]->ucSensitivity)/100.0f); + pMinecraft->options->set(Options::Option::SENSITIVITY,static_cast(GameSettingsA[iPad]->ucSensitivity)/100.0f); //InputManager.SetJoypadSensitivity(iPad,((float)GameSettingsA[iPad]->ucSensitivity)/100.0f); break; @@ -1485,7 +1506,7 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) break; case eGameSetting_GamertagsVisible: { - bool bInGame=pMinecraft->level!=NULL; + bool bInGame=pMinecraft->level!=nullptr; // Game Host only if(bInGame && g_NetworkManager.IsHost() && (iPad==ProfileManager.GetPrimaryPad())) @@ -1514,7 +1535,7 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) case eGameSetting_DisplaySplitscreenGamertags: for( BYTE idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(pMinecraft->localplayers[idx] != NULL) + if(pMinecraft->localplayers[idx] != nullptr) { if(pMinecraft->localplayers[idx]->m_iScreenSection==C4JRender::VIEWPORT_TYPE_FULLSCREEN) { @@ -1558,19 +1579,17 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) case eGameSetting_FriendsOfFriends: //nothing to do here break; - case eGameSetting_BedrockFog: - { - bool bInGame=pMinecraft->level!=NULL; + case eGameSetting_BedrockFog: + { + bool bInGame = pMinecraft->level != nullptr; - // Game Host only - if(bInGame && g_NetworkManager.IsHost() && (iPad==ProfileManager.GetPrimaryPad())) - { - // Update the Game Host setting if you are the host and you are in-game - app.SetGameHostOption(eGameHostOption_BedrockFog,GetGameSettings(iPad,eGameSetting_BedrockFog)?1:0); - app.SetXuiServerAction(iPad,eXuiServerAction_ServerSettingChanged_BedrockFog); - } - } - break; + if (bInGame && g_NetworkManager.IsHost() && (iPad == ProfileManager.GetPrimaryPad())) + { + app.SetGameHostOption(eGameHostOption_BedrockFog, GetGameSettings(iPad, eGameSetting_BedrockFog) ? 1 : 0); + app.SetXuiServerAction(iPad, eXuiServerAction_ServerSettingChanged_BedrockFog); + } + } + break; case eGameSetting_DisplayHUD: //nothing to do here break; @@ -1617,7 +1636,7 @@ void CMinecraftApp::SetPlayerSkin(int iPad,DWORD dwSkinId) TelemetryManager->RecordSkinChanged(iPad, GameSettingsA[iPad]->dwSelectedSkin); - if(Minecraft::GetInstance()->localplayers[iPad]!=NULL) Minecraft::GetInstance()->localplayers[iPad]->setAndBroadcastCustomSkin(dwSkinId); + if(Minecraft::GetInstance()->localplayers[iPad]!=nullptr) Minecraft::GetInstance()->localplayers[iPad]->setAndBroadcastCustomSkin(dwSkinId); } @@ -1629,8 +1648,8 @@ wstring CMinecraftApp::GetPlayerSkinName(int iPad) DWORD CMinecraftApp::GetPlayerSkinId(int iPad) { // 4J-PB -check the user has rights to use this skin - they may have had at some point but the entitlement has been removed. - DLCPack *Pack=NULL; - DLCSkinFile *skinFile=NULL; + DLCPack *Pack=nullptr; + DLCSkinFile *skinFile=nullptr; DWORD dwSkin=GameSettingsA[iPad]->dwSelectedSkin; wchar_t chars[256]; @@ -1685,7 +1704,7 @@ void CMinecraftApp::SetPlayerCape(int iPad,DWORD dwCapeId) //SentientManager.RecordSkinChanged(iPad, GameSettingsA[iPad]->dwSelectedSkin); - if(Minecraft::GetInstance()->localplayers[iPad]!=NULL) Minecraft::GetInstance()->localplayers[iPad]->setAndBroadcastCustomCape(dwCapeId); + if(Minecraft::GetInstance()->localplayers[iPad]!=nullptr) Minecraft::GetInstance()->localplayers[iPad]->setAndBroadcastCustomCape(dwCapeId); } wstring CMinecraftApp::GetPlayerCapeName(int iPad) @@ -1718,7 +1737,7 @@ unsigned char CMinecraftApp::GetPlayerFavoriteSkinsPos(int iPad) void CMinecraftApp::SetPlayerFavoriteSkinsPos(int iPad, int iPos) { - GameSettingsA[iPad]->ucCurrentFavoriteSkinPos=(unsigned char)iPos; + GameSettingsA[iPad]->ucCurrentFavoriteSkinPos=static_cast(iPos); GameSettingsA[iPad]->bSettingsChanged = true; } @@ -1755,7 +1774,7 @@ void CMinecraftApp::ValidateFavoriteSkins(int iPad) // Also check they haven't reverted to a trial pack DLCPack *pDLCPack=app.m_dlcManager.getPackContainingSkin(chars); - if(pDLCPack!=NULL) + if(pDLCPack!=nullptr) { // 4J-PB - We should let players add the free skins to their favourites as well! //DLCFile *pDLCFile=pDLCPack->getFile(DLCManager::e_DLCType_Skin,chars); @@ -1802,7 +1821,7 @@ void CMinecraftApp::SetMinecraftLanguage(int iPad, unsigned char ucLanguage) unsigned char CMinecraftApp::GetMinecraftLanguage(int iPad) { // if there are no game settings read yet, return the default language - if(GameSettingsA[iPad]==NULL) + if(GameSettingsA[iPad]==nullptr) { return 0; } @@ -1821,7 +1840,7 @@ void CMinecraftApp::SetMinecraftLocale(int iPad, unsigned char ucLocale) unsigned char CMinecraftApp::GetMinecraftLocale(int iPad) { // if there are no game settings read yet, return the default language - if(GameSettingsA[iPad]==NULL) + if(GameSettingsA[iPad]==nullptr) { return 0; } @@ -2523,7 +2542,7 @@ unsigned int CMinecraftApp::GetGameSettingsDebugMask(int iPad,bool bOverridePlay shared_ptr player = Minecraft::GetInstance()->localplayers[iPad]; - if(bOverridePlayer || player==NULL) + if(bOverridePlayer || player==nullptr) { return GameSettingsA[iPad]->uiDebugBitmask; } @@ -2697,7 +2716,7 @@ int CMinecraftApp::DisplaySavingMessage(void *pParam, C4JStorage::ESavingMessage void CMinecraftApp::SetActionConfirmed(LPVOID param) { - XuiActionParam *actionInfo = (XuiActionParam *)param; + XuiActionParam *actionInfo = static_cast(param); app.SetAction(actionInfo->iPad, actionInfo->action); } @@ -2835,7 +2854,7 @@ void CMinecraftApp::HandleXuiActions(void) app.SetAutosaveTimerTime(); SetAction(i,eAppAction_Idle); // Check that there is a name for the save - if we're saving from the tutorial and this is the first save from the tutorial, we'll not have a name - /*if(StorageManager.GetSaveName()==NULL) + /*if(StorageManager.GetSaveName()==nullptr) { app.NavigateToScene(i,eUIScene_SaveWorld); } @@ -2853,7 +2872,7 @@ void CMinecraftApp::HandleXuiActions(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &UIScene_PauseMenu::SaveWorldThreadProc; - loadingParams->lpParam = (LPVOID)false; + loadingParams->lpParam = static_cast(false); // 4J-JEV - PS4: Fix for #5708 - [ONLINE] - If the user pulls their network cable out while saving the title will hang. loadingParams->waitForThreadToDelete = true; @@ -2904,7 +2923,7 @@ void CMinecraftApp::HandleXuiActions(void) ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); // This just allows it to be shown - if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); + if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); //INT saveOrCheckpointId = 0; //bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); @@ -2914,7 +2933,7 @@ void CMinecraftApp::HandleXuiActions(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &UIScene_PauseMenu::SaveWorldThreadProc; - loadingParams->lpParam = (LPVOID)true; + loadingParams->lpParam = (LPVOID)(true); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -2980,7 +2999,7 @@ void CMinecraftApp::HandleXuiActions(void) // send the message for(int idx=0;idxlocalplayers[idx]!=NULL)) + if((i!=idx) && (pMinecraft->localplayers[idx]!=nullptr)) { XuiBroadcastMessage( CXuiSceneBase::GetPlayerBaseScene(idx), &xuiMsg ); } @@ -3062,7 +3081,7 @@ void CMinecraftApp::HandleXuiActions(void) // send the message for(int idx=0;idxlocalplayers[idx]!=NULL)) + if((i!=idx) && (pMinecraft->localplayers[idx]!=nullptr)) { XuiBroadcastMessage( CXuiSceneBase::GetPlayerBaseScene(idx), &xuiMsg ); } @@ -3288,8 +3307,8 @@ void CMinecraftApp::HandleXuiActions(void) UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); // If param is non-null then this is a forced exit by the server, so make sure the player knows why // 4J Stu - Changed - Don't use the FullScreenProgressScreen for action, use a dialog instead - completionData->bRequiresUserAction = FALSE;//(param != NULL) ? TRUE : FALSE; - completionData->bShowTips = (param != NULL) ? FALSE : TRUE; + completionData->bRequiresUserAction = FALSE;//(param != nullptr) ? TRUE : FALSE; + completionData->bShowTips = (param != nullptr) ? FALSE : TRUE; completionData->bShowBackground=TRUE; completionData->bShowLogo=TRUE; completionData->type = e_ProgressCompletion_NavigateToHomeMenu; @@ -3401,7 +3420,7 @@ void CMinecraftApp::HandleXuiActions(void) break; case eAppAction_WaitForRespawnComplete: player = pMinecraft->localplayers[i]; - if(player != NULL && player->GetPlayerRespawned()) + if(player != nullptr && player->GetPlayerRespawned()) { SetAction(i,eAppAction_Idle); @@ -3426,7 +3445,7 @@ void CMinecraftApp::HandleXuiActions(void) break; case eAppAction_WaitForDimensionChangeComplete: player = pMinecraft->localplayers[i]; - if(player != NULL && player->connection && player->connection->isStarted()) + if(player != nullptr && player->connection && player->connection->isStarted()) { SetAction(i,eAppAction_Idle); ui.CloseUIScenes(i); @@ -3740,12 +3759,12 @@ void CMinecraftApp::HandleXuiActions(void) // unload any texture pack audio // if there is audio in use, clear out the audio, and unmount the pack TexturePack *pTexPack=Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=NULL; + DLCTexturePack *pDLCTexPack=nullptr; if(pTexPack->hasAudio()) { // get the dlc texture pack, and store it - pDLCTexPack=(DLCTexturePack *)pTexPack; + pDLCTexPack=static_cast(pTexPack); } // change to the default texture pack @@ -3764,11 +3783,11 @@ void CMinecraftApp::HandleXuiActions(void) pMinecraft->soundEngine->playStreaming(L"", 0, 0, 0, 1, 1); #ifdef _XBOX - if(pDLCTexPack->m_pStreamedWaveBank!=NULL) + if(pDLCTexPack->m_pStreamedWaveBank!=nullptr) { pDLCTexPack->m_pStreamedWaveBank->Destroy(); } - if(pDLCTexPack->m_pSoundBank!=NULL) + if(pDLCTexPack->m_pSoundBank!=nullptr) { pDLCTexPack->m_pSoundBank->Destroy(); } @@ -3787,18 +3806,18 @@ void CMinecraftApp::HandleXuiActions(void) for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { if(ProfileManager.IsSignedIn(index) ) - { - if(index==i || pMinecraft->localplayers[index]!=NULL ) - { - m_InviteData.dwLocalUsersMask |= g_NetworkManager.GetLocalPlayerMask( index ); - } + { + if (index == i || pMinecraft->localplayers[index] != nullptr) + { + m_InviteData.dwLocalUsersMask |= g_NetworkManager.GetLocalPlayerMask(index); + } } } #endif - LoadingInputParams *loadingParams = new LoadingInputParams(); - loadingParams->func = &CGameNetworkManager::ExitAndJoinFromInviteThreadProc; - loadingParams->lpParam = (LPVOID)&m_InviteData; + LoadingInputParams *loadingParams = new LoadingInputParams(); + loadingParams->func = &CGameNetworkManager::ExitAndJoinFromInviteThreadProc; + loadingParams->lpParam = static_cast(&m_InviteData); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -3821,7 +3840,7 @@ void CMinecraftApp::HandleXuiActions(void) g_NetworkManager.SetLocalGame(false); - JoinFromInviteData *inviteData = (JoinFromInviteData *)param; + JoinFromInviteData *inviteData = static_cast(param); // 4J-PB - clear any previous connection errors Minecraft::GetInstance()->clearConnectionFailed(); @@ -3896,7 +3915,7 @@ void CMinecraftApp::HandleXuiActions(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::ChangeSessionTypeThreadProc; - loadingParams->lpParam = NULL; + loadingParams->lpParam = nullptr; UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); #ifdef __PS3__ @@ -3947,7 +3966,7 @@ void CMinecraftApp::HandleXuiActions(void) #if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__) SetDefaultOptions((C4JStorage::PROFILESETTINGS *)param,i); #else - SetDefaultOptions((C_4JProfile::PROFILESETTINGS *)param,i); + SetDefaultOptions(static_cast(param), i); #endif // if the profile data has been changed, then force a profile write @@ -3977,7 +3996,7 @@ void CMinecraftApp::HandleXuiActions(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CMinecraftApp::RemoteSaveThreadProc; - loadingParams->lpParam = NULL; + loadingParams->lpParam = nullptr; UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bRequiresUserAction=FALSE; @@ -4276,7 +4295,7 @@ void CMinecraftApp::HandleXuiActions(void) SetTMSAction(i,eTMSAction_TMSPP_UserFileList_Waiting); app.TMSPP_RetrieveFileList(i,C4JStorage::eGlobalStorage_TitleUser,"\\",eTMSAction_TMSPP_XUIDSFile); #elif defined _XBOX_ONE - //StorageManager.TMSPP_DeleteFile(i,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.png",NULL,NULL, 0); + //StorageManager.TMSPP_DeleteFile(i,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.png",nullptr,nullptr, 0); SetTMSAction(i,eTMSAction_TMSPP_UserFileList_Waiting); app.TMSPP_RetrieveFileList(i,C4JStorage::eGlobalStorage_TitleUser,eTMSAction_TMSPP_DLCFileOnly); #else @@ -4365,7 +4384,7 @@ void CMinecraftApp::HandleXuiActions(void) int CMinecraftApp::BannedLevelDialogReturned(void *pParam,int iPad,const C4JStorage::EMessageResult result) { - CMinecraftApp* pApp = (CMinecraftApp*)pParam; + CMinecraftApp* pApp = static_cast(pParam); //Minecraft *pMinecraft=Minecraft::GetInstance(); if(result==C4JStorage::EMessage_ResultAccept) @@ -4373,7 +4392,7 @@ int CMinecraftApp::BannedLevelDialogReturned(void *pParam,int iPad,const C4JStor #if defined _XBOX || defined _XBOX_ONE INetworkPlayer *pHost = g_NetworkManager.GetHostPlayer(); // unban the level - if (pHost != NULL) + if (pHost != nullptr) { #if defined _XBOX pApp->RemoveLevelFromBannedLevelList(iPad,((NetworkPlayerXbox *)pHost)->GetUID(),pApp->GetUniqueMapName()); @@ -4423,10 +4442,10 @@ void CMinecraftApp::loadMediaArchive() HANDLE hFile = CreateFile( path.c_str(), GENERIC_READ, FILE_SHARE_READ, - NULL, + nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, - NULL ); + nullptr ); if( hFile != INVALID_HANDLE_VALUE ) { @@ -4442,7 +4461,7 @@ void CMinecraftApp::loadMediaArchive() m_fBody, dwFileSize, &m_fSize, - NULL ); + nullptr ); assert( m_fSize == dwFileSize ); @@ -4454,7 +4473,7 @@ void CMinecraftApp::loadMediaArchive() { assert( false ); // AHHHHHHHHHHHH - m_mediaArchive = NULL; + m_mediaArchive = nullptr; } #endif } @@ -4463,7 +4482,7 @@ void CMinecraftApp::loadStringTable() { #ifndef _XBOX - if(m_stringTable!=NULL) + if(m_stringTable!=nullptr) { // we need to unload the current string table, this is a reload delete m_stringTable; @@ -4477,7 +4496,7 @@ void CMinecraftApp::loadStringTable() } else { - m_stringTable = NULL; + m_stringTable = nullptr; assert(false); // AHHHHHHHHH. } @@ -4490,7 +4509,7 @@ int CMinecraftApp::PrimaryPlayerSignedOutReturned(void *pParam,int iPad,const C4 //Minecraft *pMinecraft=Minecraft::GetInstance(); // if the player is null, we're in the menus - //if(Minecraft::GetInstance()->player!=NULL) + //if(Minecraft::GetInstance()->player!=nullptr) // We always create a session before kicking of any of the game code, so even though we may still be joining/creating a game // at this point we want to handle it differently from just being in a menu @@ -4511,10 +4530,10 @@ int CMinecraftApp::EthernetDisconnectReturned(void *pParam,int iPad,const C4JSto Minecraft *pMinecraft=Minecraft::GetInstance(); // if the player is null, we're in the menus - if(Minecraft::GetInstance()->player!=NULL) - { - app.SetAction(pMinecraft->player->GetXboxPad(),eAppAction_EthernetDisconnectedReturned); - } + if (Minecraft::GetInstance()->player != nullptr) + { + app.SetAction(pMinecraft->player->GetXboxPad(), eAppAction_EthernetDisconnectedReturned); + } else { // 4J-PB - turn off the PSN store icon just in case this happened when we were in one of the DLC menus @@ -4543,7 +4562,7 @@ int CMinecraftApp::SignoutExitWorldThreadProc( void* lpParameter ) bool saveStats = false; if (pMinecraft->isClientSide() || g_NetworkManager.IsInSession() ) { - if(lpParameter != NULL ) + if(lpParameter != nullptr ) { switch( app.GetDisconnectReason() ) { @@ -4575,16 +4594,16 @@ int CMinecraftApp::SignoutExitWorldThreadProc( void* lpParameter ) } pMinecraft->progressRenderer->progressStartNoAbort( exitReasonStringId ); // 4J - Force a disconnection, this handles the situation that the server has already disconnected - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(false); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(false); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(false); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(false); } else { exitReasonStringId = IDS_EXITING_GAME; pMinecraft->progressRenderer->progressStartNoAbort( IDS_EXITING_GAME ); - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(); } // 4J Stu - This only does something if we actually have a server, so don't need to do any other checks @@ -4599,7 +4618,7 @@ int CMinecraftApp::SignoutExitWorldThreadProc( void* lpParameter ) } else { - if(lpParameter != NULL ) + if(lpParameter != nullptr ) { switch( app.GetDisconnectReason() ) { @@ -4636,7 +4655,7 @@ int CMinecraftApp::SignoutExitWorldThreadProc( void* lpParameter ) pMinecraft->progressRenderer->progressStartNoAbort( exitReasonStringId ); } } - pMinecraft->setLevel(NULL,exitReasonStringId,nullptr,saveStats,true); + pMinecraft->setLevel(nullptr,exitReasonStringId,nullptr,saveStats,true); // 4J-JEV: Fix for #106402 - TCR #014 BAS Debug Output: // TU12: Mass Effect Mash-UP: Save file "Default_DisplayName" is created on all storage devices after signing out from a re-launched pre-generated world @@ -4662,7 +4681,7 @@ int CMinecraftApp::UnlockFullInviteReturned(void *pParam,int iPad,C4JStorage::EM // bug 11285 - TCR 001: BAS Game Stability: CRASH - When trying to join a full version game with a trial version, the trial crashes // 4J-PB - we may be in the main menus here, and we don't have a pMinecraft->player - if(pMinecraft->player==NULL) + if(pMinecraft->player==nullptr) { bNoPlayer=true; } @@ -4674,7 +4693,7 @@ int CMinecraftApp::UnlockFullInviteReturned(void *pParam,int iPad,C4JStorage::EM // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -4719,7 +4738,7 @@ int CMinecraftApp::UnlockFullSaveReturned(void *pParam,int iPad,C4JStorage::EMes // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -4774,7 +4793,7 @@ int CMinecraftApp::UnlockFullSaveReturned(void *pParam,int iPad,C4JStorage::EMes int CMinecraftApp::UnlockFullExitReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CMinecraftApp* pApp = (CMinecraftApp*)pParam; + CMinecraftApp* pApp = static_cast(pParam); Minecraft *pMinecraft=Minecraft::GetInstance(); if(result==C4JStorage::EMessage_ResultAccept) @@ -4784,7 +4803,7 @@ int CMinecraftApp::UnlockFullExitReturned(void *pParam,int iPad,C4JStorage::EMes // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -4846,7 +4865,7 @@ int CMinecraftApp::UnlockFullExitReturned(void *pParam,int iPad,C4JStorage::EMes int CMinecraftApp::TrialOverReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CMinecraftApp* pApp = (CMinecraftApp*)pParam; + CMinecraftApp* pApp = static_cast(pParam); Minecraft *pMinecraft=Minecraft::GetInstance(); if(result==C4JStorage::EMessage_ResultAccept) @@ -4857,7 +4876,7 @@ int CMinecraftApp::TrialOverReturned(void *pParam,int iPad,C4JStorage::EMessageR // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -4904,7 +4923,7 @@ int CMinecraftApp::TrialOverReturned(void *pParam,int iPad,C4JStorage::EMessageR void CMinecraftApp::ProfileReadErrorCallback(void *pParam) { - CMinecraftApp *pApp=(CMinecraftApp *)pParam; + CMinecraftApp *pApp=static_cast(pParam); int iPrimaryPlayer=ProfileManager.GetPrimaryPad(); pApp->SetAction(iPrimaryPlayer, eAppAction_ProfileReadError); } @@ -4936,7 +4955,7 @@ void CMinecraftApp::SignInChangeCallback(LPVOID pParam,bool bPrimaryPlayerChange Minecraft::GetInstance()->user->name = convStringToWstring( ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); #endif - CMinecraftApp *pApp=(CMinecraftApp *)pParam; + CMinecraftApp *pApp=static_cast(pParam); // check if the primary player signed out int iPrimaryPlayer=ProfileManager.GetPrimaryPad(); @@ -5001,7 +5020,7 @@ void CMinecraftApp::SignInChangeCallback(LPVOID pParam,bool bPrimaryPlayerChange if(i == iPrimaryPlayer) continue; // A guest a signed in or out, out of order which invalidates all the guest players we have in the game - if(hasGuestIdChanged && pApp->m_currentSigninInfo[i].dwGuestNumber != 0 && g_NetworkManager.GetLocalPlayerByUserIndex(i)!=NULL) + if(hasGuestIdChanged && pApp->m_currentSigninInfo[i].dwGuestNumber != 0 && g_NetworkManager.GetLocalPlayerByUserIndex(i)!=nullptr) { pApp->DebugPrintf("Recommending removal of player at index %d because their guest id changed\n",i); pApp->SetAction(i, eAppAction_ExitPlayer); @@ -5025,7 +5044,7 @@ void CMinecraftApp::SignInChangeCallback(LPVOID pParam,bool bPrimaryPlayerChange // 4J-HG: If either the player is in the network manager or in the game, need to exit player // TODO: Do we need to check the network manager? - if (g_NetworkManager.GetLocalPlayerByUserIndex(i) != NULL || Minecraft::GetInstance()->localplayers[i] != NULL) + if (g_NetworkManager.GetLocalPlayerByUserIndex(i) != nullptr || Minecraft::GetInstance()->localplayers[i] != nullptr) { pApp->DebugPrintf("Player %d signed out\n", i); pApp->SetAction(i, eAppAction_ExitPlayer); @@ -5036,7 +5055,7 @@ void CMinecraftApp::SignInChangeCallback(LPVOID pParam,bool bPrimaryPlayerChange // check if any of the addition players have signed out of PSN (primary player is handled below) if(!switchToOffline && i != ProfileManager.GetLockedProfile() && !g_NetworkManager.IsLocalGame()) { - if(g_NetworkManager.GetLocalPlayerByUserIndex(i)!=NULL) + if(g_NetworkManager.GetLocalPlayerByUserIndex(i)!=nullptr) { if(ProfileManager.IsSignedInLive(i) == false) { @@ -5111,7 +5130,7 @@ void CMinecraftApp::SignInChangeCallback(LPVOID pParam,bool bPrimaryPlayerChange void CMinecraftApp::NotificationsCallback(LPVOID pParam,DWORD dwNotification, unsigned int uiParam) { - CMinecraftApp* pClass = (CMinecraftApp*)pParam; + CMinecraftApp* pClass = static_cast(pParam); // push these on to the notifications to be handled in qnet's dowork @@ -5133,7 +5152,7 @@ void CMinecraftApp::NotificationsCallback(LPVOID pParam,DWORD dwNotification, un for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { if(!InputManager.IsPadConnected(i) && - Minecraft::GetInstance()->localplayers[i] != NULL && + Minecraft::GetInstance()->localplayers[i] != nullptr && !ui.IsPauseMenuDisplayed(i) && !ui.IsSceneInStack(i, eUIScene_EndPoem) ) { ui.CloseUIScenes(i); @@ -5162,7 +5181,7 @@ void CMinecraftApp::NotificationsCallback(LPVOID pParam,DWORD dwNotification, un { DLCTexturePack *pDLCTexPack=(DLCTexturePack *)pTexPack; XCONTENTDEVICEID deviceID = pDLCTexPack->GetDLCDeviceID(); - if( XContentGetDeviceState( deviceID, NULL ) != ERROR_SUCCESS ) + if( XContentGetDeviceState( deviceID, nullptr ) != ERROR_SUCCESS ) { // Set texture pack flag so that it is now considered as not having audio - this is critical so that the next playStreaming does what it is meant to do, // and also so that we don't try and unmount this again, or play any sounds from it in the future @@ -5170,11 +5189,11 @@ void CMinecraftApp::NotificationsCallback(LPVOID pParam,DWORD dwNotification, un // need to stop the streaming audio - by playing streaming audio from the default texture pack now Minecraft::GetInstance()->soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); - if(pDLCTexPack->m_pStreamedWaveBank!=NULL) + if(pDLCTexPack->m_pStreamedWaveBank!=nullptr) { pDLCTexPack->m_pStreamedWaveBank->Destroy(); } - if(pDLCTexPack->m_pSoundBank!=NULL) + if(pDLCTexPack->m_pSoundBank!=nullptr) { pDLCTexPack->m_pSoundBank->Destroy(); } @@ -5300,7 +5319,7 @@ void CMinecraftApp::SetDebugSequence(const char *pchSeq) } int CMinecraftApp::DebugInputCallback(LPVOID pParam) { - CMinecraftApp* pClass = (CMinecraftApp*)pParam; + CMinecraftApp* pClass = static_cast(pParam); //printf("sequence matched\n"); pClass->m_bDebugOptions=!pClass->m_bDebugOptions; @@ -5326,7 +5345,7 @@ int CMinecraftApp::GetLocalPlayerCount(void) Minecraft *pMinecraft = Minecraft::GetInstance(); for(int i=0;ilocalplayers[i] != NULL) + if(pMinecraft != nullptr && pMinecraft->localplayers[i] != nullptr) { iPlayerC++; } @@ -5476,15 +5495,15 @@ int CMinecraftApp::DLCMountedCallback(LPVOID pParam,int iPad,DWORD dwErr,DWORD d DLCPack *pack = app.m_dlcManager.getPack( CONTENT_DATA_DISPLAY_NAME(ContentData) ); - if( pack != NULL && pack->IsCorrupt() ) + if( pack != nullptr && pack->IsCorrupt() ) { app.DebugPrintf("Pack '%ls' is corrupt, removing it from the DLC Manager.\n", CONTENT_DATA_DISPLAY_NAME(ContentData)); app.m_dlcManager.removePack(pack); - pack = NULL; + pack = nullptr; } - if(pack == NULL) + if(pack == nullptr) { app.DebugPrintf("Pack \"%ls\" is not installed, so adding it\n", CONTENT_DATA_DISPLAY_NAME(ContentData)); @@ -5536,8 +5555,8 @@ int CMinecraftApp::DLCMountedCallback(LPVOID pParam,int iPad,DWORD dwErr,DWORD d // bool bRes=app.IsFileInMemoryTextures(wTemp); // // if the file is not already in the memory textures, then read it from TMS // if(!bRes) -// { -// BYTE *pBuffer=NULL; +// { +// BYTE* pBuffer = nullptr; // DWORD dwSize=0; // // 4J-PB - out for now for DaveK so he doesn't get the birthday cape // #ifdef _CONTENT_PACKAGE @@ -5566,7 +5585,7 @@ void CMinecraftApp::HandleDLC(DLCPack *pack) // 4J Stu - I don't know why we handle more than one file here any more, however this doesn't seem to work with the PS4 patches if(dlcFilenames.size() > 0) m_dlcManager.readDLCDataFile(dwFilesProcessed, dlcFilenames[0], pack); #else - for(int i=0; i(qwTicksPerSec.QuadPart); // Save the start time QueryPerformanceCounter( &m_Time.qwTime ); @@ -5671,16 +5690,10 @@ void CMinecraftApp::UpdateTime() m_Time.qwAppTime.QuadPart += qwDeltaTime.QuadPart; m_Time.qwTime.QuadPart = qwNewTime.QuadPart; - m_Time.fElapsedTime = m_Time.fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - m_Time.fAppTime = m_Time.fSecsPerTick * ((FLOAT)(m_Time.qwAppTime.QuadPart)); + m_Time.fElapsedTime = m_Time.fSecsPerTick * static_cast(qwDeltaTime.QuadPart); + m_Time.fAppTime = m_Time.fSecsPerTick * static_cast(m_Time.qwAppTime.QuadPart); } - - - - - - bool CMinecraftApp::isXuidNotch(PlayerUID xuid) { if(m_xuidNotch != INVALID_XUID && xuid != INVALID_XUID) @@ -5709,7 +5722,7 @@ void CMinecraftApp::AddMemoryTextureFile(const wstring &wName,PBYTE pbData,DWORD { EnterCriticalSection(&csMemFilesLock); // check it's not already in - PMEMDATA pData=NULL; + PMEMDATA pData=nullptr; auto it = m_MEM_Files.find(wName); if(it != m_MEM_Files.end()) { @@ -5720,8 +5733,8 @@ void CMinecraftApp::AddMemoryTextureFile(const wstring &wName,PBYTE pbData,DWORD if(pData->dwBytes == 0 && dwBytes != 0) { - // This should never be NULL if dwBytes is 0 - if(pData->pbData!=NULL) delete [] pData->pbData; + // This should never be nullptr if dwBytes is 0 + if(pData->pbData!=nullptr) delete [] pData->pbData; pData->pbData=pbData; pData->dwBytes=dwBytes; @@ -5817,7 +5830,7 @@ void CMinecraftApp::AddMemoryTPDFile(int iConfig,PBYTE pbData,DWORD dwBytes) { EnterCriticalSection(&csMemTPDLock); // check it's not already in - PMEMDATA pData=NULL; + PMEMDATA pData=nullptr; auto it = m_MEM_TPD.find(iConfig); if(it == m_MEM_TPD.end()) { @@ -5837,7 +5850,7 @@ void CMinecraftApp::RemoveMemoryTPDFile(int iConfig) { EnterCriticalSection(&csMemTPDLock); // check it's not already in - PMEMDATA pData=NULL; + PMEMDATA pData=nullptr; auto it = m_MEM_TPD.find(iConfig); if(it != m_MEM_TPD.end()) { @@ -5852,7 +5865,7 @@ void CMinecraftApp::RemoveMemoryTPDFile(int iConfig) #ifdef _XBOX int CMinecraftApp::GetTPConfigVal(WCHAR *pwchDataFile) { - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // run through the DLC info to find the right texture pack/mash-up pack for(unsigned int i = 0; i < app.GetDLCInfoTexturesOffersCount(); ++i) { @@ -5870,7 +5883,7 @@ int CMinecraftApp::GetTPConfigVal(WCHAR *pwchDataFile) #elif defined _XBOX_ONE int CMinecraftApp::GetTPConfigVal(WCHAR *pwchDataFile) { - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // run through the DLC info to find the right texture pack/mash-up pack for(unsigned int i = 0; i < app.GetDLCInfoTexturesOffersCount(); ++i) { @@ -5966,7 +5979,7 @@ void CMinecraftApp::ProcessInvite(DWORD dwUserIndex, DWORD dwLocalUsersMask, con int CMinecraftApp::ExitAndJoinFromInvite(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CMinecraftApp* pApp = (CMinecraftApp*)pParam; + CMinecraftApp* pApp = static_cast(pParam); //Minecraft *pMinecraft=Minecraft::GetInstance(); // buttons are swapped on this menu @@ -5980,7 +5993,7 @@ int CMinecraftApp::ExitAndJoinFromInvite(void *pParam,int iPad,C4JStorage::EMess int CMinecraftApp::ExitAndJoinFromInviteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CMinecraftApp *pClass = (CMinecraftApp *)pParam; + CMinecraftApp *pClass = static_cast(pParam); // Exit with or without saving // Decline means save in this dialog if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultThirdOption) @@ -6071,7 +6084,7 @@ int CMinecraftApp::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStor { // 4J-PB - need to check this user can access the store bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -6090,7 +6103,7 @@ int CMinecraftApp::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStor app.DebugPrintf("Texture Pack - %s\n",pchPackName); SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo((char *)pchPackName); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chSkuID[SCE_NP_COMMERCE2_SKU_ID_LEN]; @@ -6140,7 +6153,7 @@ int CMinecraftApp::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStor DLC_INFO *pDLCInfo=app.GetDLCInfoForProductName((WCHAR *)pDLCPack->getName().c_str()); - StorageManager.InstallOffer(1,(WCHAR *)pDLCInfo->wsProductId.c_str(),NULL,NULL); + StorageManager.InstallOffer(1,(WCHAR *)pDLCInfo->wsProductId.c_str(),nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } @@ -6173,7 +6186,7 @@ int CMinecraftApp::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStor // need to allow downloads here, or the player would need to quit the game to let the download of a texture pack happen. This might affect the network traffic, since the download could take all the bandwidth... XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } else @@ -6219,7 +6232,7 @@ int CMinecraftApp::ExitAndJoinFromInviteAndSaveReturned(void *pParam,int iPad,C4 uiIDA[1]=IDS_CONFIRM_CANCEL; // Give the player a warning about the trial version of the texture pack - ui.RequestErrorMessage(IDS_WARNING_DLC_TRIALTEXTUREPACK_TITLE, IDS_WARNING_DLC_TRIALTEXTUREPACK_TEXT, uiIDA, 2, iPad,&CMinecraftApp::WarningTrialTexturePackReturned,NULL); + ui.RequestErrorMessage(IDS_WARNING_DLC_TRIALTEXTUREPACK_TITLE, IDS_WARNING_DLC_TRIALTEXTUREPACK_TEXT, uiIDA, 2, iPad,&CMinecraftApp::WarningTrialTexturePackReturned,nullptr); return S_OK; } @@ -6731,7 +6744,7 @@ wstring CMinecraftApp::GetVKReplacement(unsigned int uiVKey) default: break; } - return NULL; + return nullptr; #else wstring replacement = L""; switch(uiVKey) @@ -6830,7 +6843,7 @@ wstring CMinecraftApp::GetIconReplacement(unsigned int uiIcon) default: break; } - return NULL; + return nullptr; #else wchar_t string[128]; @@ -6885,11 +6898,11 @@ HRESULT CMinecraftApp::RegisterMojangData(WCHAR *pXuidName, PlayerUID xuid, WCHA { HRESULT hr=S_OK; eXUID eTempXuid=eXUID_Undefined; - MOJANG_DATA *pMojangData=NULL; + MOJANG_DATA *pMojangData=nullptr; // ignore the names if we don't recognize them - if(pXuidName!=NULL) - { + if (pXuidName != nullptr) + { if( wcscmp( pXuidName, L"XUID_NOTCH" ) == 0 ) { eTempXuid = eXUID_Notch; // might be needed for the apple at some point @@ -6928,8 +6941,8 @@ HRESULT CMinecraftApp::RegisterConfigValues(WCHAR *pType, int iValue) HRESULT hr=S_OK; // #ifdef _XBOX - // if(pType!=NULL) - // { + // if(pType!=nullptr) + // { // if(wcscmp(pType,L"XboxOneTransfer")==0) // { // if(iValue>0) @@ -6979,8 +6992,8 @@ HRESULT CMinecraftApp::RegisterDLCData(WCHAR *pType, WCHAR *pBannerName, int iGe } #endif - if(pType!=NULL) - { + if(pType!=nullptr) + { if(wcscmp(pType,L"Skin")==0) { pDLCData->eDLCType=e_DLC_SkinPack; @@ -7164,7 +7177,7 @@ bool CMinecraftApp::GetDLCNameForPackID(const int iPackID,char **ppchKeyID) auto it = DLCTextures_PackID.find(iPackID); if( it == DLCTextures_PackID.end() ) { - *ppchKeyID=NULL; + *ppchKeyID=nullptr; return false; } else @@ -7184,21 +7197,21 @@ DLC_INFO *CMinecraftApp::GetDLCInfo(char *pchDLCName) if( it == DLCInfo.end() ) { // nothing for this - return NULL; + return nullptr; } else { return it->second; } } - else return NULL; + else return nullptr; } DLC_INFO *CMinecraftApp::GetDLCInfoFromTPackID(int iTPID) { unordered_map::iterator it= DLCInfo.begin(); - for(int i=0;isecond)->iConfig==iTPID) { @@ -7206,7 +7219,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfoFromTPackID(int iTPID) } ++it; } - return NULL; + return nullptr; } DLC_INFO *CMinecraftApp::GetDLCInfo(int iIndex) @@ -7262,12 +7275,12 @@ bool CMinecraftApp::GetDLCFullOfferIDForPackID(const int iPackID,wstring &Produc } // DLC_INFO *CMinecraftApp::GetDLCInfoForTrialOfferID(wstring &ProductId) // { -// return NULL; +// return nullptr; // } DLC_INFO *CMinecraftApp::GetDLCInfoTrialOffer(int iIndex) { - return NULL; + return nullptr; } DLC_INFO *CMinecraftApp::GetDLCInfoFullOffer(int iIndex) { @@ -7321,7 +7334,7 @@ bool CMinecraftApp::GetDLCFullOfferIDForPackID(const int iPackID,ULONGLONG *pull } DLC_INFO *CMinecraftApp::GetDLCInfoForTrialOfferID(ULONGLONG ullOfferID_Trial) { - //DLC_INFO *pDLCInfo=NULL; + //DLC_INFO *pDLCInfo=nullptr; if(DLCInfo_Trial.size()>0) { auto it = DLCInfo_Trial.find(ullOfferID_Trial); @@ -7329,14 +7342,14 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForTrialOfferID(ULONGLONG ullOfferID_Trial) if( it == DLCInfo_Trial.end() ) { // nothing for this - return NULL; + return nullptr; } else { return it->second; } } - else return NULL; + else return nullptr; } DLC_INFO *CMinecraftApp::GetDLCInfoTrialOffer(int iIndex) @@ -7386,21 +7399,21 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForFullOfferID(WCHAR *pwchProductID) if( it == DLCInfo_Full.end() ) { // nothing for this - return NULL; + return nullptr; } else { return it->second; } } - else return NULL; + else return nullptr; } DLC_INFO *CMinecraftApp::GetDLCInfoForProductName(WCHAR *pwchProductName) { unordered_map::iterator it= DLCInfo_Full.begin(); wstring wsProductName=pwchProductName; - for(int i=0;isecond; if(wsProductName==pDLCInfo->wsDisplayName) @@ -7410,7 +7423,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForProductName(WCHAR *pwchProductName) ++it; } - return NULL; + return nullptr; } #elif defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) @@ -7426,14 +7439,14 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForFullOfferID(ULONGLONG ullOfferID_Full) if( it == DLCInfo_Full.end() ) { // nothing for this - return NULL; + return nullptr; } else { return it->second; } } - else return NULL; + else return nullptr; } #endif @@ -7524,7 +7537,7 @@ void CMinecraftApp::ExitGameFromRemoteSave( LPVOID lpParameter ) uiIDA[0]=IDS_CONFIRM_CANCEL; uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestAlertMessage(IDS_EXIT_GAME, IDS_CONFIRM_EXIT_GAME, uiIDA, 2, primaryPad,&CMinecraftApp::ExitGameFromRemoteSaveDialogReturned,NULL); + ui.RequestAlertMessage(IDS_EXIT_GAME, IDS_CONFIRM_EXIT_GAME, uiIDA, 2, primaryPad,&CMinecraftApp::ExitGameFromRemoteSaveDialogReturned,nullptr); } int CMinecraftApp::ExitGameFromRemoteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) @@ -7540,9 +7553,9 @@ int CMinecraftApp::ExitGameFromRemoteSaveDialogReturned(void *pParam,int iPad,C4 { #ifndef _XBOX // Inform fullscreen progress scene that it's not being cancelled after all - UIScene_FullscreenProgress *pScene = (UIScene_FullscreenProgress *)ui.FindScene(eUIScene_FullscreenProgress); + UIScene_FullscreenProgress *pScene = static_cast(ui.FindScene(eUIScene_FullscreenProgress)); #ifdef __PS3__ - if(pScene!=NULL) + if(pScene!=nullptr) #else if (pScene != nullptr) #endif @@ -7558,7 +7571,7 @@ int CMinecraftApp::ExitGameFromRemoteSaveDialogReturned(void *pParam,int iPad,C4 void CMinecraftApp::SetSpecialTutorialCompletionFlag(int iPad, int index) { - if(index >= 0 && index < 32 && GameSettingsA[iPad] != NULL) + if(index >= 0 && index < 32 && GameSettingsA[iPad] != nullptr) { GameSettingsA[iPad]->uiSpecialTutorialBitmask |= (1<pszLevelName,pszLevelName); m_vBannedListA[iPad]->push_back(pBannedListData); - if(bWriteToTMS) - { - DWORD dwDataBytes=(DWORD)(sizeof(BANNEDLISTDATA)*m_vBannedListA[iPad]->size()); - PBANNEDLISTDATA pBannedList = (BANNEDLISTDATA *)(new CHAR [dwDataBytes]); + if (bWriteToTMS) + { + DWORD dwDataBytes = static_cast(sizeof(BANNEDLISTDATA)* m_vBannedListA[iPad]->size()); + PBANNEDLISTDATA pBannedList = reinterpret_cast(new CHAR [dwDataBytes]); int iCount=0; for (PBANNEDLISTDATA pData : *m_vBannedListA[iPad] ) { @@ -7630,9 +7643,9 @@ void CMinecraftApp::AddLevelToBannedLevelList(int iPad, PlayerUID xuid, char *ps //bool bRes=StorageManager.WriteTMSFile(iPad,C4JStorage::eGlobalStorage_TitleUser,L"BannedList",(PBYTE)pBannedList, dwDataBytes); #ifdef _XBOX - StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,C4JStorage::TMS_UGCTYPE_NONE,"BannedList",(PCHAR) pBannedList, dwDataBytes,NULL,NULL, 0); + StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,C4JStorage::TMS_UGCTYPE_NONE,"BannedList",(PCHAR) pBannedList, dwDataBytes,nullptr,nullptr, 0); #elif defined _XBOX_ONE - StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",(PBYTE) pBannedList, dwDataBytes,NULL,NULL, 0); + StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",(PBYTE) pBannedList, dwDataBytes,nullptr,nullptr, 0); #endif } // update telemetry too @@ -7666,7 +7679,7 @@ void CMinecraftApp::RemoveLevelFromBannedLevelList(int iPad, PlayerUID xuid, cha { PBANNEDLISTDATA pBannedListData = *it; - if(pBannedListData!=NULL) + if(pBannedListData!=nullptr) { #ifdef _XBOX_ONE PlayerUID bannedPlayerUID = pBannedListData->wchPlayerUID; @@ -7691,22 +7704,22 @@ void CMinecraftApp::RemoveLevelFromBannedLevelList(int iPad, PlayerUID xuid, cha } } - DWORD dwDataBytes=(DWORD)(sizeof(BANNEDLISTDATA)*m_vBannedListA[iPad]->size()); + DWORD dwDataBytes=static_cast(sizeof(BANNEDLISTDATA) * m_vBannedListA[iPad]->size()); if(dwDataBytes==0) { // wipe the file #ifdef _XBOX StorageManager.DeleteTMSFile(iPad,C4JStorage::eGlobalStorage_TitleUser,L"BannedList"); #elif defined _XBOX_ONE - StorageManager.TMSPP_DeleteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",NULL,NULL, 0); + StorageManager.TMSPP_DeleteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",nullptr,nullptr, 0); #endif } else { PBANNEDLISTDATA pBannedList = (BANNEDLISTDATA *)(new BYTE [dwDataBytes]); - int iSize=(int)m_vBannedListA[iPad]->size(); - for(int i=0;isize(); + for(size_t i=0;iat(i); @@ -7715,7 +7728,7 @@ void CMinecraftApp::RemoveLevelFromBannedLevelList(int iPad, PlayerUID xuid, cha #ifdef _XBOX StorageManager.WriteTMSFile(iPad,C4JStorage::eGlobalStorage_TitleUser,L"BannedList",(PBYTE)pBannedList, dwDataBytes); #elif defined _XBOX_ONE - StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",(PBYTE) pBannedList, dwDataBytes,NULL,NULL, 0); + StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"BannedList",(PBYTE) pBannedList, dwDataBytes,nullptr,nullptr, 0); #endif delete [] pBannedList; } @@ -7759,7 +7772,7 @@ bool CMinecraftApp::AlreadySeenCreditText(const wstring &wstemp) unsigned int CMinecraftApp::GetDLCCreditsCount() { - return (unsigned int)vDLCCredits.size(); + return static_cast(vDLCCredits.size()); } SCreditTextItemDef * CMinecraftApp::GetDLCCredits(int iIndex) @@ -8179,7 +8192,7 @@ unsigned int CMinecraftApp::GetGameHostOption(unsigned int uiHostSettings, eGame bool CMinecraftApp::CanRecordStatsAndAchievements() { - bool isTutorial = Minecraft::GetInstance() != NULL && Minecraft::GetInstance()->isTutorial(); + bool isTutorial = Minecraft::GetInstance() != nullptr && Minecraft::GetInstance()->isTutorial(); // 4J Stu - All of these options give the host player some advantage, so should not allow achievements return !(app.GetGameHostOption(eGameHostOption_HasBeenInCreative) || app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) || @@ -8878,7 +8891,7 @@ int CMinecraftApp::TMSPPFileReturned(LPVOID pParam,int iPad,int iUserData,C4JSto { #endif - CMinecraftApp* pClass = (CMinecraftApp *) pParam; + CMinecraftApp* pClass = static_cast(pParam); // find the right one in the vector EnterCriticalSection(&pClass->csTMSPPDownloadQueue); @@ -8897,9 +8910,8 @@ int CMinecraftApp::TMSPPFileReturned(LPVOID pParam,int iPad,int iUserData,C4JSto // set this to retrieved whether it found it or not pCurrent->eState=e_TMS_ContentState_Retrieved; - if(pFileData!=NULL) - { - + if(pFileData!=nullptr) + { #ifdef _XBOX_ONE @@ -9139,7 +9151,7 @@ void CMinecraftApp::ClearTMSPPFilesRetrieved() int CMinecraftApp::DLCOffersReturned(void *pParam, int iOfferC, DWORD dwType, int iPad) { - CMinecraftApp* pClass = (CMinecraftApp *) pParam; + CMinecraftApp* pClass = static_cast(pParam); // find the right one in the vector EnterCriticalSection(&pClass->csTMSPPDownloadQueue); @@ -9164,10 +9176,10 @@ eDLCContentType CMinecraftApp::Find_eDLCContentType(DWORD dwType) { if(m_dwContentTypeA[i]==dwType) { - return (eDLCContentType)i; + return static_cast(i); } } - return (eDLCContentType)0; + return static_cast(0); } bool CMinecraftApp::DLCContentRetrieved(eDLCMarketplaceType eType) { @@ -9250,7 +9262,7 @@ vector * CMinecraftApp::SetAdditionalSkinBoxes(DWORD dwSkinID, vect vector *CMinecraftApp::GetAdditionalModelParts(DWORD dwSkinID) { EnterCriticalSection( &csAdditionalModelParts ); - vector *pvModelParts=NULL; + vector *pvModelParts=nullptr; if(m_AdditionalModelParts.size()>0) { auto it = m_AdditionalModelParts.find(dwSkinID); @@ -9267,7 +9279,7 @@ vector *CMinecraftApp::GetAdditionalModelParts(DWORD dwSkinID) vector *CMinecraftApp::GetAdditionalSkinBoxes(DWORD dwSkinID) { EnterCriticalSection( &csAdditionalSkinBoxes ); - vector *pvSkinBoxes=NULL; + vector *pvSkinBoxes=nullptr; if(m_AdditionalSkinBoxes.size()>0) { auto it = m_AdditionalSkinBoxes.find(dwSkinID); @@ -9371,95 +9383,92 @@ wstring CMinecraftApp::getSkinPathFromId(DWORD skinId) } -int CMinecraftApp::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) +int CMinecraftApp::TexturePackDialogReturned(void* pParam, int iPad, C4JStorage::EMessageResult result) { - #if defined __PSVITA__ || defined __PS3__ || defined __ORBIS__ - if(result==C4JStorage::EMessage_ResultAccept) - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->skins->selectTexturePackById(app.GetRequiredTexturePackID()) ) - { - // it's been installed already - } - else - { - // we need to enable background downloading for the DLC - XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(app.GetRequiredTexturePackID()); - if(pSONYDLCInfo!=NULL) - { - char chName[42]; - char chKeyName[20]; - char chSkuID[SCE_NP_COMMERCE2_SKU_ID_LEN]; + if (result == C4JStorage::EMessage_ResultAccept) + { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->skins->selectTexturePackById(app.GetRequiredTexturePackID())) + { + // it's been installed already + } + else + { + // we need to enable background downloading for the DLC + XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - memset(chSkuID,0,SCE_NP_COMMERCE2_SKU_ID_LEN); - // we have to retrieve the skuid from the store info, it can't be hardcoded since Sony may change it. - // So we assume the first sku for the product is the one we want - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char - memset(chKeyName, 0, sizeof(chKeyName)); - strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); + SONYDLC* pSONYDLCInfo = app.GetSONYDLCInfo(app.GetRequiredTexturePackID()); + if (pSONYDLCInfo != nullptr) + { + char chName[42]; + char chKeyName[20]; + char chSkuID[SCE_NP_COMMERCE2_SKU_ID_LEN]; - #ifdef __ORBIS__ - strcpy(chName, chKeyName); - #else - sprintf(chName,"%s-%s",app.GetCommerceCategory(),chKeyName); - #endif - app.GetDLCSkuIDFromProductList(chName,chSkuID); - // 4J-PB - need to check for an empty store - if(app.CheckForEmptyStore(iPad)==false) - { - if(app.DLCAlreadyPurchased(chSkuID)) - { - app.DownloadAlreadyPurchased(chSkuID); - } - else - { - app.Checkout(chSkuID); - } - } - } - } - } - else - { - app.DebugPrintf("Continuing without installing texture pack\n"); - } + memset(chSkuID, 0, SCE_NP_COMMERCE2_SKU_ID_LEN); + + memset(chKeyName, 0, sizeof(chKeyName)); + strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); + + #ifdef __ORBIS__ + strcpy(chName, chKeyName); + #else + sprintf(chName, "%s-%s", app.GetCommerceCategory(), chKeyName); + #endif + + app.GetDLCSkuIDFromProductList(chName, chSkuID); + + if (app.CheckForEmptyStore(iPad) == false) + { + if (app.DLCAlreadyPurchased(chSkuID)) + { + app.DownloadAlreadyPurchased(chSkuID); + } + else + { + app.Checkout(chSkuID); + } + } + } + } + } + else + { + app.DebugPrintf("Continuing without installing texture pack\n"); + } #endif #ifdef _XBOX - if(result!=C4JStorage::EMessage_Cancelled) - { - if(app.GetRequiredTexturePackID()!=0) - { - // we need to enable background downloading for the DLC - XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); + if (result != C4JStorage::EMessage_Cancelled) + { + if (app.GetRequiredTexturePackID() != 0) + { + XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - ULONGLONG ullOfferID_Full; - ULONGLONG ullIndexA[1]; - app.GetDLCFullOfferIDForPackID(app.GetRequiredTexturePackID(),&ullOfferID_Full); + ULONGLONG ullOfferID_Full; + ULONGLONG ullIndexA[1]; + app.GetDLCFullOfferIDForPackID(app.GetRequiredTexturePackID(), &ullOfferID_Full); - if( result==C4JStorage::EMessage_ResultAccept ) // Full version - { - ullIndexA[0]=ullOfferID_Full; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); - } - else // trial version - { - DLC_INFO *pDLCInfo=app.GetDLCInfoForFullOfferID(ullOfferID_Full); - ullIndexA[0]=pDLCInfo->ullOfferID_Trial; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); - } - } - } + if (result == C4JStorage::EMessage_ResultAccept) + { + ullIndexA[0] = ullOfferID_Full; + StorageManager.InstallOffer(1, ullIndexA, nullptr, nullptr); + } + else + { + DLC_INFO* pDLCInfo = app.GetDLCInfoForFullOfferID(ullOfferID_Full); + ullIndexA[0] = pDLCInfo->ullOfferID_Trial; + StorageManager.InstallOffer(1, ullIndexA, nullptr, nullptr); + } + } + } #endif - return 0; + return 0; } - int CMinecraftApp::getArchiveFileSize(const wstring &filename) { - TexturePack *tPack = NULL; + TexturePack *tPack = nullptr; Minecraft *pMinecraft = Minecraft::GetInstance(); if(pMinecraft && pMinecraft->skins) tPack = pMinecraft->skins->getSelected(); if(tPack && tPack->hasData() && tPack->getArchiveFile() && tPack->getArchiveFile()->hasFile(filename)) @@ -9471,7 +9480,7 @@ int CMinecraftApp::getArchiveFileSize(const wstring &filename) bool CMinecraftApp::hasArchiveFile(const wstring &filename) { - TexturePack *tPack = NULL; + TexturePack *tPack = nullptr; Minecraft *pMinecraft = Minecraft::GetInstance(); if(pMinecraft && pMinecraft->skins) tPack = pMinecraft->skins->getSelected(); if(tPack && tPack->hasData() && tPack->getArchiveFile() && tPack->getArchiveFile()->hasFile(filename)) return true; @@ -9480,7 +9489,7 @@ bool CMinecraftApp::hasArchiveFile(const wstring &filename) byteArray CMinecraftApp::getArchiveFile(const wstring &filename) { - TexturePack *tPack = NULL; + TexturePack *tPack = nullptr; Minecraft *pMinecraft = Minecraft::GetInstance(); if(pMinecraft && pMinecraft->skins) tPack = pMinecraft->skins->getSelected(); if(tPack && tPack->hasData() && tPack->getArchiveFile() && tPack->getArchiveFile()->hasFile(filename)) @@ -9509,19 +9518,19 @@ int CMinecraftApp::GetDLCInfoFullOffersCount() } #else int CMinecraftApp::GetDLCInfoTrialOffersCount() -{ - return (int)DLCInfo_Trial.size(); +{ + return static_cast(DLCInfo_Trial.size()); } -int CMinecraftApp::GetDLCInfoFullOffersCount() -{ - return (int)DLCInfo_Full.size(); +int CMinecraftApp::GetDLCInfoFullOffersCount() +{ + return static_cast(DLCInfo_Full.size()); } #endif int CMinecraftApp::GetDLCInfoTexturesOffersCount() -{ - return (int)DLCTextures_PackID.size(); +{ + return static_cast(DLCTextures_PackID.size()); } // AUTOSAVE @@ -9821,7 +9830,7 @@ void CMinecraftApp::getLocale(vector &vecWstrLocales) locales.push_back(eMCLang_enUS); locales.push_back(eMCLang_null); - for (int i=0; i(0), bool bCallback=false)=0; private: @@ -862,12 +862,12 @@ public: bool GetBanListRead(int iPad) { return m_bRead_BannedListA[iPad];} void SetBanListRead(int iPad,bool bVal) { m_bRead_BannedListA[iPad]=bVal;} - void ClearBanList(int iPad) { BannedListA[iPad].pBannedList=NULL;BannedListA[iPad].dwBytes=0;} + void ClearBanList(int iPad) { BannedListA[iPad].pBannedList=nullptr;BannedListA[iPad].dwBytes=0;} DWORD GetRequiredTexturePackID() {return m_dwRequiredTexturePackID;} void SetRequiredTexturePackID(DWORD dwID) {m_dwRequiredTexturePackID=dwID;} - virtual void GetFileFromTPD(eTPDFileType eType,PBYTE pbData,DWORD dwBytes,PBYTE *ppbData,DWORD *pdwBytes ) {*ppbData = NULL; *pdwBytes = 0;} + virtual void GetFileFromTPD(eTPDFileType eType,PBYTE pbData,DWORD dwBytes,PBYTE *ppbData,DWORD *pdwBytes ) {*ppbData = nullptr; *pdwBytes = 0;} //XTITLE_DEPLOYMENT_TYPE getDeploymentType() { return m_titleDeploymentType; } diff --git a/Minecraft.Client/Common/DLC/DLCAudioFile.cpp b/Minecraft.Client/Common/DLC/DLCAudioFile.cpp index 7116f62d8..ee0cb7a72 100644 --- a/Minecraft.Client/Common/DLC/DLCAudioFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCAudioFile.cpp @@ -8,7 +8,7 @@ DLCAudioFile::DLCAudioFile(const wstring &path) : DLCFile(DLCManager::e_DLCType_Audio,path) { - m_pbData = NULL; + m_pbData = nullptr; m_dwBytes = 0; } @@ -40,7 +40,7 @@ DLCAudioFile::EAudioParameterType DLCAudioFile::getParameterType(const wstring & { if(paramName.compare(wchTypeNamesA[i]) == 0) { - type = (EAudioParameterType)i; + type = static_cast(i); break; } } @@ -87,7 +87,7 @@ void DLCAudioFile::addParameter(EAudioType type, EAudioParameterType ptype, cons { i++; } - int iLast=(int)creditValue.find_last_of(L" ",i); + size_t iLast=creditValue.find_last_of(L" ", i); switch(XGetLanguage()) { case XC_LANGUAGE_JAPANESE: @@ -96,7 +96,7 @@ void DLCAudioFile::addParameter(EAudioType type, EAudioParameterType ptype, cons iLast = maximumChars; break; default: - iLast=(int)creditValue.find_last_of(L" ",i); + iLast=creditValue.find_last_of(L" ", i); break; } @@ -133,7 +133,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) if(uiVersion < CURRENT_AUDIO_VERSION_NUM) { - if(pbData!=NULL) delete [] pbData; + if(pbData!=nullptr) delete [] pbData; app.DebugPrintf("DLC version of %d is too old to be read\n", uiVersion); return false; } @@ -145,7 +145,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) for(unsigned int i=0;iwchData); + wstring parameterName(static_cast(pParams->wchData)); EAudioParameterType type = getParameterType(parameterName); if( type != e_AudioParamType_Invalid ) { @@ -169,7 +169,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) for(unsigned int i=0;idwType; + EAudioType type = static_cast(pFile->dwType); // Params unsigned int uiParameterCount=*(unsigned int *)pbTemp; pbTemp+=sizeof(int); @@ -182,7 +182,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) if(it != parameterMapping.end() ) { - addParameter(type,(EAudioParameterType)pParams->dwType,(WCHAR *)pParams->wchData); + addParameter(type,static_cast(pParams->dwType),(WCHAR *)pParams->wchData); } pbTemp+=sizeof(C4JStorage::DLC_FILE_PARAM)+(sizeof(WCHAR)*pParams->dwWchCount); pParams = (C4JStorage::DLC_FILE_PARAM *)pbTemp; @@ -198,7 +198,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) return true; } -int DLCAudioFile::GetCountofType(DLCAudioFile::EAudioType eType) +int DLCAudioFile::GetCountofType(EAudioType eType) { return m_parameters[eType].size(); } diff --git a/Minecraft.Client/Common/DLC/DLCAudioFile.h b/Minecraft.Client/Common/DLC/DLCAudioFile.h index f1a356fe9..501317859 100644 --- a/Minecraft.Client/Common/DLC/DLCAudioFile.h +++ b/Minecraft.Client/Common/DLC/DLCAudioFile.h @@ -32,11 +32,11 @@ public: DLCAudioFile(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); - virtual PBYTE getData(DWORD &dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; + PBYTE getData(DWORD &dwBytes) override; bool processDLCDataFile(PBYTE pbData, DWORD dwLength); - int GetCountofType(DLCAudioFile::EAudioType ptype); + int GetCountofType(EAudioType ptype); wstring &GetSoundName(int iIndex); private: @@ -49,6 +49,6 @@ private: vector m_parameters[e_AudioType_Max]; // use the EAudioType to order these - void addParameter(DLCAudioFile::EAudioType type, DLCAudioFile::EAudioParameterType ptype, const wstring &value); - DLCAudioFile::EAudioParameterType getParameterType(const wstring ¶mName); + void addParameter(EAudioType type, EAudioParameterType ptype, const wstring &value); + EAudioParameterType getParameterType(const wstring ¶mName); }; diff --git a/Minecraft.Client/Common/DLC/DLCCapeFile.h b/Minecraft.Client/Common/DLC/DLCCapeFile.h index 8373d340a..9e9466c6e 100644 --- a/Minecraft.Client/Common/DLC/DLCCapeFile.h +++ b/Minecraft.Client/Common/DLC/DLCCapeFile.h @@ -6,5 +6,5 @@ class DLCCapeFile : public DLCFile public: DLCCapeFile(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCColourTableFile.cpp b/Minecraft.Client/Common/DLC/DLCColourTableFile.cpp index ec800dacf..a0c818a7c 100644 --- a/Minecraft.Client/Common/DLC/DLCColourTableFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCColourTableFile.cpp @@ -7,12 +7,12 @@ DLCColourTableFile::DLCColourTableFile(const wstring &path) : DLCFile(DLCManager::e_DLCType_ColourTable,path) { - m_colourTable = NULL; + m_colourTable = nullptr; } DLCColourTableFile::~DLCColourTableFile() { - if(m_colourTable != NULL) + if(m_colourTable != nullptr) { app.DebugPrintf("Deleting DLCColourTableFile data\n"); delete m_colourTable; diff --git a/Minecraft.Client/Common/DLC/DLCColourTableFile.h b/Minecraft.Client/Common/DLC/DLCColourTableFile.h index 842697391..ded6f515e 100644 --- a/Minecraft.Client/Common/DLC/DLCColourTableFile.h +++ b/Minecraft.Client/Common/DLC/DLCColourTableFile.h @@ -10,9 +10,9 @@ private: public: DLCColourTableFile(const wstring &path); - ~DLCColourTableFile(); + ~DLCColourTableFile() override; - virtual void addData(PBYTE pbData, DWORD dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; - ColourTable *getColourTable() { return m_colourTable; } + ColourTable *getColourTable() const { return m_colourTable; } }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCFile.h b/Minecraft.Client/Common/DLC/DLCFile.h index 3a40dbc76..31b638ef6 100644 --- a/Minecraft.Client/Common/DLC/DLCFile.h +++ b/Minecraft.Client/Common/DLC/DLCFile.h @@ -12,12 +12,12 @@ public: DLCFile(DLCManager::EDLCType type, const wstring &path); virtual ~DLCFile() {} - DLCManager::EDLCType getType() { return m_type; } + DLCManager::EDLCType getType() const { return m_type; } wstring getPath() { return m_path; } - DWORD getSkinID() { return m_dwSkinId; } + DWORD getSkinID() const { return m_dwSkinId; } virtual void addData(PBYTE pbData, DWORD dwBytes) {} - virtual PBYTE getData(DWORD &dwBytes) { dwBytes = 0; return NULL; } + virtual PBYTE getData(DWORD &dwBytes) { dwBytes = 0; return nullptr; } virtual void addParameter(DLCManager::EDLCParameterType type, const wstring &value) {} virtual wstring getParameterAsString(DLCManager::EDLCParameterType type) { return L""; } diff --git a/Minecraft.Client/Common/DLC/DLCGameRulesFile.cpp b/Minecraft.Client/Common/DLC/DLCGameRulesFile.cpp index 8ca520d68..d84e2a609 100644 --- a/Minecraft.Client/Common/DLC/DLCGameRulesFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCGameRulesFile.cpp @@ -4,7 +4,7 @@ DLCGameRulesFile::DLCGameRulesFile(const wstring &path) : DLCGameRules(DLCManager::e_DLCType_GameRules,path) { - m_pbData = NULL; + m_pbData = nullptr; m_dwBytes = 0; } diff --git a/Minecraft.Client/Common/DLC/DLCGameRulesFile.h b/Minecraft.Client/Common/DLC/DLCGameRulesFile.h index e6456d73a..671cab6a9 100644 --- a/Minecraft.Client/Common/DLC/DLCGameRulesFile.h +++ b/Minecraft.Client/Common/DLC/DLCGameRulesFile.h @@ -10,6 +10,6 @@ private: public: DLCGameRulesFile(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); - virtual PBYTE getData(DWORD &dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; + PBYTE getData(DWORD &dwBytes) override; }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCGameRulesHeader.cpp b/Minecraft.Client/Common/DLC/DLCGameRulesHeader.cpp index 39b852190..2b7859987 100644 --- a/Minecraft.Client/Common/DLC/DLCGameRulesHeader.cpp +++ b/Minecraft.Client/Common/DLC/DLCGameRulesHeader.cpp @@ -11,14 +11,14 @@ DLCGameRulesHeader::DLCGameRulesHeader(const wstring &path) : DLCGameRules(DLCManager::e_DLCType_GameRulesHeader,path) { - m_pbData = NULL; + m_pbData = nullptr; m_dwBytes = 0; m_hasData = false; m_grfPath = path.substr(0, path.length() - 4) + L".grf"; - lgo = NULL; + lgo = nullptr; } void DLCGameRulesHeader::addData(PBYTE pbData, DWORD dwBytes) diff --git a/Minecraft.Client/Common/DLC/DLCGameRulesHeader.h b/Minecraft.Client/Common/DLC/DLCGameRulesHeader.h index 4521ae110..7409540d1 100644 --- a/Minecraft.Client/Common/DLC/DLCGameRulesHeader.h +++ b/Minecraft.Client/Common/DLC/DLCGameRulesHeader.h @@ -14,29 +14,52 @@ private: bool m_hasData; public: - virtual bool requiresTexturePack() {return m_bRequiresTexturePack;} - virtual UINT getRequiredTexturePackId() {return m_requiredTexturePackId;} - virtual wstring getDefaultSaveName() {return m_defaultSaveName;} - virtual LPCWSTR getWorldName() {return m_worldName.c_str();} - virtual LPCWSTR getDisplayName() {return m_displayName.c_str();} - virtual wstring getGrfPath() {return L"GameRules.grf";} + bool requiresTexturePack() override + {return m_bRequiresTexturePack;} - virtual void setRequiresTexturePack(bool x) {m_bRequiresTexturePack = x;} - virtual void setRequiredTexturePackId(UINT x) {m_requiredTexturePackId = x;} - virtual void setDefaultSaveName(const wstring &x) {m_defaultSaveName = x;} - virtual void setWorldName(const wstring & x) {m_worldName = x;} - virtual void setDisplayName(const wstring & x) {m_displayName = x;} - virtual void setGrfPath(const wstring & x) {m_grfPath = x;} + UINT getRequiredTexturePackId() override + {return m_requiredTexturePackId;} + + wstring getDefaultSaveName() override + {return m_defaultSaveName;} + + LPCWSTR getWorldName() override + {return m_worldName.c_str();} + + LPCWSTR getDisplayName() override + {return m_displayName.c_str();} + + wstring getGrfPath() override + {return L"GameRules.grf";} + + void setRequiresTexturePack(bool x) override + {m_bRequiresTexturePack = x;} + + void setRequiredTexturePackId(UINT x) override + {m_requiredTexturePackId = x;} + + void setDefaultSaveName(const wstring &x) override + {m_defaultSaveName = x;} + + void setWorldName(const wstring & x) override + {m_worldName = x;} + + void setDisplayName(const wstring & x) override + {m_displayName = x;} + + void setGrfPath(const wstring & x) override + {m_grfPath = x;} LevelGenerationOptions *lgo; public: DLCGameRulesHeader(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); - virtual PBYTE getData(DWORD &dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; + PBYTE getData(DWORD &dwBytes) override; void setGrfData(PBYTE fData, DWORD fSize, StringTable *); - virtual bool ready() { return m_hasData; } + bool ready() override + { return m_hasData; } }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCLocalisationFile.cpp b/Minecraft.Client/Common/DLC/DLCLocalisationFile.cpp index 358a93e50..909214345 100644 --- a/Minecraft.Client/Common/DLC/DLCLocalisationFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCLocalisationFile.cpp @@ -5,7 +5,7 @@ DLCLocalisationFile::DLCLocalisationFile(const wstring &path) : DLCFile(DLCManager::e_DLCType_LocalisationData,path) { - m_strings = NULL; + m_strings = nullptr; } void DLCLocalisationFile::addData(PBYTE pbData, DWORD dwBytes) diff --git a/Minecraft.Client/Common/DLC/DLCLocalisationFile.h b/Minecraft.Client/Common/DLC/DLCLocalisationFile.h index 083e60d8b..419d714d6 100644 --- a/Minecraft.Client/Common/DLC/DLCLocalisationFile.h +++ b/Minecraft.Client/Common/DLC/DLCLocalisationFile.h @@ -12,7 +12,7 @@ public: DLCLocalisationFile(const wstring &path); DLCLocalisationFile(PBYTE pbData, DWORD dwBytes); // when we load in a texture pack details file from TMS++ - virtual void addData(PBYTE pbData, DWORD dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; StringTable *getStringTable() { return m_strings; } }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCManager.cpp b/Minecraft.Client/Common/DLC/DLCManager.cpp index dd34e67f9..931b0e1d9 100644 --- a/Minecraft.Client/Common/DLC/DLCManager.cpp +++ b/Minecraft.Client/Common/DLC/DLCManager.cpp @@ -6,6 +6,7 @@ #include "..\..\..\Minecraft.World\StringHelpers.h" #include "..\..\Minecraft.h" #include "..\..\TexturePackRepository.h" +#include "Common/UI/UI.h" const WCHAR *DLCManager::wchTypeNamesA[]= { @@ -47,7 +48,7 @@ DLCManager::EDLCParameterType DLCManager::getParameterType(const wstring ¶mN { if(paramName.compare(wchTypeNamesA[i]) == 0) { - type = (EDLCParameterType)i; + type = static_cast(i); break; } } @@ -70,7 +71,7 @@ DWORD DLCManager::getPackCount(EDLCType type /*= e_DLCType_All*/) } else { - packCount = (DWORD)m_packs.size(); + packCount = static_cast(m_packs.size()); } return packCount; } @@ -82,7 +83,7 @@ void DLCManager::addPack(DLCPack *pack) void DLCManager::removePack(DLCPack *pack) { - if(pack != NULL) + if(pack != nullptr) { auto it = find(m_packs.begin(), m_packs.end(), pack); if(it != m_packs.end() ) m_packs.erase(it); @@ -112,7 +113,7 @@ void DLCManager::LanguageChanged(void) DLCPack *DLCManager::getPack(const wstring &name) { - DLCPack *pack = NULL; + DLCPack *pack = nullptr; //DWORD currentIndex = 0; for( DLCPack * currentPack : m_packs ) { @@ -130,7 +131,7 @@ DLCPack *DLCManager::getPack(const wstring &name) #ifdef _XBOX_ONE DLCPack *DLCManager::getPackFromProductID(const wstring &productID) { - DLCPack *pack = NULL; + DLCPack *pack = nullptr; for( DLCPack *currentPack : m_packs ) { wstring wsName=currentPack->getPurchaseOfferId(); @@ -147,7 +148,7 @@ DLCPack *DLCManager::getPackFromProductID(const wstring &productID) DLCPack *DLCManager::getPack(DWORD index, EDLCType type /*= e_DLCType_All*/) { - DLCPack *pack = NULL; + DLCPack *pack = nullptr; if( type != e_DLCType_All ) { DWORD currentIndex = 0; @@ -181,9 +182,9 @@ DWORD DLCManager::getPackIndex(DLCPack *pack, bool &found, EDLCType type /*= e_D { DWORD foundIndex = 0; found = false; - if(pack == NULL) + if(pack == nullptr) { - app.DebugPrintf("DLCManager: Attempting to find the index for a NULL pack\n"); + app.DebugPrintf("DLCManager: Attempting to find the index for a nullptr pack\n"); //__debugbreak(); return foundIndex; } @@ -244,7 +245,7 @@ DWORD DLCManager::getPackIndexContainingSkin(const wstring &path, bool &found) DLCPack *DLCManager::getPackContainingSkin(const wstring &path) { - DLCPack *foundPack = NULL; + DLCPack *foundPack = nullptr; for( DLCPack *pack : m_packs ) { if(pack->getDLCItemsCount(e_DLCType_Skin)>0) @@ -261,11 +262,11 @@ DLCPack *DLCManager::getPackContainingSkin(const wstring &path) DLCSkinFile *DLCManager::getSkinFile(const wstring &path) { - DLCSkinFile *foundSkinfile = NULL; + DLCSkinFile *foundSkinfile = nullptr; for( DLCPack *pack : m_packs ) { foundSkinfile=pack->getSkinFile(path); - if(foundSkinfile!=NULL) + if(foundSkinfile!=nullptr) { break; } @@ -276,14 +277,14 @@ DLCSkinFile *DLCManager::getSkinFile(const wstring &path) DWORD DLCManager::checkForCorruptDLCAndAlert(bool showMessage /*= true*/) { DWORD corruptDLCCount = m_dwUnnamedCorruptDLCCount; - DLCPack *firstCorruptPack = NULL; + DLCPack *firstCorruptPack = nullptr; for( DLCPack *pack : m_packs ) { if( pack->IsCorrupt() ) { ++corruptDLCCount; - if(firstCorruptPack == NULL) firstCorruptPack = pack; + if(firstCorruptPack == nullptr) firstCorruptPack = pack; } } @@ -291,13 +292,13 @@ DWORD DLCManager::checkForCorruptDLCAndAlert(bool showMessage /*= true*/) { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - if(corruptDLCCount == 1 && firstCorruptPack != NULL) + if(corruptDLCCount == 1 && firstCorruptPack != nullptr) { // pass in the pack format string WCHAR wchFormat[132]; swprintf(wchFormat, 132, L"%ls\n\n%%ls", firstCorruptPack->getName().c_str()); - C4JStorage::EMessageResult result = ui.RequestErrorMessage( IDS_CORRUPT_DLC_TITLE, IDS_CORRUPT_DLC, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL,wchFormat); + C4JStorage::EMessageResult result = ui.RequestErrorMessage( IDS_CORRUPT_DLC_TITLE, IDS_CORRUPT_DLC, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr,wchFormat); } else @@ -330,13 +331,13 @@ bool DLCManager::readDLCDataFile(DWORD &dwFilesProcessed, const string &path, DL #ifdef _WINDOWS64 string finalPath = StorageManager.GetMountedPath(path.c_str()); if(finalPath.size() == 0) finalPath = path; - HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #elif defined(_DURANGO) wstring finalPath = StorageManager.GetMountedPath(wPath.c_str()); if(finalPath.size() == 0) finalPath = wPath; - HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #else - HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -347,9 +348,9 @@ bool DLCManager::readDLCDataFile(DWORD &dwFilesProcessed, const string &path, DL return false; } - DWORD bytesRead,dwFileSize = GetFileSize(file,NULL); + DWORD bytesRead,dwFileSize = GetFileSize(file,nullptr); PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { // need to treat the file as corrupt, and flag it, so can't call fatal error @@ -372,7 +373,7 @@ bool DLCManager::readDLCDataFile(DWORD &dwFilesProcessed, const string &path, DL bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD dwLength, DLCPack *pack) { - unordered_map parameterMapping; + unordered_map parameterMapping; unsigned int uiCurrentByte=0; // File format defined in the DLC_Creator @@ -391,7 +392,7 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD if(uiVersion < CURRENT_DLC_VERSION_NUM) { - if(pbData!=NULL) delete [] pbData; + if(pbData!=nullptr) delete [] pbData; app.DebugPrintf("DLC version of %d is too old to be read\n", uiVersion); return false; } @@ -403,9 +404,9 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD for(unsigned int i=0;iwchData); - DLCManager::EDLCParameterType type = DLCManager::getParameterType(parameterName); - if( type != DLCManager::e_DLCParamType_Invalid ) + wstring parameterName(static_cast(pParams->wchData)); + EDLCParameterType type = getParameterType(parameterName); + if( type != e_DLCParamType_Invalid ) { parameterMapping[pParams->dwType] = type; } @@ -429,10 +430,10 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD for(unsigned int i=0;idwType; + EDLCType type = static_cast(pFile->dwType); - DLCFile *dlcFile = NULL; - DLCPack *dlcTexturePack = NULL; + DLCFile *dlcFile = nullptr; + DLCPack *dlcTexturePack = nullptr; if(type == e_DLCType_TexturePack) { @@ -461,8 +462,8 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD } else { - if(dlcFile != NULL) dlcFile->addParameter(it->second,(WCHAR *)pParams->wchData); - else if(dlcTexturePack != NULL) dlcTexturePack->addParameter(it->second, (WCHAR *)pParams->wchData); + if(dlcFile != nullptr) dlcFile->addParameter(it->second,(WCHAR *)pParams->wchData); + else if(dlcTexturePack != nullptr) dlcTexturePack->addParameter(it->second, (WCHAR *)pParams->wchData); } } pbTemp+=sizeof(C4JStorage::DLC_FILE_PARAM)+(sizeof(WCHAR)*pParams->dwWchCount); @@ -470,28 +471,28 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD } //pbTemp+=ulParameterCount * sizeof(C4JStorage::DLC_FILE_PARAM); - if(dlcTexturePack != NULL) + if(dlcTexturePack != nullptr) { DWORD texturePackFilesProcessed = 0; bool validPack = processDLCDataFile(texturePackFilesProcessed,pbTemp,pFile->uiFileSize,dlcTexturePack); - pack->SetDataPointer(NULL); // If it's a child pack, it doesn't own the data + pack->SetDataPointer(nullptr); // If it's a child pack, it doesn't own the data if(!validPack || texturePackFilesProcessed == 0) { delete dlcTexturePack; - dlcTexturePack = NULL; + dlcTexturePack = nullptr; } else { pack->addChildPack(dlcTexturePack); - if(dlcTexturePack->getDLCItemsCount(DLCManager::e_DLCType_Texture) > 0) + if(dlcTexturePack->getDLCItemsCount(e_DLCType_Texture) > 0) { Minecraft::GetInstance()->skins->addTexturePackFromDLC(dlcTexturePack, dlcTexturePack->GetPackId() ); } } ++dwFilesProcessed; } - else if(dlcFile != NULL) + else if(dlcFile != nullptr) { // Data dlcFile->addData(pbTemp,pFile->uiFileSize); @@ -499,7 +500,7 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD // TODO - 4J Stu Remove the need for this vSkinNames vector, or manage it differently switch(pFile->dwType) { - case DLCManager::e_DLCType_Skin: + case e_DLCType_Skin: app.vSkinNames.push_back((WCHAR *)pFile->wchFile); break; } @@ -514,13 +515,13 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD pFile=(C4JStorage::DLC_FILE_DETAILS *)&pbData[uiCurrentByte]; } - if( pack->getDLCItemsCount(DLCManager::e_DLCType_GameRules) > 0 - || pack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader) > 0) + if( pack->getDLCItemsCount(e_DLCType_GameRules) > 0 + || pack->getDLCItemsCount(e_DLCType_GameRulesHeader) > 0) { app.m_gameRules.loadGameRules(pack); } - if(pack->getDLCItemsCount(DLCManager::e_DLCType_Audio) > 0) + if(pack->getDLCItemsCount(e_DLCType_Audio) > 0) { //app.m_Audio.loadAudioDetails(pack); } @@ -537,22 +538,22 @@ DWORD DLCManager::retrievePackIDFromDLCDataFile(const string &path, DLCPack *pac #ifdef _WINDOWS64 string finalPath = StorageManager.GetMountedPath(path.c_str()); if(finalPath.size() == 0) finalPath = path; - HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #elif defined(_DURANGO) wstring finalPath = StorageManager.GetMountedPath(wPath.c_str()); if(finalPath.size() == 0) finalPath = wPath; - HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(finalPath.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #else - HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { return 0; } - DWORD bytesRead,dwFileSize = GetFileSize(file,NULL); + DWORD bytesRead,dwFileSize = GetFileSize(file,nullptr); PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { // need to treat the file as corrupt, and flag it, so can't call fatal error @@ -579,7 +580,7 @@ DWORD DLCManager::retrievePackID(PBYTE pbData, DWORD dwLength, DLCPack *pack) { DWORD packId=0; bool bPackIDSet=false; - unordered_map parameterMapping; + unordered_map parameterMapping; unsigned int uiCurrentByte=0; // File format defined in the DLC_Creator @@ -608,9 +609,9 @@ DWORD DLCManager::retrievePackID(PBYTE pbData, DWORD dwLength, DLCPack *pack) for(unsigned int i=0;iwchData); - DLCManager::EDLCParameterType type = DLCManager::getParameterType(parameterName); - if( type != DLCManager::e_DLCParamType_Invalid ) + wstring parameterName(static_cast(pParams->wchData)); + EDLCParameterType type = getParameterType(parameterName); + if( type != e_DLCParamType_Invalid ) { parameterMapping[pParams->dwType] = type; } @@ -633,7 +634,7 @@ DWORD DLCManager::retrievePackID(PBYTE pbData, DWORD dwLength, DLCPack *pack) for(unsigned int i=0;idwType; + EDLCType type = static_cast(pFile->dwType); // Params uiParameterCount=*(unsigned int *)pbTemp; @@ -649,7 +650,7 @@ DWORD DLCManager::retrievePackID(PBYTE pbData, DWORD dwLength, DLCPack *pack) { if(it->second==e_DLCParamType_PackId) { - wstring wsTemp=(WCHAR *)pParams->wchData; + wstring wsTemp=static_cast(pParams->wchData); std::wstringstream ss; // 4J Stu - numbered using decimal to make it easier for artists/people to number manually ss << std::dec << wsTemp.c_str(); diff --git a/Minecraft.Client/Common/DLC/DLCPack.cpp b/Minecraft.Client/Common/DLC/DLCPack.cpp index ea8a270fd..110008c61 100644 --- a/Minecraft.Client/Common/DLC/DLCPack.cpp +++ b/Minecraft.Client/Common/DLC/DLCPack.cpp @@ -24,14 +24,14 @@ DLCPack::DLCPack(const wstring &name,DWORD dwLicenseMask) m_isCorrupt = false; m_packId = 0; m_packVersion = 0; - m_parentPack = NULL; + m_parentPack = nullptr; m_dlcMountIndex = -1; #ifdef _XBOX m_dlcDeviceID = XCONTENTDEVICE_ANY; #endif // This pointer is for all the data used for this pack, so deleting it invalidates ALL of it's children. - m_data = NULL; + m_data = nullptr; } #ifdef _XBOX_ONE @@ -44,11 +44,11 @@ DLCPack::DLCPack(const wstring &name,const wstring &productID,DWORD dwLicenseMas m_isCorrupt = false; m_packId = 0; m_packVersion = 0; - m_parentPack = NULL; + m_parentPack = nullptr; m_dlcMountIndex = -1; // This pointer is for all the data used for this pack, so deleting it invalidates ALL of it's children. - m_data = NULL; + m_data = nullptr; } #endif @@ -76,7 +76,7 @@ DLCPack::~DLCPack() wprintf(L"Deleting data for DLC pack %ls\n", m_packName.c_str()); #endif // For the same reason, don't delete data pointer for any child pack as it just points to a region within the parent pack that has already been freed - if( m_parentPack == NULL ) + if( m_parentPack == nullptr ) { delete [] m_data; } @@ -85,7 +85,7 @@ DLCPack::~DLCPack() DWORD DLCPack::GetDLCMountIndex() { - if(m_parentPack != NULL) + if(m_parentPack != nullptr) { return m_parentPack->GetDLCMountIndex(); } @@ -94,7 +94,7 @@ DWORD DLCPack::GetDLCMountIndex() XCONTENTDEVICEID DLCPack::GetDLCDeviceID() { - if(m_parentPack != NULL ) + if(m_parentPack != nullptr ) { return m_parentPack->GetDLCDeviceID(); } @@ -156,7 +156,7 @@ void DLCPack::addParameter(DLCManager::EDLCParameterType type, const wstring &va m_dataPath = value; break; default: - m_parameters[(int)type] = value; + m_parameters[static_cast(type)] = value; break; } } @@ -187,7 +187,7 @@ bool DLCPack::getParameterAsUInt(DLCManager::EDLCParameterType type, unsigned in DLCFile *DLCPack::addFile(DLCManager::EDLCType type, const wstring &path) { - DLCFile *newFile = NULL; + DLCFile *newFile = nullptr; switch(type) { @@ -243,7 +243,7 @@ DLCFile *DLCPack::addFile(DLCManager::EDLCType type, const wstring &path) break; }; - if( newFile != NULL ) + if( newFile != nullptr ) { m_files[newFile->getType()].push_back(newFile); } @@ -252,7 +252,7 @@ DLCFile *DLCPack::addFile(DLCManager::EDLCType type, const wstring &path) } // MGH - added this comp func, as the embedded func in find_if was confusing the PS3 compiler -static const wstring *g_pathCmpString = NULL; +static const wstring *g_pathCmpString = nullptr; static bool pathCmp(DLCFile *val) { return (g_pathCmpString->compare(val->getPath()) == 0); @@ -263,7 +263,7 @@ bool DLCPack::doesPackContainFile(DLCManager::EDLCType type, const wstring &path bool hasFile = false; if(type == DLCManager::e_DLCType_All) { - for(DLCManager::EDLCType currentType = (DLCManager::EDLCType)0; currentType < DLCManager::e_DLCType_Max; currentType = (DLCManager::EDLCType)(currentType + 1)) + for(DLCManager::EDLCType currentType = static_cast(0); currentType < DLCManager::e_DLCType_Max; currentType = static_cast(currentType + 1)) { hasFile = doesPackContainFile(currentType,path); if(hasFile) break; @@ -284,13 +284,13 @@ bool DLCPack::doesPackContainFile(DLCManager::EDLCType type, const wstring &path DLCFile *DLCPack::getFile(DLCManager::EDLCType type, DWORD index) { - DLCFile *file = NULL; + DLCFile *file = nullptr; if(type == DLCManager::e_DLCType_All) { - for(DLCManager::EDLCType currentType = (DLCManager::EDLCType)0; currentType < DLCManager::e_DLCType_Max; currentType = (DLCManager::EDLCType)(currentType + 1)) + for(DLCManager::EDLCType currentType = static_cast(0); currentType < DLCManager::e_DLCType_Max; currentType = static_cast(currentType + 1)) { file = getFile(currentType,index); - if(file != NULL) break; + if(file != nullptr) break; } } else @@ -306,13 +306,13 @@ DLCFile *DLCPack::getFile(DLCManager::EDLCType type, DWORD index) DLCFile *DLCPack::getFile(DLCManager::EDLCType type, const wstring &path) { - DLCFile *file = NULL; + DLCFile *file = nullptr; if(type == DLCManager::e_DLCType_All) { - for(DLCManager::EDLCType currentType = (DLCManager::EDLCType)0; currentType < DLCManager::e_DLCType_Max; currentType = (DLCManager::EDLCType)(currentType + 1)) + for(DLCManager::EDLCType currentType = static_cast(0); currentType < DLCManager::e_DLCType_Max; currentType = static_cast(currentType + 1)) { file = getFile(currentType,path); - if(file != NULL) break; + if(file != nullptr) break; } } else @@ -323,7 +323,7 @@ DLCFile *DLCPack::getFile(DLCManager::EDLCType type, const wstring &path) if(it == m_files[type].end()) { // Not found - file = NULL; + file = nullptr; } else { @@ -346,11 +346,11 @@ DWORD DLCPack::getDLCItemsCount(DLCManager::EDLCType type /*= DLCManager::e_DLCT case DLCManager::e_DLCType_All: for(int i = 0; i < DLCManager::e_DLCType_Max; ++i) { - count += getDLCItemsCount((DLCManager::EDLCType)i); + count += getDLCItemsCount(static_cast(i)); } break; default: - count = (DWORD)m_files[(int)type].size(); + count = static_cast(m_files[(int)type].size()); break; }; return count; @@ -420,12 +420,12 @@ void DLCPack::UpdateLanguage() { // find the language file DLCManager::e_DLCType_LocalisationData; - DLCFile *file = NULL; + DLCFile *file = nullptr; if(m_files[DLCManager::e_DLCType_LocalisationData].size() > 0) { file = m_files[DLCManager::e_DLCType_LocalisationData][0]; - DLCLocalisationFile *localisationFile = (DLCLocalisationFile *)getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc"); + DLCLocalisationFile *localisationFile = static_cast(getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")); StringTable *strTable = localisationFile->getStringTable(); strTable->ReloadStringTable(); } diff --git a/Minecraft.Client/Common/DLC/DLCPack.h b/Minecraft.Client/Common/DLC/DLCPack.h index df1f65f04..14129cbed 100644 --- a/Minecraft.Client/Common/DLC/DLCPack.h +++ b/Minecraft.Client/Common/DLC/DLCPack.h @@ -87,8 +87,8 @@ public: DWORD getSkinCount() { return getDLCItemsCount(DLCManager::e_DLCType_Skin); } DWORD getSkinIndexAt(const wstring &path, bool &found) { return getFileIndexAt(DLCManager::e_DLCType_Skin, path, found); } - DLCSkinFile *getSkinFile(const wstring &path) { return (DLCSkinFile *)getFile(DLCManager::e_DLCType_Skin, path); } - DLCSkinFile *getSkinFile(DWORD index) { return (DLCSkinFile *)getFile(DLCManager::e_DLCType_Skin, index); } + DLCSkinFile *getSkinFile(const wstring &path) { return static_cast(getFile(DLCManager::e_DLCType_Skin, path)); } + DLCSkinFile *getSkinFile(DWORD index) { return static_cast(getFile(DLCManager::e_DLCType_Skin, index)); } bool doesPackContainSkin(const wstring &path) { return doesPackContainFile(DLCManager::e_DLCType_Skin, path); } bool hasPurchasedFile(DLCManager::EDLCType type, const wstring &path); diff --git a/Minecraft.Client/Common/DLC/DLCSkinFile.cpp b/Minecraft.Client/Common/DLC/DLCSkinFile.cpp index c845acd9b..f7ef2ad00 100644 --- a/Minecraft.Client/Common/DLC/DLCSkinFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCSkinFile.cpp @@ -79,7 +79,7 @@ void DLCSkinFile::addParameter(DLCManager::EDLCParameterType type, const wstring { i++; } - int iLast=(int)creditValue.find_last_of(L" ",i); + size_t iLast=creditValue.find_last_of(L" ", i); switch(XGetLanguage()) { case XC_LANGUAGE_JAPANESE: @@ -88,7 +88,7 @@ void DLCSkinFile::addParameter(DLCManager::EDLCParameterType type, const wstring iLast = maximumChars; break; default: - iLast=(int)creditValue.find_last_of(L" ",i); + iLast=creditValue.find_last_of(L" ", i); break; } @@ -178,7 +178,7 @@ void DLCSkinFile::addParameter(DLCManager::EDLCParameterType type, const wstring int DLCSkinFile::getAdditionalBoxesCount() { - return (int)m_AdditionalBoxes.size(); + return static_cast(m_AdditionalBoxes.size()); } vector *DLCSkinFile::getAdditionalBoxes() { diff --git a/Minecraft.Client/Common/DLC/DLCSkinFile.h b/Minecraft.Client/Common/DLC/DLCSkinFile.h index c8dcf0e9c..15a50e717 100644 --- a/Minecraft.Client/Common/DLC/DLCSkinFile.h +++ b/Minecraft.Client/Common/DLC/DLCSkinFile.h @@ -17,11 +17,11 @@ public: DLCSkinFile(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); - virtual void addParameter(DLCManager::EDLCParameterType type, const wstring &value); + void addData(PBYTE pbData, DWORD dwBytes) override; + void addParameter(DLCManager::EDLCParameterType type, const wstring &value) override; - virtual wstring getParameterAsString(DLCManager::EDLCParameterType type); - virtual bool getParameterAsBool(DLCManager::EDLCParameterType type); + wstring getParameterAsString(DLCManager::EDLCParameterType type) override; + bool getParameterAsBool(DLCManager::EDLCParameterType type) override; vector *getAdditionalBoxes(); int getAdditionalBoxesCount(); unsigned int getAnimOverrideBitmask() { return m_uiAnimOverrideBitmask;} diff --git a/Minecraft.Client/Common/DLC/DLCTextureFile.cpp b/Minecraft.Client/Common/DLC/DLCTextureFile.cpp index edf071c63..fb9c5b036 100644 --- a/Minecraft.Client/Common/DLC/DLCTextureFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCTextureFile.cpp @@ -7,7 +7,7 @@ DLCTextureFile::DLCTextureFile(const wstring &path) : DLCFile(DLCManager::e_DLCT m_bIsAnim = false; m_animString = L""; - m_pbData = NULL; + m_pbData = nullptr; m_dwBytes = 0; } diff --git a/Minecraft.Client/Common/DLC/DLCTextureFile.h b/Minecraft.Client/Common/DLC/DLCTextureFile.h index bc7916867..2b397e8e3 100644 --- a/Minecraft.Client/Common/DLC/DLCTextureFile.h +++ b/Minecraft.Client/Common/DLC/DLCTextureFile.h @@ -14,11 +14,11 @@ private: public: DLCTextureFile(const wstring &path); - virtual void addData(PBYTE pbData, DWORD dwBytes); - virtual PBYTE getData(DWORD &dwBytes); + void addData(PBYTE pbData, DWORD dwBytes) override; + PBYTE getData(DWORD &dwBytes) override; - virtual void addParameter(DLCManager::EDLCParameterType type, const wstring &value); + void addParameter(DLCManager::EDLCParameterType type, const wstring &value) override; - virtual wstring getParameterAsString(DLCManager::EDLCParameterType type); - virtual bool getParameterAsBool(DLCManager::EDLCParameterType type); + wstring getParameterAsString(DLCManager::EDLCParameterType type) override; + bool getParameterAsBool(DLCManager::EDLCParameterType type) override; }; \ No newline at end of file diff --git a/Minecraft.Client/Common/DLC/DLCUIDataFile.cpp b/Minecraft.Client/Common/DLC/DLCUIDataFile.cpp index a2a56bca5..597c4b7bc 100644 --- a/Minecraft.Client/Common/DLC/DLCUIDataFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCUIDataFile.cpp @@ -4,14 +4,14 @@ DLCUIDataFile::DLCUIDataFile(const wstring &path) : DLCFile(DLCManager::e_DLCType_UIData,path) { - m_pbData = NULL; + m_pbData = nullptr; m_dwBytes = 0; m_canDeleteData = false; } DLCUIDataFile::~DLCUIDataFile() { - if(m_canDeleteData && m_pbData != NULL) + if(m_canDeleteData && m_pbData != nullptr) { app.DebugPrintf("Deleting DLCUIDataFile data\n"); delete [] m_pbData; diff --git a/Minecraft.Client/Common/DLC/DLCUIDataFile.h b/Minecraft.Client/Common/DLC/DLCUIDataFile.h index 105ad0dfd..c858933cc 100644 --- a/Minecraft.Client/Common/DLC/DLCUIDataFile.h +++ b/Minecraft.Client/Common/DLC/DLCUIDataFile.h @@ -10,11 +10,11 @@ private: public: DLCUIDataFile(const wstring &path); - ~DLCUIDataFile(); + ~DLCUIDataFile() override; using DLCFile::addData; using DLCFile::addParameter; virtual void addData(PBYTE pbData, DWORD dwBytes,bool canDeleteData = false); - virtual PBYTE getData(DWORD &dwBytes); + PBYTE getData(DWORD &dwBytes) override; }; diff --git a/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp index 555ed8b47..f97bfdd1f 100644 --- a/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp @@ -46,7 +46,7 @@ void AddEnchantmentRuleDefinition::addAttribute(const wstring &attributeName, co bool AddEnchantmentRuleDefinition::enchantItem(shared_ptr item) { bool enchanted = false; - if (item != NULL) + if (item != nullptr) { // 4J-JEV: Ripped code from enchantmenthelpers // Maybe we want to add an addEnchantment method to EnchantmentHelpers @@ -58,7 +58,7 @@ bool AddEnchantmentRuleDefinition::enchantItem(shared_ptr item) { Enchantment *e = Enchantment::enchantments[m_enchantmentId]; - if(e != NULL && e->category->canEnchant(item->getItem())) + if(e != nullptr && e->category->canEnchant(item->getItem())) { int level = min(e->getMaxLevel(), m_enchantmentLevel); item->enchant(e, m_enchantmentLevel); diff --git a/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp index 801a29373..49809d0c5 100644 --- a/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp @@ -41,11 +41,11 @@ void AddItemRuleDefinition::getChildren(vector *children) GameRuleDefinition *AddItemRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_AddEnchantment) { rule = new AddEnchantmentRuleDefinition(); - m_enchantments.push_back((AddEnchantmentRuleDefinition *)rule); + m_enchantments.push_back(static_cast(rule)); } else { @@ -97,10 +97,10 @@ void AddItemRuleDefinition::addAttribute(const wstring &attributeName, const wst bool AddItemRuleDefinition::addItemToContainer(shared_ptr container, int slotId) { bool added = false; - if(Item::items[m_itemId] != NULL) + if(Item::items[m_itemId] != nullptr) { int quantity = std::min(m_quantity, Item::items[m_itemId]->getMaxStackSize()); - shared_ptr newItem = shared_ptr(new ItemInstance(m_itemId,quantity,m_auxValue) ); + shared_ptr newItem = std::make_shared(m_itemId, quantity, m_auxValue); newItem->set4JData(m_dataTag); for( auto& it : m_enchantments ) @@ -118,7 +118,7 @@ bool AddItemRuleDefinition::addItemToContainer(shared_ptr container, container->setItem( slotId, newItem ); added = true; } - else if(dynamic_pointer_cast(container) != NULL) + else if(dynamic_pointer_cast(container) != nullptr) { added = dynamic_pointer_cast(container)->add(newItem); } diff --git a/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp index a740a2beb..3c7e02a39 100644 --- a/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp @@ -13,20 +13,20 @@ ApplySchematicRuleDefinition::ApplySchematicRuleDefinition(LevelGenerationOption { m_levelGenOptions = levelGenOptions; m_location = Vec3::newPermanent(0,0,0); - m_locationBox = NULL; + m_locationBox = nullptr; m_totalBlocksChanged = 0; m_totalBlocksChangedLighting = 0; m_rotation = ConsoleSchematicFile::eSchematicRot_0; m_completed = false; m_dimension = 0; - m_schematic = NULL; + m_schematic = nullptr; } ApplySchematicRuleDefinition::~ApplySchematicRuleDefinition() { app.DebugPrintf("Deleting ApplySchematicRuleDefinition.\n"); if(!m_completed) m_levelGenOptions->releaseSchematicFile(m_schematicName); - m_schematic = NULL; + m_schematic = nullptr; delete m_location; } @@ -72,20 +72,20 @@ void ApplySchematicRuleDefinition::addAttribute(const wstring &attributeName, co else if(attributeName.compare(L"x") == 0) { m_location->x = _fromString(attributeValue); - if( ((int)abs(m_location->x))%2 != 0) m_location->x -=1; + if( static_cast(abs(m_location->x))%2 != 0) m_location->x -=1; //app.DebugPrintf("ApplySchematicRuleDefinition: Adding parameter x=%f\n",m_location->x); } else if(attributeName.compare(L"y") == 0) { m_location->y = _fromString(attributeValue); - if( ((int)abs(m_location->y))%2 != 0) m_location->y -= 1; + if( static_cast(abs(m_location->y))%2 != 0) m_location->y -= 1; if(m_location->y < 0) m_location->y = 0; //app.DebugPrintf("ApplySchematicRuleDefinition: Adding parameter y=%f\n",m_location->y); } else if(attributeName.compare(L"z") == 0) { m_location->z = _fromString(attributeValue); - if(((int)abs(m_location->z))%2 != 0) m_location->z -= 1; + if(static_cast(abs(m_location->z))%2 != 0) m_location->z -= 1; //app.DebugPrintf("ApplySchematicRuleDefinition: Adding parameter z=%f\n",m_location->z); } else if(attributeName.compare(L"rot") == 0) @@ -95,7 +95,7 @@ void ApplySchematicRuleDefinition::addAttribute(const wstring &attributeName, co while(degrees < 0) degrees += 360; while(degrees >= 360) degrees -= 360; float quad = degrees/90; - degrees = (int)(quad + 0.5f); + degrees = static_cast(quad + 0.5f); switch(degrees) { case 1: @@ -130,7 +130,7 @@ void ApplySchematicRuleDefinition::addAttribute(const wstring &attributeName, co void ApplySchematicRuleDefinition::updateLocationBox() { - if(m_schematic == NULL) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); + if(m_schematic == nullptr) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); m_locationBox = AABB::newPermanent(0,0,0,0,0,0); @@ -162,9 +162,9 @@ void ApplySchematicRuleDefinition::processSchematic(AABB *chunkBox, LevelChunk * if(chunk->level->dimension->id != m_dimension) return; PIXBeginNamedEvent(0, "Processing ApplySchematicRuleDefinition"); - if(m_schematic == NULL) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); + if(m_schematic == nullptr) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); - if(m_locationBox == NULL) updateLocationBox(); + if(m_locationBox == nullptr) updateLocationBox(); if(chunkBox->intersects( m_locationBox )) { m_locationBox->y1 = min((double)Level::maxBuildHeight, m_locationBox->y1 ); @@ -189,7 +189,7 @@ void ApplySchematicRuleDefinition::processSchematic(AABB *chunkBox, LevelChunk * { m_completed = true; //m_levelGenOptions->releaseSchematicFile(m_schematicName); - //m_schematic = NULL; + //m_schematic = nullptr; } } PIXEndNamedEvent(); @@ -201,9 +201,9 @@ void ApplySchematicRuleDefinition::processSchematicLighting(AABB *chunkBox, Leve if(chunk->level->dimension->id != m_dimension) return; PIXBeginNamedEvent(0, "Processing ApplySchematicRuleDefinition (lighting)"); - if(m_schematic == NULL) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); + if(m_schematic == nullptr) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); - if(m_locationBox == NULL) updateLocationBox(); + if(m_locationBox == nullptr) updateLocationBox(); if(chunkBox->intersects( m_locationBox )) { m_locationBox->y1 = min((double)Level::maxBuildHeight, m_locationBox->y1 ); @@ -223,7 +223,7 @@ void ApplySchematicRuleDefinition::processSchematicLighting(AABB *chunkBox, Leve { m_completed = true; //m_levelGenOptions->releaseSchematicFile(m_schematicName); - //m_schematic = NULL; + //m_schematic = nullptr; } } PIXEndNamedEvent(); @@ -231,13 +231,13 @@ void ApplySchematicRuleDefinition::processSchematicLighting(AABB *chunkBox, Leve bool ApplySchematicRuleDefinition::checkIntersects(int x0, int y0, int z0, int x1, int y1, int z1) { - if( m_locationBox == NULL ) updateLocationBox(); + if( m_locationBox == nullptr ) updateLocationBox(); return m_locationBox->intersects(x0,y0,z0,x1,y1,z1); } int ApplySchematicRuleDefinition::getMinY() { - if( m_locationBox == NULL ) updateLocationBox(); + if( m_locationBox == nullptr ) updateLocationBox(); return m_locationBox->y0; } diff --git a/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp index f3b484459..7f03a0fef 100644 --- a/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp @@ -77,7 +77,7 @@ void CollectItemRuleDefinition::populateGameRule(GameRulesInstance::EGameRulesIn bool CollectItemRuleDefinition::onCollectItem(GameRule *rule, shared_ptr item) { bool statusChanged = false; - if(item != NULL && item->id == m_itemId && item->getAuxValue() == m_auxValue && item->get4JData() == m_4JDataValue) + if(item != nullptr && item->id == m_itemId && item->getAuxValue() == m_auxValue && item->get4JData() == m_4JDataValue) { if(!getComplete(rule)) { @@ -90,13 +90,21 @@ bool CollectItemRuleDefinition::onCollectItem(GameRule *rule, shared_ptr= m_quantity) { setComplete(rule, true); - app.DebugPrintf("Completed CollectItemRule with info - itemId:%d, auxValue:%d, quantity:%d, dataTag:%d\n", m_itemId,m_auxValue,m_quantity,m_4JDataValue); + app.DebugPrintf("Completed CollectItemRule with info - itemId:%d, auxValue:%d, quantity:%d, dataTag:%d\n", m_itemId, m_auxValue, m_quantity, m_4JDataValue); - if(rule->getConnection() != NULL) - { - rule->getConnection()->send( shared_ptr( new UpdateGameRuleProgressPacket(getActionType(), this->m_descriptionId, m_itemId, m_auxValue, this->m_4JDataValue,NULL,0))); - } - } + if (rule->getConnection() != nullptr) + { + rule->getConnection()->send(std::make_shared( + getActionType(), + this->m_descriptionId, + m_itemId, + m_auxValue, + this->m_4JDataValue, + nullptr, + static_cast(0) + )); + } + } } } return statusChanged; @@ -106,7 +114,7 @@ wstring CollectItemRuleDefinition::generateXml(shared_ptr item) { // 4J Stu - This should be kept in sync with the GameRulesDefinition.xsd wstring xml = L""; - if(item != NULL) + if(item != nullptr) { xml = L"id) + L"\" quantity=\"SET\" descriptionName=\"OPTIONAL\" promptName=\"OPTIONAL\""; if(item->getAuxValue() != 0) xml += L" auxValue=\"" + std::to_wstring(item->getAuxValue()) + L"\""; diff --git a/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp index b928b26cc..cd23cd504 100644 --- a/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp @@ -36,7 +36,7 @@ void CompleteAllRuleDefinition::updateStatus(GameRule *rule) progress += it.second.gr->getGameRuleDefinition()->getProgress(it.second.gr); } } - if(rule->getConnection() != NULL) + if(rule->getConnection() != nullptr) { PacketData data; data.goal = goal; @@ -45,20 +45,20 @@ void CompleteAllRuleDefinition::updateStatus(GameRule *rule) int icon = -1; int auxValue = 0; - if(m_lastRuleStatusChanged != NULL) + if(m_lastRuleStatusChanged != nullptr) { icon = m_lastRuleStatusChanged->getIcon(); auxValue = m_lastRuleStatusChanged->getAuxValue(); - m_lastRuleStatusChanged = NULL; + m_lastRuleStatusChanged = nullptr; } - rule->getConnection()->send( shared_ptr( new UpdateGameRuleProgressPacket(getActionType(), this->m_descriptionId,icon, auxValue, 0,&data,sizeof(PacketData)))); + rule->getConnection()->send(std::make_shared(getActionType(), this->m_descriptionId, icon, auxValue, 0, &data, sizeof(PacketData))); } app.DebugPrintf("Updated CompleteAllRule - Completed %d of %d\n", progress, goal); } wstring CompleteAllRuleDefinition::generateDescriptionString(const wstring &description, void *data, int dataLength) { - PacketData *values = (PacketData *)data; + PacketData *values = static_cast(data); wstring newDesc = description; newDesc = replaceAll(newDesc,L"{*progress*}",std::to_wstring(values->progress)); newDesc = replaceAll(newDesc,L"{*goal*}",std::to_wstring(values->goal)); diff --git a/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp index 395b4eebd..f75eddd40 100644 --- a/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp @@ -6,7 +6,7 @@ CompoundGameRuleDefinition::CompoundGameRuleDefinition() { - m_lastRuleStatusChanged = NULL; + m_lastRuleStatusChanged = nullptr; } CompoundGameRuleDefinition::~CompoundGameRuleDefinition() @@ -26,7 +26,7 @@ void CompoundGameRuleDefinition::getChildren(vector *child GameRuleDefinition *CompoundGameRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_CompleteAllRule) { rule = new CompleteAllRuleDefinition(); @@ -49,13 +49,13 @@ GameRuleDefinition *CompoundGameRuleDefinition::addChild(ConsoleGameRules::EGame wprintf(L"CompoundGameRuleDefinition: Attempted to add invalid child rule - %d\n", ruleType ); #endif } - if(rule != NULL) m_children.push_back(rule); + if(rule != nullptr) m_children.push_back(rule); return rule; } void CompoundGameRuleDefinition::populateGameRule(GameRulesInstance::EGameRulesInstanceType type, GameRule *rule) { - GameRule *newRule = NULL; + GameRule *newRule = nullptr; int i = 0; for (auto& it : m_children ) { diff --git a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp index f505ce7a3..dd7776824 100644 --- a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp +++ b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp @@ -10,7 +10,7 @@ ConsoleGenerateStructure::ConsoleGenerateStructure() : StructurePiece(0) { m_x = m_y = m_z = 0; - boundingBox = NULL; + boundingBox = nullptr; orientation = Direction::NORTH; m_dimension = 0; } @@ -25,26 +25,26 @@ void ConsoleGenerateStructure::getChildren(vector *childre GameRuleDefinition *ConsoleGenerateStructure::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_GenerateBox) { rule = new XboxStructureActionGenerateBox(); - m_actions.push_back((XboxStructureActionGenerateBox *)rule); + m_actions.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_PlaceBlock) { rule = new XboxStructureActionPlaceBlock(); - m_actions.push_back((XboxStructureActionPlaceBlock *)rule); + m_actions.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_PlaceContainer) { rule = new XboxStructureActionPlaceContainer(); - m_actions.push_back((XboxStructureActionPlaceContainer *)rule); + m_actions.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_PlaceSpawner) { rule = new XboxStructureActionPlaceSpawner(); - m_actions.push_back((XboxStructureActionPlaceSpawner *)rule); + m_actions.push_back(static_cast(rule)); } else { @@ -112,7 +112,7 @@ void ConsoleGenerateStructure::addAttribute(const wstring &attributeName, const BoundingBox* ConsoleGenerateStructure::getBoundingBox() { - if(boundingBox == NULL) + if(boundingBox == nullptr) { // Find the max bounds int maxX, maxY, maxZ; @@ -139,25 +139,25 @@ bool ConsoleGenerateStructure::postProcess(Level *level, Random *random, Boundin { case ConsoleGameRules::eGameRuleType_GenerateBox: { - XboxStructureActionGenerateBox *genBox = (XboxStructureActionGenerateBox *)action; + XboxStructureActionGenerateBox *genBox = static_cast(action); genBox->generateBoxInLevel(this,level,chunkBB); } break; case ConsoleGameRules::eGameRuleType_PlaceBlock: { - XboxStructureActionPlaceBlock *pPlaceBlock = (XboxStructureActionPlaceBlock *)action; + XboxStructureActionPlaceBlock *pPlaceBlock = static_cast(action); pPlaceBlock->placeBlockInLevel(this,level,chunkBB); } break; case ConsoleGameRules::eGameRuleType_PlaceContainer: { - XboxStructureActionPlaceContainer *pPlaceContainer = (XboxStructureActionPlaceContainer *)action; + XboxStructureActionPlaceContainer *pPlaceContainer = static_cast(action); pPlaceContainer->placeContainerInLevel(this,level,chunkBB); } break; case ConsoleGameRules::eGameRuleType_PlaceSpawner: { - XboxStructureActionPlaceSpawner *pPlaceSpawner = (XboxStructureActionPlaceSpawner *)action; + XboxStructureActionPlaceSpawner *pPlaceSpawner = static_cast(action); pPlaceSpawner->placeSpawnerInLevel(this,level,chunkBB); } break; diff --git a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.h b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.h index 91c4ef357..712a29ab1 100644 --- a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.h +++ b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.h @@ -36,7 +36,7 @@ public: virtual int getMinY(); - EStructurePiece GetType() { return (EStructurePiece)0; } + EStructurePiece GetType() { return static_cast(0); } void addAdditonalSaveData(CompoundTag *tag) {} void readAdditonalSaveData(CompoundTag *tag) {} }; \ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp b/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp index 7b69c4b4e..c261e0cd6 100644 --- a/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp +++ b/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp @@ -16,18 +16,18 @@ ConsoleSchematicFile::ConsoleSchematicFile() { m_xSize = m_ySize = m_zSize = 0; m_refCount = 1; - m_data.data = NULL; + m_data.data = nullptr; } ConsoleSchematicFile::~ConsoleSchematicFile() { app.DebugPrintf("Deleting schematic file\n"); - if(m_data.data != NULL) delete [] m_data.data; + if(m_data.data != nullptr) delete [] m_data.data; } void ConsoleSchematicFile::save(DataOutputStream *dos) { - if(dos != NULL) + if(dos != nullptr) { dos->writeInt(XBOX_SCHEMATIC_CURRENT_VERSION); @@ -52,7 +52,7 @@ void ConsoleSchematicFile::save(DataOutputStream *dos) void ConsoleSchematicFile::load(DataInputStream *dis) { - if(dis != NULL) + if(dis != nullptr) { // VERSION CHECK // int version = dis->readInt(); @@ -61,7 +61,7 @@ void ConsoleSchematicFile::load(DataInputStream *dis) if (version > XBOX_SCHEMATIC_ORIGINAL_VERSION) // Or later versions { - compressionType = (Compression::ECompressionTypes)dis->readByte(); + compressionType = static_cast(dis->readByte()); } if (version > XBOX_SCHEMATIC_CURRENT_VERSION) @@ -75,10 +75,10 @@ void ConsoleSchematicFile::load(DataInputStream *dis) byteArray compressedBuffer(compressedSize); dis->readFully(compressedBuffer); - if(m_data.data != NULL) + if(m_data.data != nullptr) { - delete [] m_data.data; - m_data.data = NULL; + delete [] m_data.data; + m_data.data = nullptr; } if(compressionType == Compression::eCompressionType_None) @@ -111,17 +111,17 @@ void ConsoleSchematicFile::load(DataInputStream *dis) // READ TAGS // CompoundTag *tag = NbtIo::read(dis); ListTag *tileEntityTags = (ListTag *) tag->getList(L"TileEntities"); - if (tileEntityTags != NULL) + if (tileEntityTags != nullptr) { for (int i = 0; i < tileEntityTags->size(); i++) { CompoundTag *teTag = tileEntityTags->get(i); shared_ptr te = TileEntity::loadStatic(teTag); - if(te == NULL) + if(te == nullptr) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("ConsoleSchematicFile has read a NULL tile entity\n"); + app.DebugPrintf("ConsoleSchematicFile has read a nullptr tile entity\n"); __debugbreak(); #endif } @@ -132,7 +132,7 @@ void ConsoleSchematicFile::load(DataInputStream *dis) } } ListTag *entityTags = (ListTag *) tag->getList(L"Entities"); - if (entityTags != NULL) + if (entityTags != nullptr) { for (int i = 0; i < entityTags->size(); i++) { @@ -145,15 +145,15 @@ void ConsoleSchematicFile::load(DataInputStream *dis) double z = pos->get(2)->data; if( type == eTYPE_PAINTING || type == eTYPE_ITEM_FRAME ) - { - x = ((IntTag *) eTag->get(L"TileX") )->data; - y = ((IntTag *) eTag->get(L"TileY") )->data; - z = ((IntTag *) eTag->get(L"TileZ") )->data; - } + { + x = static_cast(eTag->get(L"TileX"))->data; + y = static_cast(eTag->get(L"TileY"))->data; + z = static_cast(eTag->get(L"TileZ"))->data; + } #ifdef _DEBUG //app.DebugPrintf(1,"Loaded entity type %d at (%f,%f,%f)\n",(int)type,x,y,z); #endif - m_entities.push_back( pair(Vec3::newPermanent(x,y,z),(CompoundTag *)eTag->copy())); + m_entities.push_back( pair(Vec3::newPermanent(x,y,z),static_cast(eTag->copy()))); } } delete tag; @@ -178,7 +178,7 @@ void ConsoleSchematicFile::save_tags(DataOutputStream *dos) tag->put(L"Entities", entityTags); for (auto& it : m_entities ) - entityTags->add( (CompoundTag *)(it).second->copy() ); + entityTags->add( static_cast((it).second->copy()) ); NbtIo::write(tag,dos); delete tag; @@ -186,15 +186,15 @@ void ConsoleSchematicFile::save_tags(DataOutputStream *dos) int64_t ConsoleSchematicFile::applyBlocksAndData(LevelChunk *chunk, AABB *chunkBox, AABB *destinationBox, ESchematicRotation rot) { - int xStart = static_cast(std::fmax(destinationBox->x0, (double)chunk->x*16)); - int xEnd = static_cast(std::fmin(destinationBox->x1, (double)((xStart >> 4) << 4) + 16)); + int xStart = static_cast(std::fmax(destinationBox->x0, static_cast(chunk->x)*16)); + int xEnd = static_cast(std::fmin(destinationBox->x1, static_cast((xStart >> 4) << 4) + 16)); int yStart = destinationBox->y0; int yEnd = destinationBox->y1; if(yEnd > Level::maxBuildHeight) yEnd = Level::maxBuildHeight; - int zStart = static_cast(std::fmax(destinationBox->z0, (double)chunk->z * 16)); - int zEnd = static_cast(std::fmin(destinationBox->z1, (double)((zStart >> 4) << 4) + 16)); + int zStart = static_cast(std::fmax(destinationBox->z0, static_cast(chunk->z) * 16)); + int zEnd = static_cast(std::fmin(destinationBox->z1, static_cast((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); @@ -442,10 +442,10 @@ void ConsoleSchematicFile::applyTileEntities(LevelChunk *chunk, AABB *chunkBox, Vec3 *pos = Vec3::newTemp(targetX,targetY,targetZ); if( chunkBox->containsIncludingLowerBound(pos) ) { - shared_ptr teCopy = chunk->getTileEntity( (int)targetX & 15, (int)targetY & 15, (int)targetZ & 15 ); + shared_ptr teCopy = chunk->getTileEntity( static_cast(targetX) & 15, static_cast(targetY) & 15, static_cast(targetZ) & 15 ); - if ( teCopy != NULL ) - { + if ( teCopy != nullptr ) + { CompoundTag *teData = new CompoundTag(); te->save(teData); @@ -493,7 +493,7 @@ void ConsoleSchematicFile::applyTileEntities(LevelChunk *chunk, AABB *chunkBox, } CompoundTag *eTag = it->second; - shared_ptr e = EntityIO::loadStatic(eTag, NULL); + shared_ptr e = EntityIO::loadStatic(eTag, nullptr); if( e->GetType() == eTYPE_PAINTING ) { @@ -582,18 +582,18 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l app.DebugPrintf("Generating schematic file for area (%d,%d,%d) to (%d,%d,%d), %dx%dx%d\n",xStart,yStart,zStart,xEnd,yEnd,zEnd,xSize,ySize,zSize); - if(dos != NULL) dos->writeInt(XBOX_SCHEMATIC_CURRENT_VERSION); + if(dos != nullptr) dos->writeInt(XBOX_SCHEMATIC_CURRENT_VERSION); - if(dos != NULL) dos->writeByte(compressionType); + if(dos != nullptr) dos->writeByte(compressionType); //Write xSize - if(dos != NULL) dos->writeInt(xSize); + if(dos != nullptr) dos->writeInt(xSize); //Write ySize - if(dos != NULL) dos->writeInt(ySize); + if(dos != nullptr) dos->writeInt(ySize); //Write zSize - if(dos != NULL) dos->writeInt(zSize); + if(dos != nullptr) dos->writeInt(zSize); //byteArray rawBuffer = level->getBlocksAndData(xStart, yStart, zStart, xSize, ySize, zSize, false); int xRowSize = ySize * zSize; @@ -660,8 +660,8 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l delete [] result.data; byteArray buffer = byteArray(ucTemp,inputSize); - if(dos != NULL) dos->writeInt(inputSize); - if(dos != NULL) dos->write(buffer); + if(dos != nullptr) dos->writeInt(inputSize); + if(dos != nullptr) dos->write(buffer); delete [] buffer.data; CompoundTag tag; @@ -725,10 +725,10 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l pos->get(2)->data -= zStart; if( e->instanceof(eTYPE_HANGING_ENTITY) ) - { - ((IntTag *) eTag->get(L"TileX") )->data -= xStart; - ((IntTag *) eTag->get(L"TileY") )->data -= yStart; - ((IntTag *) eTag->get(L"TileZ") )->data -= zStart; + { + static_cast(eTag->get(L"TileX"))->data -= xStart; + static_cast(eTag->get(L"TileY"))->data -= yStart; + static_cast(eTag->get(L"TileZ"))->data -= zStart; } entitiesTag->add(eTag); @@ -738,7 +738,7 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l tag.put(L"Entities", entitiesTag); - if(dos != NULL) NbtIo::write(&tag,dos); + if(dos != nullptr) NbtIo::write(&tag,dos); } void ConsoleSchematicFile::getBlocksAndData(LevelChunk *chunk, byteArray *data, int x0, int y0, int z0, int x1, int y1, int z1, int &blocksP, int &dataP, int &blockLightP, int &skyLightP) diff --git a/Minecraft.Client/Common/GameRules/GameRule.h b/Minecraft.Client/Common/GameRules/GameRule.h index 3b9dba7ed..e35f13752 100644 --- a/Minecraft.Client/Common/GameRules/GameRule.h +++ b/Minecraft.Client/Common/GameRules/GameRule.h @@ -40,7 +40,7 @@ public: stringValueMapType m_parameters; // These are the members of this rule that maintain it's state public: - GameRule(GameRuleDefinition *definition, Connection *connection = NULL); + GameRule(GameRuleDefinition *definition, Connection *connection = nullptr); virtual ~GameRule(); Connection *getConnection() { return m_connection; } diff --git a/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp index 80d029560..770b56d56 100644 --- a/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp @@ -50,7 +50,7 @@ GameRuleDefinition *GameRuleDefinition::addChild(ConsoleGameRules::EGameRuleType #ifndef _CONTENT_PACKAGE wprintf(L"GameRuleDefinition: Attempted to add invalid child rule - %d\n", ruleType ); #endif - return NULL; + return nullptr; } void GameRuleDefinition::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/GameRuleDefinition.h b/Minecraft.Client/Common/GameRules/GameRuleDefinition.h index afec8fbcc..4a2c43a1c 100644 --- a/Minecraft.Client/Common/GameRules/GameRuleDefinition.h +++ b/Minecraft.Client/Common/GameRules/GameRuleDefinition.h @@ -61,6 +61,6 @@ public: // Static functions static GameRulesInstance *generateNewGameRulesInstance(GameRulesInstance::EGameRulesInstanceType type, LevelRuleset *rules, Connection *connection); - static wstring generateDescriptionString(ConsoleGameRules::EGameRuleType defType, const wstring &description, void *data = NULL, int dataLength = 0); + static wstring generateDescriptionString(ConsoleGameRules::EGameRuleType defType, const wstring &description, void *data = nullptr, int dataLength = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/GameRuleManager.cpp b/Minecraft.Client/Common/GameRules/GameRuleManager.cpp index 0606808cb..95434c08c 100644 --- a/Minecraft.Client/Common/GameRules/GameRuleManager.cpp +++ b/Minecraft.Client/Common/GameRules/GameRuleManager.cpp @@ -85,24 +85,24 @@ const WCHAR *GameRuleManager::wchAttrNameA[] = GameRuleManager::GameRuleManager() { - m_currentGameRuleDefinitions = NULL; - m_currentLevelGenerationOptions = NULL; + m_currentGameRuleDefinitions = nullptr; + m_currentLevelGenerationOptions = nullptr; } void GameRuleManager::loadGameRules(DLCPack *pack) { - StringTable *strings = NULL; + StringTable *strings = nullptr; if(pack->doesPackContainFile(DLCManager::e_DLCType_LocalisationData,L"languages.loc")) { - DLCLocalisationFile *localisationFile = (DLCLocalisationFile *)pack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc"); + DLCLocalisationFile *localisationFile = static_cast(pack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")); strings = localisationFile->getStringTable(); } int gameRulesCount = pack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader); for(int i = 0; i < gameRulesCount; ++i) { - DLCGameRulesHeader *dlcHeader = (DLCGameRulesHeader *)pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i); + DLCGameRulesHeader *dlcHeader = static_cast(pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i)); DWORD dSize; byte *dData = dlcHeader->getData(dSize); @@ -120,7 +120,7 @@ void GameRuleManager::loadGameRules(DLCPack *pack) gameRulesCount = pack->getDLCItemsCount(DLCManager::e_DLCType_GameRules); for (int i = 0; i < gameRulesCount; ++i) { - DLCGameRulesFile *dlcFile = (DLCGameRulesFile *)pack->getFile(DLCManager::e_DLCType_GameRules, i); + DLCGameRulesFile *dlcFile = static_cast(pack->getFile(DLCManager::e_DLCType_GameRules, i)); DWORD dSize; byte *dData = dlcFile->getData(dSize); @@ -182,7 +182,7 @@ void GameRuleManager::loadGameRules(LevelGenerationOptions *lgo, byte *dIn, UINT compr_content(new BYTE[compr_len], compr_len); dis.read(compr_content); - Compression::getCompression()->SetDecompressionType( (Compression::ECompressionTypes)compression_type ); + Compression::getCompression()->SetDecompressionType( static_cast(compression_type) ); Compression::getCompression()->DecompressLZXRLE( content.data, &content.length, compr_content.data, compr_content.length); Compression::getCompression()->SetDecompressionType( SAVE_FILE_PLATFORM_LOCAL ); @@ -237,11 +237,11 @@ void GameRuleManager::loadGameRules(LevelGenerationOptions *lgo, byte *dIn, UINT // 4J-JEV: Reverse of loadGameRules. void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) { - if (m_currentGameRuleDefinitions == NULL && - m_currentLevelGenerationOptions == NULL) + if (m_currentGameRuleDefinitions == nullptr && + m_currentLevelGenerationOptions == nullptr) { app.DebugPrintf("GameRuleManager:: Nothing here to save."); - *dOut = NULL; + *dOut = nullptr; *dSize = 0; return; } @@ -268,7 +268,7 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) ByteArrayOutputStream compr_baos; DataOutputStream compr_dos(&compr_baos); - if (m_currentGameRuleDefinitions == NULL) + if (m_currentGameRuleDefinitions == nullptr) { compr_dos.writeInt( 0 ); // numStrings for StringTable compr_dos.writeInt( version_number ); @@ -282,9 +282,9 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) { StringTable *st = m_currentGameRuleDefinitions->getStringTable(); - if (st == NULL) + if (st == nullptr) { - app.DebugPrintf("GameRuleManager::saveGameRules: StringTable == NULL!"); + app.DebugPrintf("GameRuleManager::saveGameRules: StringTable == nullptr!"); } else { @@ -322,7 +322,7 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) *dSize = baos.buf.length; *dOut = baos.buf.data; - baos.buf.data = NULL; + baos.buf.data = nullptr; dos.close(); baos.close(); } @@ -344,6 +344,7 @@ void GameRuleManager::writeRuleFile(DataOutputStream *dos) // Write schematic files. unordered_map *files; files = getLevelGenerationOptions()->getUnfinishedSchematicFiles(); + dos->writeInt((int)files->size()); for ( auto& it : *files ) { const wstring& filename = it.first; @@ -399,8 +400,8 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT for(int i = 0; i < 8; ++i) dis.readBoolean(); } - ByteArrayInputStream *contentBais = NULL; - DataInputStream *contentDis = NULL; + ByteArrayInputStream *contentBais = nullptr; + DataInputStream *contentDis = nullptr; if(compressionType == Compression::eCompressionType_None) { @@ -469,13 +470,13 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT tagsAndAtts.push_back( contentDis->readUTF() ); unordered_map tagIdMap; - for(int type = (int)ConsoleGameRules::eGameRuleType_Root; type < (int)ConsoleGameRules::eGameRuleType_Count; ++type) + for(int type = (int)ConsoleGameRules::eGameRuleType_Root; type < static_cast(ConsoleGameRules::eGameRuleType_Count); ++type) { for(UINT i = 0; i < numStrings; ++i) { if(tagsAndAtts[i].compare(wchTagNameA[type]) == 0) { - tagIdMap.insert( unordered_map::value_type(i, (ConsoleGameRules::EGameRuleType)type) ); + tagIdMap.insert( unordered_map::value_type(i, static_cast(type)) ); break; } } @@ -497,17 +498,36 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT }*/ // subfile + // Old saves didn't write a numFiles count before the schematic entries. + // Detect this: a real count is small, but a UTF filename prefix reads as a large int. UINT numFiles = contentDis->readInt(); - for (UINT i = 0; i < numFiles; i++) + + if (lgo->isFromSave() && numFiles > 100) { - wstring sFilename = contentDis->readUTF(); - int length = contentDis->readInt(); - byteArray ba( length ); - - contentDis->read(ba); - - levelGenerator->loadSchematicFile(sFilename, ba.data, ba.length); + contentDis->skip(-4); + while (true) + { + int peek = contentDis->readInt(); + if (peek <= 100) { contentDis->skip(-4); break; } + contentDis->skip(-4); + wstring sFilename = contentDis->readUTF(); + int length = contentDis->readInt(); + byteArray ba( length ); + contentDis->read(ba); + levelGenerator->loadSchematicFile(sFilename, ba.data, ba.length); + } + } + else + { + for (UINT i = 0; i < numFiles; i++) + { + wstring sFilename = contentDis->readUTF(); + int length = contentDis->readInt(); + byteArray ba( length ); + contentDis->read(ba); + levelGenerator->loadSchematicFile(sFilename, ba.data, ba.length); + } } LEVEL_GEN_ID lgoID = LEVEL_GEN_ID_NULL; @@ -521,7 +541,7 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT auto it = tagIdMap.find(tagId); if(it != tagIdMap.end()) tagVal = it->second; - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(tagVal == ConsoleGameRules::eGameRuleType_LevelGenerationOptions) { @@ -548,14 +568,14 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT { // Not default contentDis->close(); - if(contentBais != NULL) delete contentBais; + if(contentBais != nullptr) delete contentBais; delete contentDis; } dis.close(); bais.reset(); - //if(!levelGenAdded) { delete levelGenerator; levelGenerator = NULL; } + //if(!levelGenAdded) { delete levelGenerator; levelGenerator = nullptr; } if(!gameRulesAdded) delete gameRules; return true; @@ -583,7 +603,7 @@ void GameRuleManager::readAttributes(DataInputStream *dis, vector *tags int attID = dis->readInt(); wstring value = dis->readUTF(); - if(rule != NULL) rule->addAttribute(tagsAndAtts->at(attID),value); + if(rule != nullptr) rule->addAttribute(tagsAndAtts->at(attID),value); } } @@ -597,8 +617,8 @@ void GameRuleManager::readChildren(DataInputStream *dis, vector *tagsAn auto it = tagIdMap->find(tagId); if(it != tagIdMap->end()) tagVal = it->second; - GameRuleDefinition *childRule = NULL; - if(rule != NULL) childRule = rule->addChild(tagVal); + GameRuleDefinition *childRule = nullptr; + if(rule != nullptr) childRule = rule->addChild(tagVal); readAttributes(dis,tagsAndAtts,childRule); readChildren(dis,tagsAndAtts,tagIdMap,childRule); @@ -607,7 +627,7 @@ void GameRuleManager::readChildren(DataInputStream *dis, vector *tagsAn void GameRuleManager::processSchematics(LevelChunk *levelChunk) { - if(getLevelGenerationOptions() != NULL) + if(getLevelGenerationOptions() != nullptr) { LevelGenerationOptions *levelGenOptions = getLevelGenerationOptions(); levelGenOptions->processSchematics(levelChunk); @@ -616,7 +636,7 @@ void GameRuleManager::processSchematics(LevelChunk *levelChunk) void GameRuleManager::processSchematicsLighting(LevelChunk *levelChunk) { - if(getLevelGenerationOptions() != NULL) + if(getLevelGenerationOptions() != nullptr) { LevelGenerationOptions *levelGenOptions = getLevelGenerationOptions(); levelGenOptions->processSchematicsLighting(levelChunk); @@ -701,21 +721,21 @@ void GameRuleManager::setLevelGenerationOptions(LevelGenerationOptions *levelGen { unloadCurrentGameRules(); - m_currentGameRuleDefinitions = NULL; + m_currentGameRuleDefinitions = nullptr; m_currentLevelGenerationOptions = levelGen; - if(m_currentLevelGenerationOptions != NULL && m_currentLevelGenerationOptions->requiresGameRules() ) + if(m_currentLevelGenerationOptions != nullptr && m_currentLevelGenerationOptions->requiresGameRules() ) { m_currentGameRuleDefinitions = m_currentLevelGenerationOptions->getRequiredGameRules(); } - if(m_currentLevelGenerationOptions != NULL) + if(m_currentLevelGenerationOptions != nullptr) m_currentLevelGenerationOptions->reset_start(); } LPCWSTR GameRuleManager::GetGameRulesString(const wstring &key) { - if(m_currentGameRuleDefinitions != NULL && !key.empty() ) + if(m_currentGameRuleDefinitions != nullptr && !key.empty() ) { return m_currentGameRuleDefinitions->getString(key); } @@ -739,9 +759,9 @@ LEVEL_GEN_ID GameRuleManager::addLevelGenerationOptions(LevelGenerationOptions * void GameRuleManager::unloadCurrentGameRules() { - if (m_currentLevelGenerationOptions != NULL) + if (m_currentLevelGenerationOptions != nullptr) { - if (m_currentGameRuleDefinitions != NULL + if (m_currentGameRuleDefinitions != nullptr && m_currentLevelGenerationOptions->isFromSave()) m_levelRules.removeLevelRule( m_currentGameRuleDefinitions ); @@ -757,6 +777,6 @@ void GameRuleManager::unloadCurrentGameRules() } } - m_currentGameRuleDefinitions = NULL; - m_currentLevelGenerationOptions = NULL; + m_currentGameRuleDefinitions = nullptr; + m_currentLevelGenerationOptions = nullptr; } diff --git a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp index 59fde56e0..2af1826cf 100644 --- a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp +++ b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp @@ -44,8 +44,8 @@ bool JustGrSource::ready() { return true; } LevelGenerationOptions::LevelGenerationOptions(DLCPack *parentPack) { - m_spawnPos = NULL; - m_stringTable = NULL; + m_spawnPos = nullptr; + m_stringTable = nullptr; m_hasLoadedData = false; @@ -56,7 +56,7 @@ LevelGenerationOptions::LevelGenerationOptions(DLCPack *parentPack) m_minY = INT_MAX; m_bRequiresGameRules = false; - m_pbBaseSaveData = NULL; + m_pbBaseSaveData = nullptr; m_dwBaseSaveSize = 0; m_parentDLCPack = parentPack; @@ -66,7 +66,7 @@ LevelGenerationOptions::LevelGenerationOptions(DLCPack *parentPack) LevelGenerationOptions::~LevelGenerationOptions() { clearSchematics(); - if(m_spawnPos != NULL) delete m_spawnPos; + if(m_spawnPos != nullptr) delete m_spawnPos; for (auto& it : m_schematicRules ) { delete it; @@ -141,26 +141,26 @@ void LevelGenerationOptions::getChildren(vector *children) GameRuleDefinition *LevelGenerationOptions::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_ApplySchematic) { rule = new ApplySchematicRuleDefinition(this); - m_schematicRules.push_back((ApplySchematicRuleDefinition *)rule); + m_schematicRules.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_GenerateStructure) { rule = new ConsoleGenerateStructure(); - m_structureRules.push_back((ConsoleGenerateStructure *)rule); + m_structureRules.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_BiomeOverride) { rule = new BiomeOverride(); - m_biomeOverrides.push_back((BiomeOverride *)rule); + m_biomeOverrides.push_back(static_cast(rule)); } else if(ruleType == ConsoleGameRules::eGameRuleType_StartFeature) { rule = new StartFeature(); - m_features.push_back((StartFeature *)rule); + m_features.push_back(static_cast(rule)); } else { @@ -180,21 +180,21 @@ void LevelGenerationOptions::addAttribute(const wstring &attributeName, const ws } else if(attributeName.compare(L"spawnX") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->x = value; app.DebugPrintf("LevelGenerationOptions: Adding parameter spawnX=%d\n",value); } else if(attributeName.compare(L"spawnY") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->y = value; app.DebugPrintf("LevelGenerationOptions: Adding parameter spawnY=%d\n",value); } else if(attributeName.compare(L"spawnZ") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->z = value; app.DebugPrintf("LevelGenerationOptions: Adding parameter spawnZ=%d\n",value); @@ -268,7 +268,7 @@ void LevelGenerationOptions::processSchematics(LevelChunk *chunk) if (structureStart->getBoundingBox()->intersects(cx, cz, cx + 15, cz + 15)) { BoundingBox *bb = new BoundingBox(cx, cz, cx + 15, cz + 15); - structureStart->postProcess(chunk->level, NULL, bb); + structureStart->postProcess(chunk->level, nullptr, bb); delete bb; } } @@ -353,7 +353,7 @@ ConsoleSchematicFile *LevelGenerationOptions::loadSchematicFile(const wstring &f return it->second; } - ConsoleSchematicFile *schematic = NULL; + ConsoleSchematicFile *schematic = nullptr; byteArray data(pbData,dwLen); ByteArrayInputStream bais(data); DataInputStream dis(&bais); @@ -366,7 +366,7 @@ ConsoleSchematicFile *LevelGenerationOptions::loadSchematicFile(const wstring &f ConsoleSchematicFile *LevelGenerationOptions::getSchematicFile(const wstring &filename) { - ConsoleSchematicFile *schematic = NULL; + ConsoleSchematicFile *schematic = nullptr; // If we have already loaded this, just return auto it = m_schematics.find(filename); if(it != m_schematics.end()) @@ -399,7 +399,7 @@ void LevelGenerationOptions::loadStringTable(StringTable *table) LPCWSTR LevelGenerationOptions::getString(const wstring &key) { - if(m_stringTable == NULL) + if(m_stringTable == nullptr) { return L""; } @@ -455,8 +455,76 @@ unordered_map *LevelGenerationOptions::getUnfin void LevelGenerationOptions::loadBaseSaveData() { +#ifdef _WINDOWS64 + + int gameRulesCount = m_parentDLCPack ? m_parentDLCPack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader) : 0; + + wstring baseSave = getBaseSavePath(); + wstring packName = baseSave.substr(0, baseSave.find(L'.')); + + for (int i = 0; i < gameRulesCount; ++i) + { + DLCGameRulesHeader* dlcFile = static_cast(m_parentDLCPack->getFile(DLCManager::e_DLCType_GameRulesHeader, i)); + + if (!dlcFile->getGrfPath().empty()) + { + File grf(L"Windows64Media\\DLC\\" + packName + L"\\Data\\" + dlcFile->getGrfPath()); + + if (grf.exists()) + { + wstring path = grf.getPath(); + HANDLE fileHandle = CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + + if (fileHandle != INVALID_HANDLE_VALUE) + { + DWORD dwFileSize = grf.length(); + DWORD bytesRead; + PBYTE pbData = new BYTE[dwFileSize]; + BOOL bSuccess = ReadFile(fileHandle, pbData, dwFileSize, &bytesRead, nullptr); + CloseHandle(fileHandle); + + if (bSuccess) + { + dlcFile->setGrfData(pbData, dwFileSize, m_stringTable); + app.m_gameRules.setLevelGenerationOptions(dlcFile->lgo); + } + delete[] pbData; + } + } + } + } + + if (requiresBaseSave() && !getBaseSavePath().empty()) + { + File save(L"Windows64Media\\DLC\\" + packName + L"\\Data\\" + baseSave); + + if (save.exists()) + { + wstring path = save.getPath(); + HANDLE fileHandle = CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + + if (fileHandle != INVALID_HANDLE_VALUE) + { + DWORD dwFileSize = GetFileSize(fileHandle, nullptr); + DWORD bytesRead; + PBYTE pbData = new BYTE[dwFileSize]; + BOOL bSuccess = ReadFile(fileHandle, pbData, dwFileSize, &bytesRead, nullptr); + CloseHandle(fileHandle); + + if (bSuccess) + setBaseSaveData(pbData, dwFileSize); + else + delete[] pbData; + } + } + } + + setLoadedData(); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); + +#else int mountIndex = -1; - if(m_parentDLCPack != NULL) mountIndex = m_parentDLCPack->GetDLCMountIndex(); + if(m_parentDLCPack != nullptr) mountIndex = m_parentDLCPack->GetDLCMountIndex(); if(mountIndex > -1) { @@ -481,11 +549,12 @@ void LevelGenerationOptions::loadBaseSaveData() setLoadedData(); app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); } +#endif } int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicenceMask) { - LevelGenerationOptions *lgo = (LevelGenerationOptions *)pParam; + LevelGenerationOptions *lgo = static_cast(pParam); lgo->m_bLoadingData = false; if(dwErr!=ERROR_SUCCESS) { @@ -499,7 +568,7 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD int gameRulesCount = lgo->m_parentDLCPack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader); for(int i = 0; i < gameRulesCount; ++i) { - DLCGameRulesHeader *dlcFile = (DLCGameRulesHeader *) lgo->m_parentDLCPack->getFile(DLCManager::e_DLCType_GameRulesHeader, i); + DLCGameRulesHeader *dlcFile = static_cast(lgo->m_parentDLCPack->getFile(DLCManager::e_DLCType_GameRulesHeader, i)); if (!dlcFile->getGrfPath().empty()) { @@ -513,10 +582,10 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #else const char *pchFilename=wstringtofilename(grf.getPath()); @@ -524,10 +593,10 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #endif @@ -536,7 +605,7 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD DWORD dwFileSize = grf.length(); DWORD bytesRead; PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); @@ -565,10 +634,10 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #else const char *pchFilename=wstringtofilename(save.getPath()); @@ -576,18 +645,18 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #endif if( fileHandle != INVALID_HANDLE_VALUE ) { - DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,NULL); + DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,nullptr); PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); @@ -624,8 +693,8 @@ void LevelGenerationOptions::reset_start() void LevelGenerationOptions::reset_finish() { - //if (m_spawnPos) { delete m_spawnPos; m_spawnPos = NULL; } - //if (m_stringTable) { delete m_stringTable; m_stringTable = NULL; } + //if (m_spawnPos) { delete m_spawnPos; m_spawnPos = nullptr; } + //if (m_stringTable) { delete m_stringTable; m_stringTable = nullptr; } if (isFromDLC()) { @@ -694,8 +763,8 @@ bool LevelGenerationOptions::ready() { return info()->ready(); } void LevelGenerationOptions::setBaseSaveData(PBYTE pbData, DWORD dwSize) { m_pbBaseSaveData = pbData; m_dwBaseSaveSize = dwSize; } PBYTE LevelGenerationOptions::getBaseSaveData(DWORD &size) { size = m_dwBaseSaveSize; return m_pbBaseSaveData; } -bool LevelGenerationOptions::hasBaseSaveData() { return m_dwBaseSaveSize > 0 && m_pbBaseSaveData != NULL; } -void LevelGenerationOptions::deleteBaseSaveData() { if(m_pbBaseSaveData) delete m_pbBaseSaveData; m_pbBaseSaveData = NULL; m_dwBaseSaveSize = 0; } +bool LevelGenerationOptions::hasBaseSaveData() { return m_dwBaseSaveSize > 0 && m_pbBaseSaveData != nullptr; } +void LevelGenerationOptions::deleteBaseSaveData() { if(m_pbBaseSaveData) delete m_pbBaseSaveData; m_pbBaseSaveData = nullptr; m_dwBaseSaveSize = 0; } bool LevelGenerationOptions::hasLoadedData() { return m_hasLoadedData; } void LevelGenerationOptions::setLoadedData() { m_hasLoadedData = true; } diff --git a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.h b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.h index cf669019a..378ac6c5d 100644 --- a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.h +++ b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.h @@ -167,7 +167,7 @@ private: bool m_bLoadingData; public: - LevelGenerationOptions(DLCPack *parentPack = NULL); + LevelGenerationOptions(DLCPack *parentPack = nullptr); ~LevelGenerationOptions(); virtual ConsoleGameRules::EGameRuleType getActionType(); @@ -202,7 +202,7 @@ public: LevelRuleset *getRequiredGameRules(); void getBiomeOverride(int biomeId, BYTE &tile, BYTE &topTile); - bool isFeatureChunk(int chunkX, int chunkZ, StructureFeature::EFeatureTypes feature, int *orientation = NULL); + bool isFeatureChunk(int chunkX, int chunkZ, StructureFeature::EFeatureTypes feature, int *orientation = nullptr); void loadStringTable(StringTable *table); LPCWSTR getString(const wstring &key); diff --git a/Minecraft.Client/Common/GameRules/LevelRuleset.cpp b/Minecraft.Client/Common/GameRules/LevelRuleset.cpp index 658abe91f..de17bacca 100644 --- a/Minecraft.Client/Common/GameRules/LevelRuleset.cpp +++ b/Minecraft.Client/Common/GameRules/LevelRuleset.cpp @@ -6,7 +6,7 @@ LevelRuleset::LevelRuleset() { - m_stringTable = NULL; + m_stringTable = nullptr; } LevelRuleset::~LevelRuleset() @@ -26,11 +26,11 @@ void LevelRuleset::getChildren(vector *children) GameRuleDefinition *LevelRuleset::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_NamedArea) { rule = new NamedAreaRuleDefinition(); - m_areas.push_back((NamedAreaRuleDefinition *)rule); + m_areas.push_back(static_cast(rule)); } else { @@ -46,7 +46,7 @@ void LevelRuleset::loadStringTable(StringTable *table) LPCWSTR LevelRuleset::getString(const wstring &key) { - if(m_stringTable == NULL) + if(m_stringTable == nullptr) { return L""; } diff --git a/Minecraft.Client/Common/GameRules/StartFeature.cpp b/Minecraft.Client/Common/GameRules/StartFeature.cpp index 904bce734..14b6d9c93 100644 --- a/Minecraft.Client/Common/GameRules/StartFeature.cpp +++ b/Minecraft.Client/Common/GameRules/StartFeature.cpp @@ -47,7 +47,7 @@ void StartFeature::addAttribute(const wstring &attributeName, const wstring &att else if(attributeName.compare(L"feature") == 0) { int value = _fromString(attributeValue); - m_feature = (StructureFeature::EFeatureTypes)value; + m_feature = static_cast(value); app.DebugPrintf("StartFeature: Adding parameter feature=%d\n",m_feature); } else @@ -58,6 +58,6 @@ void StartFeature::addAttribute(const wstring &attributeName, const wstring &att bool StartFeature::isFeatureChunk(int chunkX, int chunkZ, StructureFeature::EFeatureTypes feature, int *orientation) { - if(orientation != NULL) *orientation = m_orientation; + if(orientation != nullptr) *orientation = m_orientation; return chunkX == m_chunkX && chunkZ == m_chunkZ && feature == m_feature; } \ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp index ec218c7a9..99aee99b0 100644 --- a/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp @@ -12,7 +12,7 @@ UpdatePlayerRuleDefinition::UpdatePlayerRuleDefinition() m_bUpdateHealth = m_bUpdateFood = m_bUpdateYRot = false;; m_health = 0; m_food = 0; - m_spawnPos = NULL; + m_spawnPos = nullptr; m_yRot = 0.0f; } @@ -65,11 +65,11 @@ void UpdatePlayerRuleDefinition::getChildren(vector *child GameRuleDefinition *UpdatePlayerRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_AddItem) { rule = new AddItemRuleDefinition(); - m_items.push_back((AddItemRuleDefinition *)rule); + m_items.push_back(static_cast(rule)); } else { @@ -84,21 +84,21 @@ void UpdatePlayerRuleDefinition::addAttribute(const wstring &attributeName, cons { if(attributeName.compare(L"spawnX") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->x = value; app.DebugPrintf("UpdatePlayerRuleDefinition: Adding parameter spawnX=%d\n",value); } else if(attributeName.compare(L"spawnY") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->y = value; app.DebugPrintf("UpdatePlayerRuleDefinition: Adding parameter spawnY=%d\n",value); } else if(attributeName.compare(L"spawnZ") == 0) { - if(m_spawnPos == NULL) m_spawnPos = new Pos(); + if(m_spawnPos == nullptr) m_spawnPos = new Pos(); int value = _fromString(attributeValue); m_spawnPos->z = value; app.DebugPrintf("UpdatePlayerRuleDefinition: Adding parameter spawnZ=%d\n",value); @@ -148,7 +148,7 @@ void UpdatePlayerRuleDefinition::postProcessPlayer(shared_ptr player) double z = player->z; float yRot = player->yRot; float xRot = player->xRot; - if(m_spawnPos != NULL) + if(m_spawnPos != nullptr) { x = m_spawnPos->x; y = m_spawnPos->y; @@ -160,7 +160,7 @@ void UpdatePlayerRuleDefinition::postProcessPlayer(shared_ptr player) yRot = m_yRot; } - if(m_spawnPos != NULL || m_bUpdateYRot) player->absMoveTo(x,y,z,yRot,xRot); + if(m_spawnPos != nullptr || m_bUpdateYRot) player->absMoveTo(x,y,z,yRot,xRot); for(auto& addItem : m_items) { diff --git a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp index fa68ef6a4..1f4946912 100644 --- a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp +++ b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp @@ -33,11 +33,11 @@ void XboxStructureActionPlaceContainer::getChildren(vector GameRuleDefinition *XboxStructureActionPlaceContainer::addChild(ConsoleGameRules::EGameRuleType ruleType) { - GameRuleDefinition *rule = NULL; + GameRuleDefinition *rule = nullptr; if(ruleType == ConsoleGameRules::eGameRuleType_AddItem) { rule = new AddItemRuleDefinition(); - m_items.push_back((AddItemRuleDefinition *)rule); + m_items.push_back(static_cast(rule)); } else { @@ -70,7 +70,7 @@ bool XboxStructureActionPlaceContainer::placeContainerInLevel(StructurePiece *st if ( chunkBB->isInside( worldX, worldY, worldZ ) ) { - if ( level->getTileEntity( worldX, worldY, worldZ ) != NULL ) + if ( level->getTileEntity( worldX, worldY, worldZ ) != nullptr ) { // Remove the current tile entity level->removeTileEntity( worldX, worldY, worldZ ); @@ -81,7 +81,7 @@ bool XboxStructureActionPlaceContainer::placeContainerInLevel(StructurePiece *st shared_ptr container = dynamic_pointer_cast(level->getTileEntity( worldX, worldY, worldZ )); app.DebugPrintf("XboxStructureActionPlaceContainer - placing a container at (%d,%d,%d)\n", worldX, worldY, worldZ); - if ( container != NULL ) + if ( container != nullptr ) { level->setData( worldX, worldY, worldZ, m_data, Tile::UPDATE_CLIENTS); // Add items diff --git a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceSpawner.cpp b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceSpawner.cpp index 3f6204af7..3e61154fc 100644 --- a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceSpawner.cpp +++ b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceSpawner.cpp @@ -46,7 +46,7 @@ bool XboxStructureActionPlaceSpawner::placeSpawnerInLevel(StructurePiece *struct if ( chunkBB->isInside( worldX, worldY, worldZ ) ) { - if ( level->getTileEntity( worldX, worldY, worldZ ) != NULL ) + if ( level->getTileEntity( worldX, worldY, worldZ ) != nullptr ) { // Remove the current tile entity level->removeTileEntity( worldX, worldY, worldZ ); @@ -59,7 +59,7 @@ bool XboxStructureActionPlaceSpawner::placeSpawnerInLevel(StructurePiece *struct #ifndef _CONTENT_PACKAGE wprintf(L"XboxStructureActionPlaceSpawner - placing a %ls spawner at (%d,%d,%d)\n", m_entityId.c_str(), worldX, worldY, worldZ); #endif - if( entity != NULL ) + if( entity != nullptr ) { entity->setEntityId(m_entityId); } diff --git a/Minecraft.Client/Common/Leaderboards/LeaderboardInterface.cpp b/Minecraft.Client/Common/Leaderboards/LeaderboardInterface.cpp index 07463517a..06f9a69bd 100644 --- a/Minecraft.Client/Common/Leaderboards/LeaderboardInterface.cpp +++ b/Minecraft.Client/Common/Leaderboards/LeaderboardInterface.cpp @@ -6,8 +6,8 @@ LeaderboardInterface::LeaderboardInterface(LeaderboardManager *man) m_manager = man; m_pending = false; - m_filter = (LeaderboardManager::EFilterMode) -1; - m_callback = NULL; + m_filter = static_cast(-1); + m_callback = nullptr; m_difficulty = 0; m_type = LeaderboardManager::eStatsType_UNDEFINED; m_startIndex = 0; diff --git a/Minecraft.Client/Common/Leaderboards/LeaderboardManager.cpp b/Minecraft.Client/Common/Leaderboards/LeaderboardManager.cpp index 33707b14c..2ba1efd60 100644 --- a/Minecraft.Client/Common/Leaderboards/LeaderboardManager.cpp +++ b/Minecraft.Client/Common/Leaderboards/LeaderboardManager.cpp @@ -12,7 +12,7 @@ const wstring LeaderboardManager::filterNames[eNumFilterModes] = void LeaderboardManager::DeleteInstance() { delete m_instance; - m_instance = NULL; + m_instance = nullptr; } LeaderboardManager::LeaderboardManager() @@ -26,7 +26,7 @@ void LeaderboardManager::zeroReadParameters() { m_difficulty = -1; m_statsType = eStatsType_UNDEFINED; - m_readListener = NULL; + m_readListener = nullptr; m_startIndex = 0; m_readCount = 0; m_eFilterMode = eFM_UNDEFINED; diff --git a/Minecraft.Client/Common/Leaderboards/SonyLeaderboardManager.cpp b/Minecraft.Client/Common/Leaderboards/SonyLeaderboardManager.cpp index 78d62568c..f2d48947d 100644 --- a/Minecraft.Client/Common/Leaderboards/SonyLeaderboardManager.cpp +++ b/Minecraft.Client/Common/Leaderboards/SonyLeaderboardManager.cpp @@ -35,7 +35,7 @@ SonyLeaderboardManager::SonyLeaderboardManager() m_myXUID = INVALID_XUID; - m_scores = NULL; + m_scores = nullptr; m_statsType = eStatsType_Kills; m_difficulty = 0; @@ -47,7 +47,7 @@ SonyLeaderboardManager::SonyLeaderboardManager() InitializeCriticalSection(&m_csViewsLock); m_running = false; - m_threadScoreboard = NULL; + m_threadScoreboard = nullptr; } SonyLeaderboardManager::~SonyLeaderboardManager() @@ -288,7 +288,7 @@ bool SonyLeaderboardManager::getScoreByIds() SonyRtcTick last_sort_date; SceNpScoreRankNumber mTotalRecord; - SceNpId *npIds = NULL; + SceNpId *npIds = nullptr; int ret; uint32_t num = 0; @@ -322,7 +322,7 @@ bool SonyLeaderboardManager::getScoreByIds() ZeroMemory(comments, sizeof(SceNpScoreComment) * num); /* app.DebugPrintf("sceNpScoreGetRankingByNpId(\n\t transaction=%i,\n\t boardID=0,\n\t npId=%i,\n\t friendCount*sizeof(SceNpId)=%i*%i=%i,\ - rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t NULL, 0, NULL, 0,\n\t friendCount=%i,\n...\n", + rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t nullptr, 0, nullptr, 0,\n\t friendCount=%i,\n...\n", transaction, npId, friendCount, sizeof(SceNpId), friendCount*sizeof(SceNpId), rankData, friendCount*sizeof(SceNpScorePlayerRankData), friendCount ); */ @@ -342,9 +342,9 @@ bool SonyLeaderboardManager::getScoreByIds() destroyTransactionContext(ret); - if (npIds != NULL) delete [] npIds; - if (ptr != NULL) delete [] ptr; - if (comments != NULL) delete [] comments; + if (npIds != nullptr) delete [] npIds; + if (ptr != nullptr) delete [] ptr; + if (comments != nullptr) delete [] comments; return false; } @@ -355,9 +355,9 @@ bool SonyLeaderboardManager::getScoreByIds() m_eStatsState = eStatsState_Failed; - if (npIds != NULL) delete [] npIds; - if (ptr != NULL) delete [] ptr; - if (comments != NULL) delete [] comments; + if (npIds != nullptr) delete [] npIds; + if (ptr != nullptr) delete [] ptr; + if (comments != nullptr) delete [] comments; return false; } @@ -387,14 +387,14 @@ bool SonyLeaderboardManager::getScoreByIds() comments, sizeof(SceNpScoreComment) * tmpNum, //OUT: Comments #endif - NULL, 0, // GameData. (unused) + nullptr, 0, // GameData. (unused) tmpNum, &last_sort_date, &mTotalRecord, - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -425,7 +425,7 @@ bool SonyLeaderboardManager::getScoreByIds() m_readCount = num; // Filter scorers and construct output structure. - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_scores = new ReadScore[m_readCount]; convertToOutput(m_readCount, m_scores, ptr, comments); m_maxRank = m_readCount; @@ -458,7 +458,7 @@ error3: delete [] ptr; delete [] comments; error2: - if (npIds != NULL) delete [] npIds; + if (npIds != nullptr) delete [] npIds; error1: if (m_eStatsState != eStatsState_Canceled) m_eStatsState = eStatsState_Failed; app.DebugPrintf("[SonyLeaderboardManager] getScoreByIds() FAILED, ret=0x%X\n", ret); @@ -511,14 +511,14 @@ bool SonyLeaderboardManager::getScoreByRange() comments, sizeof(SceNpScoreComment) * num, //OUT: Comment Data - NULL, 0, // GameData. + nullptr, 0, // GameData. num, &last_sort_date, &m_maxRank, // 'Total number of players registered in the target scoreboard.' - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -539,7 +539,7 @@ bool SonyLeaderboardManager::getScoreByRange() delete [] ptr; delete [] comments; - m_scores = NULL; + m_scores = nullptr; m_readCount = 0; m_eStatsState = eStatsState_Ready; @@ -557,7 +557,7 @@ bool SonyLeaderboardManager::getScoreByRange() //m_stats = ptr; //Maybe: addPadding(num,ptr); - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_readCount = ret; m_scores = new ReadScore[m_readCount]; for (int i=0; i 0) ret = eStatsReturn_Success; - if (m_readListener != NULL) + if (m_readListener != nullptr) { app.DebugPrintf("[SonyLeaderboardManager] OnStatsReadComplete(%i, %i, _), m_readCount=%i.\n", ret, m_maxRank, m_readCount); m_readListener->OnStatsReadComplete(ret, m_maxRank, view); @@ -716,16 +716,16 @@ void SonyLeaderboardManager::Tick() m_eStatsState = eStatsState_Idle; delete [] m_scores; - m_scores = NULL; + m_scores = nullptr; } break; case eStatsState_Failed: { view.m_numQueries = 0; - view.m_queries = NULL; + view.m_queries = nullptr; - if ( m_readListener != NULL ) + if ( m_readListener != nullptr ) m_readListener->OnStatsReadComplete(eStatsReturn_NetworkError, 0, view); m_eStatsState = eStatsState_Idle; @@ -747,7 +747,7 @@ bool SonyLeaderboardManager::OpenSession() { if (m_openSessions == 0) { - if (m_threadScoreboard == NULL) + if (m_threadScoreboard == nullptr) { m_threadScoreboard = new C4JThread(&scoreboardThreadEntry, this, "4JScoreboard"); m_threadScoreboard->SetProcessor(CPU_CORE_LEADERBOARDS); @@ -837,7 +837,7 @@ void SonyLeaderboardManager::FlushStats() {} void SonyLeaderboardManager::CancelOperation() { - m_readListener = NULL; + m_readListener = nullptr; m_eStatsState = eStatsState_Canceled; if (m_requestId != 0) @@ -980,7 +980,7 @@ void SonyLeaderboardManager::fromBase32(void *out, SceNpScoreComment *in) for (int i = 0; i < SCE_NP_SCORE_COMMENT_MAXLEN; i++) { ch[0] = getComment(in)[i]; - unsigned char fivebits = strtol(ch, NULL, 32) << 3; + unsigned char fivebits = strtol(ch, nullptr, 32) << 3; int sByte = (i*5) / 8; int eByte = (5+(i*5)) / 8; @@ -1041,7 +1041,7 @@ bool SonyLeaderboardManager::test_string(string testing) int ctx = createTransactionContext(m_titleContext); if (ctx<0) return false; - int ret = sceNpScoreCensorComment(ctx, (const char *) &comment, NULL); + int ret = sceNpScoreCensorComment(ctx, (const char *) &comment, nullptr); if (ret == SCE_NP_COMMUNITY_SERVER_ERROR_CENSORED) { diff --git a/Minecraft.Client/Common/Media/Intro1080.swf b/Minecraft.Client/Common/Media/Intro1080.swf index c9f2d3ba4..e0a90a579 100644 Binary files a/Minecraft.Client/Common/Media/Intro1080.swf and b/Minecraft.Client/Common/Media/Intro1080.swf differ diff --git a/Minecraft.Client/Common/Media/MediaWindows64.arc b/Minecraft.Client/Common/Media/MediaWindows64.arc index 6ce552c53..0756ef1e1 100644 Binary files a/Minecraft.Client/Common/Media/MediaWindows64.arc and b/Minecraft.Client/Common/Media/MediaWindows64.arc differ diff --git a/Minecraft.Client/Common/Media/SettingsGraphicsMenu1080.swf b/Minecraft.Client/Common/Media/SettingsGraphicsMenu1080.swf index f6866abf1..2495b4342 100644 Binary files a/Minecraft.Client/Common/Media/SettingsGraphicsMenu1080.swf and b/Minecraft.Client/Common/Media/SettingsGraphicsMenu1080.swf differ diff --git a/Minecraft.Client/Common/Media/SettingsGraphicsMenu480.swf b/Minecraft.Client/Common/Media/SettingsGraphicsMenu480.swf index c360db92d..aae01e78c 100644 Binary files a/Minecraft.Client/Common/Media/SettingsGraphicsMenu480.swf and b/Minecraft.Client/Common/Media/SettingsGraphicsMenu480.swf differ diff --git a/Minecraft.Client/Common/Media/SettingsGraphicsMenu720.swf b/Minecraft.Client/Common/Media/SettingsGraphicsMenu720.swf index 418b1ba2b..4e860fb1f 100644 Binary files a/Minecraft.Client/Common/Media/SettingsGraphicsMenu720.swf and b/Minecraft.Client/Common/Media/SettingsGraphicsMenu720.swf differ diff --git a/Minecraft.Client/Common/Media/languages.loc b/Minecraft.Client/Common/Media/languages.loc index c267b1ac8..3fb5b1a06 100644 Binary files a/Minecraft.Client/Common/Media/languages.loc and b/Minecraft.Client/Common/Media/languages.loc differ diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.cpp b/Minecraft.Client/Common/Network/GameNetworkManager.cpp index 92ea8ad03..50aeae689 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.cpp +++ b/Minecraft.Client/Common/Network/GameNetworkManager.cpp @@ -41,6 +41,11 @@ #include "..\Minecraft.World\DurangoStats.h" #endif +#ifdef _WINDOWS64 +#include "..\..\Windows64\Network\WinsockNetLayer.h" +#include "..\..\Windows64\Windows64_Xuid.h" +#endif + // Global instance CGameNetworkManager g_NetworkManager; CPlatformNetworkManager *CGameNetworkManager::s_pPlatformNetworkManager; @@ -56,8 +61,8 @@ CGameNetworkManager::CGameNetworkManager() m_bFullSessionMessageOnNextSessionChange = false; #ifdef __ORBIS__ - m_pUpsell = NULL; - m_pInviteInfo = NULL; + m_pUpsell = nullptr; + m_pInviteInfo = nullptr; #endif } @@ -120,26 +125,26 @@ void CGameNetworkManager::DoWork() s_pPlatformNetworkManager->DoWork(); #ifdef __ORBIS__ - if (m_pUpsell != NULL && m_pUpsell->hasResponse()) + if (m_pUpsell != nullptr && m_pUpsell->hasResponse()) { int iPad_invited = m_iPlayerInvited, iPad_checking = m_pUpsell->m_userIndex; m_iPlayerInvited = -1; delete m_pUpsell; - m_pUpsell = NULL; + m_pUpsell = nullptr; if (ProfileManager.HasPlayStationPlus(iPad_checking)) { this->GameInviteReceived(iPad_invited, m_pInviteInfo); // m_pInviteInfo deleted by GameInviteReceived. - m_pInviteInfo = NULL; + m_pInviteInfo = nullptr; } else { delete m_pInviteInfo; - m_pInviteInfo = NULL; + m_pInviteInfo = nullptr; } } #endif @@ -194,16 +199,18 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame ProfileManager.SetDeferredSignoutEnabled(true); #endif - int64_t seed = 0; - if(lpParameter != NULL) + int64_t seed = 0; + bool dedicatedNoLocalHostPlayer = false; + if (lpParameter != nullptr) { - NetworkGameInitData *param = (NetworkGameInitData *)lpParameter; + NetworkGameInitData *param = static_cast(lpParameter); seed = param->seed; + dedicatedNoLocalHostPlayer = param->dedicatedNoLocalHostPlayer; app.setLevelGenerationOptions(param->levelGen); - if(param->levelGen != NULL) + if(param->levelGen != nullptr) { - if(app.getLevelGenerationOptions() == NULL) + if(app.getLevelGenerationOptions() == nullptr) { app.DebugPrintf("Game rule was not loaded, and seed is required. Exiting.\n"); return false; @@ -248,10 +255,10 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #else const char *pchFilename=wstringtofilename(grf.getPath()); @@ -259,18 +266,18 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #endif if( fileHandle != INVALID_HANDLE_VALUE ) { - DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,NULL); + DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,nullptr); PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); @@ -312,7 +319,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame } else { - Socket::Initialise(NULL); + Socket::Initialise(nullptr); } #ifndef _XBOX @@ -354,47 +361,59 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame // PRIMARY PLAYER vector createdConnections; - ClientConnection *connection; + ClientConnection *connection = nullptr; - if( g_NetworkManager.IsHost() ) + if( g_NetworkManager.IsHost() && dedicatedNoLocalHostPlayer ) { - connection = new ClientConnection(minecraft, NULL); + app.DebugPrintf("Dedicated server mode: skipping local host client connection\n"); + + // Keep telemetry behavior consistent with the host path. + INT multiplayerInstanceId = TelemetryManager->GenerateMultiplayerInstanceId(); + TelemetryManager->SetMultiplayerInstanceId(multiplayerInstanceId); + + app.SetGameMode( eMode_Multiplayer ); + } + else if( g_NetworkManager.IsHost() ) + { + connection = new ClientConnection(minecraft, nullptr); } else { INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(ProfileManager.GetLockedProfile()); - if(pNetworkPlayer == NULL) + if(pNetworkPlayer == nullptr) { MinecraftServer::HaltServer(); app.DebugPrintf("%d\n",ProfileManager.GetLockedProfile()); - // If the player is NULL here then something went wrong in the session setup, and continuing will end up in a crash + // If the player is nullptr here then something went wrong in the session setup, and continuing will end up in a crash return false; } Socket *socket = pNetworkPlayer->GetSocket(); // Fix for #13259 - CRASH: Gameplay: loading process is halted when player loads saved data - if(socket == NULL) + if(socket == nullptr) { assert(false); MinecraftServer::HaltServer(); - // If the socket is NULL here then something went wrong in the session setup, and continuing will end up in a crash + // If the socket is nullptr here then something went wrong in the session setup, and continuing will end up in a crash return false; } connection = new ClientConnection(minecraft, socket); } - if( !connection->createdOk ) + if (connection != nullptr) { - assert(false); - delete connection; - connection = NULL; - MinecraftServer::HaltServer(); - return false; - } + if( !connection->createdOk ) + { + assert(false); + delete connection; + connection = nullptr; + MinecraftServer::HaltServer(); + return false; + } - connection->send( shared_ptr( new PreLoginPacket(minecraft->user->name) ) ); + connection->send(std::make_shared(minecraft->user->name)); // Tick connection until we're ready to go. The stages involved in this are: // (1) Creating the ClientConnection sends a prelogin packet to the server @@ -429,9 +448,9 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame connection->close(); } - if( connection->isStarted() && !connection->isClosed() ) - { - createdConnections.push_back( connection ); + if( connection->isStarted() && !connection->isClosed() ) + { + createdConnections.push_back( connection ); int primaryPad = ProfileManager.GetPrimaryPad(); app.SetRichPresenceContext(primaryPad,CONTEXT_GAME_STATE_BLANK); @@ -453,7 +472,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame // Already have setup the primary pad if(idx == ProfileManager.GetPrimaryPad() ) continue; - if( GetLocalPlayerByUserIndex(idx) != NULL && !ProfileManager.IsSignedIn(idx) ) + if( GetLocalPlayerByUserIndex(idx) != nullptr && !ProfileManager.IsSignedIn(idx) ) { INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(idx); Socket *socket = pNetworkPlayer->GetSocket(); @@ -467,7 +486,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame // when joining any other way, so just because they are signed in doesn't mean they are in the session // 4J Stu - If they are in the session, then we should add them to the game. Otherwise we won't be able to add them later INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(idx); - if( pNetworkPlayer == NULL ) + if( pNetworkPlayer == nullptr ) continue; ClientConnection *connection; @@ -481,7 +500,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame // Open the socket on the server end to accept incoming data Socket::addIncomingSocket(socket); - connection->send( shared_ptr( new PreLoginPacket(convStringToWstring( ProfileManager.GetGamertag(idx) )) ) ); + connection->send(std::make_shared(convStringToWstring(ProfileManager.GetGamertag(idx)))); createdConnections.push_back( connection ); @@ -528,13 +547,14 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame } } - app.SetGameMode( eMode_Multiplayer ); - } - else if ( connection->isClosed() || !IsInSession()) - { + app.SetGameMode( eMode_Multiplayer ); + } + else if ( connection->isClosed() || !IsInSession()) + { // assert(false); - MinecraftServer::HaltServer(); - return false; + MinecraftServer::HaltServer(); + return false; + } } @@ -744,7 +764,7 @@ CGameNetworkManager::eJoinGameResult CGameNetworkManager::JoinGame(FriendSession // Make sure that the Primary Pad is in by default localUsersMask |= GetLocalPlayerMask( ProfileManager.GetPrimaryPad() ); - return (eJoinGameResult)(s_pPlatformNetworkManager->JoinGame( searchResult, localUsersMask, primaryUserIndex )); + return static_cast(s_pPlatformNetworkManager->JoinGame(searchResult, localUsersMask, primaryUserIndex)); } void CGameNetworkManager::CancelJoinGame(LPVOID lpParam) @@ -762,7 +782,7 @@ bool CGameNetworkManager::LeaveGame(bool bMigrateHost) int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContinue, int iPad) { - INVITE_INFO * pInviteInfo = (INVITE_INFO *)pParam; + INVITE_INFO * pInviteInfo = static_cast(pParam); if(bContinue==true) { @@ -801,9 +821,9 @@ int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContin // Check if user-created content is allowed, as we cannot play multiplayer if it's not bool noUGC = false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(iPad,false,&noUGC,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,false,&noUGC,nullptr,nullptr); #elif defined(__ORBIS__) - ProfileManager.GetChatAndContentRestrictions(iPad,false,NULL,&noUGC,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,false,nullptr,&noUGC,nullptr); #endif if(noUGC) @@ -823,7 +843,7 @@ int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContin { #if defined(__ORBIS__) || defined(__PSVITA__) bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(iPad,false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( 0, ProfileManager.GetPrimaryPad() ); @@ -912,7 +932,7 @@ int CGameNetworkManager::RunNetworkGameThreadProc( void* lpParameter ) app.SetDisconnectReason( DisconnectPacket::eDisconnect_ConnectionCreationFailed ); } // If we failed before the server started, clear the game rules. Otherwise the server will clear it up. - if(MinecraftServer::getInstance() == NULL) app.m_gameRules.unloadCurrentGameRules(); + if(MinecraftServer::getInstance() == nullptr) app.m_gameRules.unloadCurrentGameRules(); Tile::ReleaseThreadStorage(); return -1; } @@ -929,21 +949,26 @@ int CGameNetworkManager::RunNetworkGameThreadProc( void* lpParameter ) int CGameNetworkManager::ServerThreadProc( void* lpParameter ) { - int64_t seed = 0; - if(lpParameter != NULL) + int64_t seed = 0; + if (lpParameter != nullptr) { - NetworkGameInitData *param = (NetworkGameInitData *)lpParameter; + NetworkGameInitData *param = static_cast(lpParameter); seed = param->seed; app.SetGameHostOption(eGameHostOption_All,param->settings); // 4J Stu - If we are loading a DLC save that's separate from the texture pack, load - if( param->levelGen != NULL && (param->texturePackId == 0 || param->levelGen->getRequiredTexturePackId() != param->texturePackId) ) + if (param != nullptr && param->levelGen != nullptr && param->levelGen->isFromDLC()) { while((Minecraft::GetInstance()->skins->needsUIUpdate() || ui.IsReloadingSkin())) { Sleep(1); } param->levelGen->loadBaseSaveData(); + + while (!param->levelGen->hasLoadedData()) + { + Sleep(1); + } } } @@ -966,7 +991,7 @@ int CGameNetworkManager::ServerThreadProc( void* lpParameter ) IntCache::ReleaseThreadStorage(); Level::destroyLightingCache(); - if(lpParameter != NULL) delete lpParameter; + if(lpParameter != nullptr) delete lpParameter; return S_OK; } @@ -979,7 +1004,7 @@ int CGameNetworkManager::ExitAndJoinFromInviteThreadProc( void* lpParam ) Compression::UseDefaultThreadStorage(); //app.SetGameStarted(false); - UIScene_PauseMenu::_ExitWorld(NULL); + UIScene_PauseMenu::_ExitWorld(nullptr); while( g_NetworkManager.IsInSession() ) { @@ -988,7 +1013,7 @@ int CGameNetworkManager::ExitAndJoinFromInviteThreadProc( void* lpParam ) // Xbox should always be online when receiving invites - on PS3 we need to check & ask the user to sign in #if !defined(__PS3__) && !defined(__PSVITA__) - JoinFromInviteData *inviteData = (JoinFromInviteData *)lpParam; + JoinFromInviteData *inviteData = static_cast(lpParam); app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, lpParam); #else if(ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) @@ -1216,14 +1241,14 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) #endif // Null the network player of all the server players that are local, to stop them being removed from the server when removed from the session - if( pServer != NULL ) + if( pServer != nullptr ) { PlayerList *players = pServer->getPlayers(); for(auto& servPlayer : players->players) { if( servPlayer->connection->isLocal() && !servPlayer->connection->isGuest() ) { - servPlayer->connection->connection->getSocket()->setPlayer(NULL); + servPlayer->connection->connection->getSocket()->setPlayer(nullptr); } } } @@ -1259,7 +1284,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) char numLocalPlayers = 0; for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { - if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != NULL ) + if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != nullptr ) { numLocalPlayers++; localUsersMask |= GetLocalPlayerMask(index); @@ -1277,11 +1302,11 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) } // Restore the network player of all the server players that are local - if( pServer != NULL ) + if( pServer != nullptr ) { for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { - if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != NULL ) + if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != nullptr ) { PlayerUID localPlayerXuid = pMinecraft->localplayers[index]->getXuid(); @@ -1295,7 +1320,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) } // Player might have a pending connection - if (pMinecraft->m_pendingLocalConnections[index] != NULL) + if (pMinecraft->m_pendingLocalConnections[index] != nullptr) { // Update the network player pMinecraft->m_pendingLocalConnections[index]->getConnection()->getSocket()->setPlayer(g_NetworkManager.GetLocalPlayerByUserIndex(index)); @@ -1361,8 +1386,8 @@ void CGameNetworkManager::renderQueueMeter() #ifdef _XBOX int height = 720; - CGameNetworkManager::byteQueue[(CGameNetworkManager::messageQueuePos) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeBytes(NULL, false); - CGameNetworkManager::messageQueue[(CGameNetworkManager::messageQueuePos++) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeMessages(NULL, false); + CGameNetworkManager::byteQueue[(CGameNetworkManager::messageQueuePos) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeBytes(nullptr, false); + CGameNetworkManager::messageQueue[(CGameNetworkManager::messageQueuePos++) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeMessages(nullptr, false); Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->gui->renderGraph(CGameNetworkManager::messageQueue_length, CGameNetworkManager::messageQueuePos, CGameNetworkManager::messageQueue, 10, 1000, CGameNetworkManager::byteQueue, 100, 25000); @@ -1426,7 +1451,7 @@ void CGameNetworkManager::StateChange_AnyToStarting() { LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = NULL; + loadingParams->lpParam = nullptr; UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1447,7 +1472,7 @@ void CGameNetworkManager::StateChange_AnyToEnding(bool bStateWasPlaying) for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(i); - if(pNetworkPlayer != NULL && ProfileManager.IsSignedIn( i ) ) + if(pNetworkPlayer != nullptr && ProfileManager.IsSignedIn( i ) ) { app.DebugPrintf("Stats save for an offline game for the player at index %d\n", i ); Minecraft::GetInstance()->forceStatsSave(pNetworkPlayer->GetUserIndex()); @@ -1482,12 +1507,12 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc { Minecraft *pMinecraft = Minecraft::GetInstance(); - Socket *socket = NULL; + Socket *socket = nullptr; shared_ptr mpPlayer = nullptr; int userIdx = pNetworkPlayer->GetUserIndex(); if (userIdx >= 0 && userIdx < XUSER_MAX_COUNT) mpPlayer = pMinecraft->localplayers[userIdx]; - if( localPlayer && mpPlayer != NULL && mpPlayer->connection != NULL) + if( localPlayer && mpPlayer != nullptr && mpPlayer->connection != nullptr) { // If we already have a MultiplayerLocalPlayer here then we are doing a session type change socket = mpPlayer->connection->getSocket(); @@ -1501,6 +1526,45 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc } else { +#ifdef _WINDOWS64 + // Non-host split-screen: open a dedicated TCP connection for this pad + if (localPlayer && !g_NetworkManager.IsHost() && g_NetworkManager.IsInGameplay()) + { + int padIdx = pNetworkPlayer->GetUserIndex(); + BYTE assignedSmallId = 0; + + if (!WinsockNetLayer::JoinSplitScreen(padIdx, &assignedSmallId)) + { + app.DebugPrintf("Split-screen pad %d: failed to open TCP to host\n", padIdx); + pMinecraft->connectionDisconnected(padIdx, DisconnectPacket::eDisconnect_ConnectionCreationFailed); + return; + } + + // Update the local IQNetPlayer (at pad index) with the host-assigned smallId. + // The NetworkPlayerXbox created by NotifyPlayerJoined already points to + // m_player[padIdx], so we just set the smallId for network routing. + IQNet::m_player[padIdx].m_smallId = assignedSmallId; + IQNet::m_player[padIdx].m_resolvedXuid = Win64Xuid::DeriveXuidForPad(Win64Xuid::ResolvePersistentXuid(), padIdx); + + // Network socket (not hostLocal) — data goes through TCP via GetLocalSocket + socket = new Socket(pNetworkPlayer, false, false); + pNetworkPlayer->SetSocket(socket); + + ClientConnection* connection = new ClientConnection(pMinecraft, socket, padIdx); + if (connection->createdOk) + { + connection->send(shared_ptr(new PreLoginPacket(pNetworkPlayer->GetOnlineName()))); + pMinecraft->addPendingLocalConnection(padIdx, connection); + } + else + { + pMinecraft->connectionDisconnected(padIdx, DisconnectPacket::eDisconnect_ConnectionCreationFailed); + delete connection; + } + return; + } +#endif + socket = new Socket( pNetworkPlayer, g_NetworkManager.IsHost(), g_NetworkManager.IsHost() && localPlayer ); pNetworkPlayer->SetSocket( socket ); @@ -1523,14 +1587,14 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc if( connection->createdOk ) { - connection->send( shared_ptr( new PreLoginPacket( pNetworkPlayer->GetOnlineName() ) ) ); + connection->send(std::make_shared(pNetworkPlayer->GetOnlineName())); pMinecraft->addPendingLocalConnection(idx, connection); } else { pMinecraft->connectionDisconnected( idx , DisconnectPacket::eDisconnect_ConnectionCreationFailed ); delete connection; - connection = NULL; + connection = nullptr; } } } @@ -1540,10 +1604,10 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc void CGameNetworkManager::CloseConnection( INetworkPlayer *pNetworkPlayer ) { MinecraftServer *server = MinecraftServer::getInstance(); - if( server != NULL ) + if( server != nullptr ) { PlayerList *players = server->getPlayers(); - if( players != NULL ) + if( players != nullptr ) { players->closePlayerConnectionBySmallId(pNetworkPlayer->GetSmallId()); } @@ -1559,7 +1623,7 @@ void CGameNetworkManager::PlayerJoining( INetworkPlayer *pNetworkPlayer ) for (int iPad=0; iPadlocalplayers[idx] != NULL) + if(Minecraft::GetInstance()->localplayers[idx] != nullptr) { TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } @@ -1609,7 +1673,7 @@ void CGameNetworkManager::PlayerLeaving( INetworkPlayer *pNetworkPlayer ) { for(int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(Minecraft::GetInstance()->localplayers[idx] != NULL) + if(Minecraft::GetInstance()->localplayers[idx] != nullptr) { TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } @@ -1632,7 +1696,7 @@ void CGameNetworkManager::WriteStats( INetworkPlayer *pNetworkPlayer ) void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO *pInviteInfo) { #ifdef __ORBIS__ - if (m_pUpsell != NULL) + if (m_pUpsell != nullptr) { delete pInviteInfo; return; @@ -1721,7 +1785,7 @@ 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 ) + if(index==userIndex || pMinecraft->localplayers[index]!=nullptr ) { ++joiningUsers; if( !ProfileManager.AllowedToPlayMultiplayer(index) ) noPrivileges = true; @@ -1736,7 +1800,7 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * BOOL pccAllowed = TRUE; BOOL pccFriendsAllowed = TRUE; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(userIndex,false,&noUGC,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(userIndex,false,&noUGC,&bContentRestricted,nullptr); #else ProfileManager.AllowedPlayerCreatedContent(ProfileManager.GetPrimaryPad(),false,&pccAllowed,&pccFriendsAllowed); if(!pccAllowed && !pccFriendsAllowed) noUGC = true; @@ -1781,14 +1845,14 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * uiIDA[0]=IDS_CONFIRM_OK; // 4J-PB - it's possible there is no primary pad here, when accepting an invite from the dashboard - //StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + //StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); ui.RequestErrorMessage( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,XUSER_INDEX_ANY); } else { #if defined(__ORBIS__) || defined(__PSVITA__) bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); @@ -1984,7 +2048,7 @@ const char *CGameNetworkManager::GetOnlineName(int playerIdx) void CGameNetworkManager::ServerReadyCreate(bool create) { - m_hServerReadyEvent = ( create ? ( new C4JThread::Event ) : NULL ); + m_hServerReadyEvent = ( create ? ( new C4JThread::Event ) : nullptr ); } void CGameNetworkManager::ServerReady() @@ -2000,17 +2064,17 @@ void CGameNetworkManager::ServerReadyWait() void CGameNetworkManager::ServerReadyDestroy() { delete m_hServerReadyEvent; - m_hServerReadyEvent = NULL; + m_hServerReadyEvent = nullptr; } bool CGameNetworkManager::ServerReadyValid() { - return ( m_hServerReadyEvent != NULL ); + return ( m_hServerReadyEvent != nullptr ); } void CGameNetworkManager::ServerStoppedCreate(bool create) { - m_hServerStoppedEvent = ( create ? ( new C4JThread::Event ) : NULL ); + m_hServerStoppedEvent = ( create ? ( new C4JThread::Event ) : nullptr ); } void CGameNetworkManager::ServerStopped() @@ -2051,12 +2115,12 @@ void CGameNetworkManager::ServerStoppedWait() void CGameNetworkManager::ServerStoppedDestroy() { delete m_hServerStoppedEvent; - m_hServerStoppedEvent = NULL; + m_hServerStoppedEvent = nullptr; } bool CGameNetworkManager::ServerStoppedValid() { - return ( m_hServerStoppedEvent != NULL ); + return ( m_hServerStoppedEvent != nullptr ); } int CGameNetworkManager::GetJoiningReadyPercentage() diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.h b/Minecraft.Client/Common/Network/GameNetworkManager.h index 15c7f0b06..3357b3cdd 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.h +++ b/Minecraft.Client/Common/Network/GameNetworkManager.h @@ -108,7 +108,7 @@ public: static void CancelJoinGame(LPVOID lpParam); // Not part of the shared interface bool LeaveGame(bool bMigrateHost); static int JoinFromInvite_SignInReturned(void *pParam,bool bContinue, int iPad); - void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr); void SendInviteGUI(int iPad); void ResetLeavingGame(); @@ -137,17 +137,17 @@ public: // Events - void ServerReadyCreate(bool create); // Create the signal (or set to NULL) + void ServerReadyCreate(bool create); // Create the signal (or set to nullptr) void ServerReady(); // Signal that we are ready void ServerReadyWait(); // Wait for the signal void ServerReadyDestroy(); // Destroy signal - bool ServerReadyValid(); // Is non-NULL + bool ServerReadyValid(); // Is non-nullptr void ServerStoppedCreate(bool create); // Create the signal void ServerStopped(); // Signal that we are ready - void ServerStoppedWait(); // Wait for the signal - void ServerStoppedDestroy(); // Destroy signal - bool ServerStoppedValid(); // Is non-NULL + void ServerStoppedWait(); // Wait for the signal + void ServerStoppedDestroy(); // Destroy signal + bool ServerStoppedValid(); // Is non-nullptr #ifdef __PSVITA__ static bool usingAdhocMode(); diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h index 31c415a75..3ed0f888f 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h @@ -93,7 +93,7 @@ private: public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL) = 0; + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr) = 0; private: virtual bool RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ) = 0; diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp index 44ca3c2f9..1e625098b 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp @@ -26,7 +26,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) bool createFakeSocket = false; bool localPlayer = false; - NetworkPlayerXbox *networkPlayer = (NetworkPlayerXbox *)addNetworkPlayer(pQNetPlayer); + NetworkPlayerXbox *networkPlayer = static_cast(addNetworkPlayer(pQNetPlayer)); if( pQNetPlayer->IsLocal() ) { @@ -90,8 +90,8 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) pQNetPlayer, pQNetPlayer->GetGamertag(), pszDescription, - (int) pQNetPlayer->HasVoice(), - (int) pQNetPlayer->HasCamera() ); + pQNetPlayer->HasVoice(), + pQNetPlayer->HasCamera() ); if( m_pIQNet->IsHost() ) @@ -103,7 +103,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); } @@ -112,7 +112,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -127,11 +127,11 @@ void CPlatformNetworkManagerStub::NotifyPlayerLeaving(IQNetPlayer* pQNetPlayer) app.DebugPrintf("Player 0x%p \"%ls\" leaving.\n", pQNetPlayer, pQNetPlayer->GetGamertag()); INetworkPlayer* networkPlayer = getNetworkPlayer(pQNetPlayer); - if (networkPlayer == NULL) + if (networkPlayer == nullptr) return; Socket* socket = networkPlayer->GetSocket(); - if (socket != NULL) + if (socket != nullptr) { if (m_pIQNet->IsHost()) g_NetworkManager.CloseConnection(networkPlayer); @@ -146,7 +146,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerLeaving(IQNetPlayer* pQNetPlayer) for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if (playerChangedCallback[idx] != NULL) + if (playerChangedCallback[idx] != nullptr) playerChangedCallback[idx](playerChangedCallbackParam[idx], networkPlayer, true); } @@ -162,7 +162,7 @@ bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkMa g_pPlatformNetworkManager = this; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - playerChangedCallback[ i ] = NULL; + playerChangedCallback[ i ] = nullptr; } m_bLeavingGame = false; @@ -173,8 +173,8 @@ bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkMa m_bSearchPending = false; m_bIsOfflineGame = false; - m_pSearchParam = NULL; - m_SessionsUpdatedCallback = NULL; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { @@ -182,10 +182,10 @@ bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkMa m_lastSearchStartTime[i] = 0; // The results that will be filled in with the current search - m_pSearchResults[i] = NULL; - m_pQoSResult[i] = NULL; - m_pCurrentSearchResults[i] = NULL; - m_pCurrentQoSResult[i] = NULL; + m_pSearchResults[i] = nullptr; + m_pQoSResult[i] = nullptr; + m_pCurrentSearchResults[i] = nullptr; + m_pCurrentQoSResult[i] = nullptr; m_currentSearchResultsCount[i] = 0; } @@ -231,7 +231,7 @@ void CPlatformNetworkManagerStub::DoWork() while (WinsockNetLayer::PopDisconnectedSmallId(&disconnectedSmallId)) { IQNetPlayer* qnetPlayer = m_pIQNet->GetPlayerBySmallId(disconnectedSmallId); - if (qnetPlayer != NULL && qnetPlayer->m_smallId == disconnectedSmallId) + if (qnetPlayer != nullptr && qnetPlayer->m_smallId == disconnectedSmallId) { NotifyPlayerLeaving(qnetPlayer); qnetPlayer->m_smallId = 0; @@ -240,15 +240,46 @@ void CPlatformNetworkManagerStub::DoWork() qnetPlayer->m_resolvedXuid = INVALID_XUID; qnetPlayer->m_gamertag[0] = 0; qnetPlayer->SetCustomDataValue(0); - if (IQNet::s_playerCount > 1) + // Recalculate s_playerCount as the highest active slot + 1. + // A blind decrement would hide players at higher-indexed slots when a + // lower-indexed player disconnects first: GetPlayerBySmallId scans + // [0, s_playerCount) so any slot at or above the decremented count + // becomes invisible, causing its disconnect to be missed (ghost player). + while (IQNet::s_playerCount > 1 && + IQNet::m_player[IQNet::s_playerCount - 1].GetCustomDataValue() == 0) IQNet::s_playerCount--; } - // Always return smallId to the free pool so it can be reused (game may have already cleared the slot). - WinsockNetLayer::PushFreeSmallId(disconnectedSmallId); - // Clear O(1) socket lookup so GetSocketForSmallId stays fast (s_connections never shrinks). - WinsockNetLayer::ClearSocketForSmallId(disconnectedSmallId); + // NOTE: Do NOT call PushFreeSmallId here. The old PlayerConnection's + // write thread may still be alive (it dies in PlayerList::tick when + // m_smallIdsToClose is processed). If we recycle the smallId now, + // AcceptThread can reuse it for a new connection, and the old write + // thread's getPlayer() lookup will resolve to the NEW player, sending + // stale game packets to the new client's TCP socket — corrupting its + // login handshake (bad packet id crash). PushFreeSmallId and + // ClearSocketForSmallId are called from PlayerList::tick after the + // old Connection threads are dead. + // // Clear chunk visibility flags for this system so rejoin gets fresh chunk state. - SystemFlagRemoveBySmallId((int)disconnectedSmallId); + SystemFlagRemoveBySmallId(disconnectedSmallId); + } + } + + // Client-side host disconnect detection: + // if TCP is gone, propagate through normal network-disconnect flow so UI returns to menus. + // The processing from the Xbox version will be reused. + if (_iQNetStubState == QNET_STATE_GAME_PLAY && !m_pIQNet->IsHost() && !m_bLeavingGame) + { + if (!WinsockNetLayer::IsConnected()) + { + if (!m_bLeaveGameOnTick) + { + m_bLeaveGameOnTick = true; + g_NetworkManager.HandleDisconnect(false); + } + } + else + { + m_bLeaveGameOnTick = false; } } #endif @@ -261,7 +292,7 @@ bool CPlatformNetworkManagerStub::CanAcceptMoreConnections() if (server == NULL) return true; PlayerList* list = server->getPlayerList(); if (list == NULL) return true; - return (unsigned int)list->players.size() < (unsigned int)list->getMaxPlayers(); + return static_cast(list->players.size()) < static_cast(list->getMaxPlayers()); #else return true; #endif @@ -289,12 +320,40 @@ int CPlatformNetworkManagerStub::GetLocalPlayerMask(int playerIndex) bool CPlatformNetworkManagerStub::AddLocalPlayerByUserIndex( int userIndex ) { - NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); - return ( m_pIQNet->AddLocalPlayerByUserIndex(userIndex) == S_OK ); + if ( m_pIQNet->AddLocalPlayerByUserIndex(userIndex) != S_OK ) + return false; + // Player is now registered in IQNet — get a pointer and notify the network layer. + // Use the static array directly: GetLocalPlayerByUserIndex checks customData which + // isn't set until addNetworkPlayer runs inside NotifyPlayerJoined. + NotifyPlayerJoined(&IQNet::m_player[userIndex]); + return true; } bool CPlatformNetworkManagerStub::RemoveLocalPlayerByUserIndex( int userIndex ) { +#ifdef _WINDOWS64 + if (userIndex > 0 && userIndex < XUSER_MAX_COUNT && !m_pIQNet->IsHost()) + { + IQNetPlayer* qp = &IQNet::m_player[userIndex]; + + // Notify the network layer before clearing the slot + if (qp->GetCustomDataValue() != 0) + { + NotifyPlayerLeaving(qp); + } + + // Close the split-screen TCP connection and reset WinsockNetLayer state + WinsockNetLayer::CloseSplitScreenConnection(userIndex); + + // Clear the IQNet slot so it can be reused on rejoin + qp->m_smallId = 0; + qp->m_isRemote = false; + qp->m_isHostPlayer = false; + qp->m_resolvedXuid = INVALID_XUID; + qp->m_gamertag[0] = 0; + qp->SetCustomDataValue(0); + } +#endif return true; } @@ -322,6 +381,7 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) if( m_bLeavingGame ) return true; m_bLeavingGame = true; + m_bLeaveGameOnTick = false; #ifdef _WINDOWS64 WinsockNetLayer::StopAdvertising(); @@ -370,6 +430,7 @@ void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame, localUsersMask |= GetLocalPlayerMask( g_NetworkManager.GetPrimaryPad() ); m_bLeavingGame = false; + m_bLeaveGameOnTick = false; m_pIQNet->HostGame(); @@ -386,7 +447,7 @@ void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame, #ifdef _WINDOWS64 int port = WIN64_NET_DEFAULT_PORT; - const char* bindIp = NULL; + const char* bindIp = nullptr; if (g_Win64DedicatedServer) { if (g_Win64DedicatedServerPort > 0) @@ -399,9 +460,23 @@ void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame, if (WinsockNetLayer::IsActive()) { - const wchar_t* hostName = IQNet::m_player[0].m_gamertag; - unsigned int settings = app.GetGameHostOption(eGameHostOption_All); - WinsockNetLayer::StartAdvertising(port, hostName, settings, 0, 0, MINECRAFT_NET_VERSION); + // For Dedicated Server, refer to `lan-advertise` in `server.properties` + bool enableLanAdvertising = true; + if (g_Win64DedicatedServer) + { + enableLanAdvertising = g_Win64DedicatedServerLanAdvertise; + } + + if (enableLanAdvertising) + { + const wchar_t* hostName = IQNet::m_player[0].m_gamertag; + unsigned int settings = app.GetGameHostOption(eGameHostOption_All); + WinsockNetLayer::StartAdvertising(port, hostName, settings, 0, 0, MINECRAFT_NET_VERSION); + } + else + { + WinsockNetLayer::StopAdvertising(); + } } #endif //#endif @@ -419,7 +494,7 @@ bool CPlatformNetworkManagerStub::_StartGame() int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo* searchResult, int localUsersMask, int primaryUserIndex) { #ifdef _WINDOWS64 - if (searchResult == NULL) + if (searchResult == nullptr) return CGameNetworkManager::JOINGAME_FAIL_GENERAL; const char* hostIP = searchResult->data.hostIP; @@ -429,6 +504,7 @@ int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo* searchResult, int l return CGameNetworkManager::JOINGAME_FAIL_GENERAL; m_bLeavingGame = false; + m_bLeaveGameOnTick = false; IQNet::s_isHosting = false; m_pIQNet->ClientJoinGame(); @@ -493,8 +569,8 @@ void CPlatformNetworkManagerStub::UnRegisterPlayerChangedCallback(int iPad, void { if(playerChangedCallbackParam[iPad] == callbackParam) { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; + playerChangedCallback[iPad] = nullptr; + playerChangedCallbackParam[iPad] = nullptr; } } @@ -514,7 +590,7 @@ bool CPlatformNetworkManagerStub::_RunNetworkGame() if (IQNet::m_player[i].m_isRemote) { INetworkPlayer* pNetworkPlayer = getNetworkPlayer(&IQNet::m_player[i]); - if (pNetworkPlayer != NULL && pNetworkPlayer->GetSocket() != NULL) + if (pNetworkPlayer != nullptr && pNetworkPlayer->GetSocket() != nullptr) { Socket::addIncomingSocket(pNetworkPlayer->GetSocket()); } @@ -524,14 +600,14 @@ bool CPlatformNetworkManagerStub::_RunNetworkGame() return true; } -void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) +void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= nullptr*/) { // DWORD playerCount = m_pIQNet->GetPlayerCount(); // // if( this->m_bLeavingGame ) // return; // -// if( GetHostPlayer() == NULL ) +// if( GetHostPlayer() == nullptr ) // return; // // for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) @@ -551,13 +627,13 @@ void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pN // } // else // { -// m_hostGameSessionData.players[i] = NULL; +// m_hostGameSessionData.players[i] = nullptr; // memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); // } // } // else // { -// m_hostGameSessionData.players[i] = NULL; +// m_hostGameSessionData.players[i] = nullptr; // memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); // } // } @@ -568,18 +644,18 @@ void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pN int CPlatformNetworkManagerStub::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) { - INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; + INetworkPlayer *pNetworkPlayer = static_cast(lpParam); Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); socket->m_socketClosedEvent->WaitForSignal(INFINITE); //printf("Socket closed event has fired\n"); // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); + pNetworkPlayer->SetSocket( nullptr ); delete socket; } @@ -601,7 +677,7 @@ CPlatformNetworkManagerStub::PlayerFlags::PlayerFlags(INetworkPlayer *pNetworkPl this->flags = new unsigned char [ count / 8 ]; memset( this->flags, 0, count / 8 ); this->count = count; - this->m_smallId = (pNetworkPlayer && pNetworkPlayer->IsLocal()) ? 256 : (pNetworkPlayer ? (int)pNetworkPlayer->GetSmallId() : -1); + this->m_smallId = (pNetworkPlayer && pNetworkPlayer->IsLocal()) ? 256 : (pNetworkPlayer ? static_cast(pNetworkPlayer->GetSmallId()) : -1); } CPlatformNetworkManagerStub::PlayerFlags::~PlayerFlags() { @@ -669,7 +745,7 @@ void CPlatformNetworkManagerStub::SystemFlagReset() void CPlatformNetworkManagerStub::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; + if( pNetworkPlayer == nullptr ) return; for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) { @@ -685,7 +761,7 @@ void CPlatformNetworkManagerStub::SystemFlagSet(INetworkPlayer *pNetworkPlayer, bool CPlatformNetworkManagerStub::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) + if( pNetworkPlayer == nullptr ) { return false; } @@ -713,7 +789,7 @@ wstring CPlatformNetworkManagerStub::GatherRTTStats() for(unsigned int i = 0; i < GetPlayerCount(); ++i) { - IQNetPlayer *pQNetPlayer = ((NetworkPlayerXbox *)GetPlayerByIndex( i ))->GetQNetPlayer(); + IQNetPlayer *pQNetPlayer = static_cast(GetPlayerByIndex(i))->GetQNetPlayer(); if(!pQNetPlayer->IsLocal()) { @@ -728,7 +804,7 @@ wstring CPlatformNetworkManagerStub::GatherRTTStats() void CPlatformNetworkManagerStub::TickSearch() { #ifdef _WINDOWS64 - if (m_SessionsUpdatedCallback == NULL) + if (m_SessionsUpdatedCallback == nullptr) return; static DWORD lastSearchTime = 0; @@ -757,7 +833,7 @@ void CPlatformNetworkManagerStub::SearchForGames() size_t nameLen = wcslen(lanSessions[i].hostName); info->displayLabel = new wchar_t[nameLen + 1]; wcscpy_s(info->displayLabel, nameLen + 1, lanSessions[i].hostName); - info->displayLabelLength = (unsigned char)nameLen; + info->displayLabelLength = static_cast(nameLen); info->displayLabelViewableStartIndex = 0; info->data.netVersion = lanSessions[i].netVersion; @@ -772,14 +848,13 @@ void CPlatformNetworkManagerStub::SearchForGames() info->data.playerCount = lanSessions[i].playerCount; info->data.maxPlayers = lanSessions[i].maxPlayers; - info->sessionId = (SessionID)((uint64_t)inet_addr(lanSessions[i].hostIP) | ((uint64_t)lanSessions[i].hostPort << 32)); + info->sessionId = static_cast(inet_addr(lanSessions[i].hostIP)) | + static_cast(lanSessions[i].hostPort) << 32; friendsSessions[0].push_back(info); } - std::FILE* file = std::fopen("servers.db", "rb"); - - if (file) { + if (std::FILE* file = std::fopen("servers.db", "rb")) { char magic[4] = {}; if (std::fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) { @@ -797,7 +872,6 @@ void CPlatformNetworkManagerStub::SearchForGames() char ipBuf[257] = {}; if (std::fread(ipBuf, 1, ipLen, file) != ipLen) break; - if (std::fread(&port, sizeof(uint16_t), 1, file) != 1) break; if (std::fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; @@ -815,13 +889,13 @@ void CPlatformNetworkManagerStub::SearchForGames() size_t nLen = wName.length(); info->displayLabel = new wchar_t[nLen + 1]; wcscpy_s(info->displayLabel, nLen + 1, wName.c_str()); - info->displayLabelLength = (unsigned char)nLen; + info->displayLabelLength = static_cast(nLen); info->displayLabelViewableStartIndex = 0; info->data.isReadyToJoin = true; info->data.isJoinable = true; strncpy_s(info->data.hostIP, sizeof(info->data.hostIP), ipBuf, _TRUNCATE); info->data.hostPort = port; - info->sessionId = (SessionID)(static_cast(inet_addr(ipBuf)) | (static_cast(port) << 32)); + info->sessionId = static_cast(inet_addr(ipBuf)) | static_cast(port) << 32; friendsSessions[0].push_back(info); } } @@ -829,9 +903,9 @@ void CPlatformNetworkManagerStub::SearchForGames() std::fclose(file); } - m_searchResultsCount[0] = (int)friendsSessions[0].size(); + m_searchResultsCount[0] = static_cast(friendsSessions[0].size()); - if (m_SessionsUpdatedCallback != NULL) + if (m_SessionsUpdatedCallback != nullptr) m_SessionsUpdatedCallback(m_pSearchParam); #endif } @@ -879,7 +953,7 @@ void CPlatformNetworkManagerStub::ForceFriendsSessionRefresh() m_searchResultsCount[i] = 0; m_lastSearchStartTime[i] = 0; delete m_pSearchResults[i]; - m_pSearchResults[i] = NULL; + m_pSearchResults[i] = nullptr; } } @@ -906,7 +980,7 @@ void CPlatformNetworkManagerStub::removeNetworkPlayer(IQNetPlayer *pQNetPlayer) INetworkPlayer *CPlatformNetworkManagerStub::getNetworkPlayer(IQNetPlayer *pQNetPlayer) { - return pQNetPlayer ? (INetworkPlayer *)(pQNetPlayer->GetCustomDataValue()) : NULL; + return pQNetPlayer ? (INetworkPlayer *)(pQNetPlayer->GetCustomDataValue()) : nullptr; } diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h index 261639f2a..4a3f4068d 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h @@ -81,7 +81,7 @@ private: GameSessionData m_hostGameSessionData; CGameNetworkManager *m_pGameNetworkManager; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr); private: // TODO 4J Stu - Do we need to be able to have more than one of these? diff --git a/Minecraft.Client/Common/Network/SessionInfo.h b/Minecraft.Client/Common/Network/SessionInfo.h index 7b3629fff..4e091c871 100644 --- a/Minecraft.Client/Common/Network/SessionInfo.h +++ b/Minecraft.Client/Common/Network/SessionInfo.h @@ -113,7 +113,7 @@ public: FriendSessionInfo() { - displayLabel = NULL; + displayLabel = nullptr; displayLabelLength = 0; displayLabelViewableStartIndex = 0; hasPartyMember = false; @@ -148,7 +148,7 @@ public: ~FriendSessionInfo() { - if (displayLabel != NULL) + if (displayLabel != nullptr) delete[] displayLabel; } }; diff --git a/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp index 21cd82aad..a1cc40382 100644 --- a/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp +++ b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp @@ -4,7 +4,7 @@ NetworkPlayerSony::NetworkPlayerSony(SQRNetworkPlayer *qnetPlayer) { m_sqrPlayer = qnetPlayer; - m_pSocket = NULL; + m_pSocket = nullptr; m_lastChunkPacketTime = 0; } @@ -16,12 +16,12 @@ unsigned char NetworkPlayerSony::GetSmallId() void NetworkPlayerSony::SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority, bool ack) { // TODO - handle priority - m_sqrPlayer->SendData( ((NetworkPlayerSony *)player)->m_sqrPlayer, pvData, dataSize, ack ); + m_sqrPlayer->SendData( static_cast(player)->m_sqrPlayer, pvData, dataSize, ack ); } bool NetworkPlayerSony::IsSameSystem(INetworkPlayer *player) { - return m_sqrPlayer->IsSameSystem(((NetworkPlayerSony *)player)->m_sqrPlayer); + return m_sqrPlayer->IsSameSystem(static_cast(player)->m_sqrPlayer); } int NetworkPlayerSony::GetOutstandingAckCount() @@ -133,5 +133,5 @@ int NetworkPlayerSony::GetTimeSinceLastChunkPacket_ms() } int64_t currentTime = System::currentTimeMillis(); - return (int)( currentTime - m_lastChunkPacketTime ); + return static_cast(currentTime - m_lastChunkPacketTime); } diff --git a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp index a9799d265..107101f4a 100644 --- a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp +++ b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp @@ -123,7 +123,7 @@ void CPlatformNetworkManagerSony::HandleDataReceived(SQRNetworkPlayer *playerFro INetworkPlayer *pPlayerFrom = getNetworkPlayer(playerFrom); Socket *socket = pPlayerFrom->GetSocket(); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(data, dataSize, false); } else @@ -132,7 +132,7 @@ void CPlatformNetworkManagerSony::HandleDataReceived(SQRNetworkPlayer *playerFro INetworkPlayer *pPlayerTo = getNetworkPlayer(playerTo); Socket *socket = pPlayerTo->GetSocket(); //app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", apPlayersTo[dwPlayer]->GetGamertag()); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(data, dataSize); } } @@ -226,7 +226,7 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); } @@ -235,7 +235,7 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -258,7 +258,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay { // Get our wrapper object associated with this player. Socket *socket = networkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { // If we are in game then remove this player from the game as well. // We may get here either from the player requesting to exit the game, @@ -274,19 +274,19 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay // We need this as long as the game server still needs to communicate with the player //delete socket; - networkPlayer->SetSocket( NULL ); + networkPlayer->SetSocket( nullptr ); } if( m_pSQRNet->IsHost() && !m_bHostChanged ) { if( isSystemPrimaryPlayer(pSQRPlayer) ) { - SQRNetworkPlayer *pNewSQRPrimaryPlayer = NULL; + SQRNetworkPlayer *pNewSQRPrimaryPlayer = nullptr; for(unsigned int i = 0; i < m_pSQRNet->GetPlayerCount(); ++i ) { SQRNetworkPlayer *pSQRPlayer2 = m_pSQRNet->GetPlayerByIndex( i ); - if ( pSQRPlayer2 != NULL && pSQRPlayer2 != pSQRPlayer && pSQRPlayer2->IsSameSystem( pSQRPlayer ) ) + if ( pSQRPlayer2 != nullptr && pSQRPlayer2 != pSQRPlayer && pSQRPlayer2->IsSameSystem( pSQRPlayer ) ) { pNewSQRPrimaryPlayer = pSQRPlayer2; break; @@ -298,7 +298,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay m_machineSQRPrimaryPlayers.erase( it ); } - if( pNewSQRPrimaryPlayer != NULL ) + if( pNewSQRPrimaryPlayer != nullptr ) m_machineSQRPrimaryPlayers.push_back( pNewSQRPrimaryPlayer ); } @@ -311,7 +311,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, true ); } @@ -320,7 +320,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -391,7 +391,7 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa if(ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) { // we're signed into the PSN, but we won't be online yet, force a sign-in online here - m_pSQRNet_Vita->AttemptPSNSignIn(NULL, NULL); + m_pSQRNet_Vita->AttemptPSNSignIn(nullptr, nullptr); } @@ -402,7 +402,7 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa g_pPlatformNetworkManager = this; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - playerChangedCallback[ i ] = NULL; + playerChangedCallback[ i ] = nullptr; } m_bLeavingGame = false; @@ -413,11 +413,11 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa m_bSearchPending = false; m_bIsOfflineGame = false; - m_pSearchParam = NULL; - m_SessionsUpdatedCallback = NULL; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; m_searchResultsCount = 0; - m_pSearchResults = NULL; + m_pSearchResults = nullptr; m_lastSearchStartTime = 0; @@ -622,11 +622,11 @@ bool CPlatformNetworkManagerSony::RemoveLocalPlayerByUserIndex( int userIndex ) SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(userIndex); INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - if(pNetworkPlayer != NULL) + if(pNetworkPlayer != nullptr) { Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { // We can't remove the player from qnet until we have stopped using it to communicate C4JThread* thread = new C4JThread(&CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc, pNetworkPlayer, "RemovePlayerOnSocketClosed"); @@ -702,11 +702,11 @@ bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - if(pNetworkPlayer != NULL) + if(pNetworkPlayer != nullptr) { Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); DWORD result = socket->m_socketClosedEvent->WaitForSignal(INFINITE); @@ -718,13 +718,13 @@ bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) // 4J Stu - Clear our reference to this socket pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - pNetworkPlayer->SetSocket( NULL ); + pNetworkPlayer->SetSocket( nullptr ); } delete socket; } else { - //printf("Socket is already NULL\n"); + //printf("Socket is already nullptr\n"); } } @@ -878,8 +878,8 @@ void CPlatformNetworkManagerSony::UnRegisterPlayerChangedCallback(int iPad, void { if(playerChangedCallbackParam[iPad] == callbackParam) { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; + playerChangedCallback[iPad] = nullptr; + playerChangedCallbackParam[iPad] = nullptr; } } @@ -917,7 +917,7 @@ bool CPlatformNetworkManagerSony::_RunNetworkGame() // Note that this does less than the xbox equivalent as we have HandleResyncPlayerRequest that is called by the underlying SQRNetworkManager when players are added/removed etc., so this // call is only used to update the game host settings & then do the final push out of the data. -void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) +void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= nullptr*/) { if( this->m_bLeavingGame ) return; @@ -934,7 +934,7 @@ void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pN // If this is called With a pNetworkPlayerLeaving, then the call has ultimately started within SQRNetworkManager::RemoveRemotePlayersAndSync, so we don't need to sync each change // as that function does a sync at the end of all changes. - if( pNetworkPlayerLeaving == NULL ) + if( pNetworkPlayerLeaving == nullptr ) { m_pSQRNet->UpdateExternalRoomData(); } @@ -946,14 +946,14 @@ int CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc( void* lpP Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); socket->m_socketClosedEvent->WaitForSignal(INFINITE); //printf("Socket closed event has fired\n"); // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); + pNetworkPlayer->SetSocket( nullptr ); delete socket; } @@ -1030,7 +1030,7 @@ void CPlatformNetworkManagerSony::SystemFlagReset() void CPlatformNetworkManagerSony::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; + if( pNetworkPlayer == nullptr ) return; for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) { @@ -1046,7 +1046,7 @@ void CPlatformNetworkManagerSony::SystemFlagSet(INetworkPlayer *pNetworkPlayer, bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) + if( pNetworkPlayer == nullptr ) { return false; } @@ -1064,8 +1064,8 @@ bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer *pNetworkPlayer, wstring CPlatformNetworkManagerSony::GatherStats() { #if 0 - 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 ) ); + return L"Queue messages: " + std::to_wstring(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( nullptr, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + + L" Queue bytes: " + std::to_wstring( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( nullptr, QNET_GETSENDQUEUESIZE_BYTES ) ); #else return L""; #endif @@ -1111,7 +1111,7 @@ void CPlatformNetworkManagerSony::TickSearch() } m_bSearchPending = false; - if( m_SessionsUpdatedCallback != NULL ) m_SessionsUpdatedCallback(m_pSearchParam); + if( m_SessionsUpdatedCallback != nullptr ) m_SessionsUpdatedCallback(m_pSearchParam); } } else @@ -1126,7 +1126,7 @@ void CPlatformNetworkManagerSony::TickSearch() if( usingAdhocMode()) searchDelay = 5000; #endif - if( m_SessionsUpdatedCallback != NULL && (m_lastSearchStartTime + searchDelay) < GetTickCount() ) + if( m_SessionsUpdatedCallback != nullptr && (m_lastSearchStartTime + searchDelay) < GetTickCount() ) { if( m_pSQRNet->FriendRoomManagerSearch() ) { @@ -1189,7 +1189,7 @@ bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID session if(memcmp( &pSearchResult->info.sessionID, &sessionId, sizeof(SessionID) ) != 0) continue; bool foundSession = false; - FriendSessionInfo *sessionInfo = NULL; + FriendSessionInfo *sessionInfo = nullptr; auto itFriendSession = friendsSessions[iPad].begin(); for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) { @@ -1231,7 +1231,7 @@ bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID session sessionInfo->data.isJoinable) { foundSessionInfo->data = sessionInfo->data; - if(foundSessionInfo->displayLabel != NULL) delete [] foundSessionInfo->displayLabel; + if(foundSessionInfo->displayLabel != nullptr) delete [] foundSessionInfo->displayLabel; foundSessionInfo->displayLabel = new wchar_t[100]; memcpy(foundSessionInfo->displayLabel, sessionInfo->displayLabel, 100 * sizeof(wchar_t) ); foundSessionInfo->displayLabelLength = sessionInfo->displayLabelLength; @@ -1267,7 +1267,7 @@ void CPlatformNetworkManagerSony::ForceFriendsSessionRefresh() m_lastSearchStartTime = 0; m_searchResultsCount = 0; delete m_pSearchResults; - m_pSearchResults = NULL; + m_pSearchResults = nullptr; } INetworkPlayer *CPlatformNetworkManagerSony::addNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) @@ -1293,7 +1293,7 @@ void CPlatformNetworkManagerSony::removeNetworkPlayer(SQRNetworkPlayer *pSQRPlay INetworkPlayer *CPlatformNetworkManagerSony::getNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) { - return pSQRPlayer ? (INetworkPlayer *)(pSQRPlayer->GetCustomDataValue()) : NULL; + return pSQRPlayer ? (INetworkPlayer *)(pSQRPlayer->GetCustomDataValue()) : nullptr; } diff --git a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h index 258acd833..9131e8979 100644 --- a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h +++ b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h @@ -102,7 +102,7 @@ private: GameSessionData m_hostGameSessionData; CGameNetworkManager *m_pGameNetworkManager; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr); private: // TODO 4J Stu - Do we need to be able to have more than one of these? diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp index f23a0a630..7561c17d4 100644 --- a/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp @@ -16,7 +16,7 @@ int SQRNetworkManager::GetSendQueueSizeBytes() for(int i = 0; i < playerCount; ++i) { SQRNetworkPlayer *player = GetPlayerByIndex( i ); - if( player != NULL ) + if( player != nullptr ) { queueSize += player->GetTotalSendQueueBytes(); } @@ -31,7 +31,7 @@ int SQRNetworkManager::GetSendQueueSizeMessages() for(int i = 0; i < playerCount; ++i) { SQRNetworkPlayer *player = GetPlayerByIndex( i ); - if( player != NULL ) + if( player != nullptr ) { queueSize += player->GetTotalSendQueueMessages(); } diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp index 79c9835b8..4ed27824e 100644 --- a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp @@ -279,12 +279,12 @@ void SQRNetworkPlayer::SendInternal(const void *data, unsigned int dataSize, Ack { // no data, just the flag assert(dataSize == 0); - assert(data == NULL); + assert(data == nullptr); int dataSize = dataRemaining; if( dataSize > SNP_MAX_PAYLOAD ) dataSize = SNP_MAX_PAYLOAD; - sendBlock.start = NULL; - sendBlock.end = NULL; - sendBlock.current = NULL; + sendBlock.start = nullptr; + sendBlock.end = nullptr; + sendBlock.current = nullptr; sendBlock.ack = ackFlags; m_sendQueue.push(sendBlock); } @@ -387,9 +387,9 @@ int SQRNetworkPlayer::ReadDataPacket(void* data, int dataSize) unsigned char* packetData = new unsigned char[packetSize]; #ifdef __PS3__ - int bytesRead = cellRudpRead( m_rudpCtx, packetData, packetSize, 0, NULL ); + int bytesRead = cellRudpRead( m_rudpCtx, packetData, packetSize, 0, nullptr ); #else // __ORBIS__ && __PSVITA__ - int bytesRead = sceRudpRead( m_rudpCtx, packetData, packetSize, 0, NULL ); + int bytesRead = sceRudpRead( m_rudpCtx, packetData, packetSize, 0, nullptr ); #endif if(bytesRead == sc_wouldBlockFlag) { @@ -426,9 +426,9 @@ void SQRNetworkPlayer::ReadAck() { DataPacketHeader header; #ifdef __PS3__ - int bytesRead = cellRudpRead( m_rudpCtx, &header, sizeof(header), 0, NULL ); + int bytesRead = cellRudpRead( m_rudpCtx, &header, sizeof(header), 0, nullptr ); #else // __ORBIS__ && __PSVITA__ - int bytesRead = sceRudpRead( m_rudpCtx, &header, sizeof(header), 0, NULL ); + int bytesRead = sceRudpRead( m_rudpCtx, &header, sizeof(header), 0, nullptr ); #endif if(bytesRead == sc_wouldBlockFlag) { @@ -459,7 +459,7 @@ void SQRNetworkPlayer::ReadAck() void SQRNetworkPlayer::WriteAck() { - SendInternal(NULL, 0, e_flag_AckReturning); + SendInternal(nullptr, 0, e_flag_AckReturning); } int SQRNetworkPlayer::GetOutstandingAckCount() diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h index a72e5a41b..c67069d17 100644 --- a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h @@ -63,7 +63,7 @@ class SQRNetworkPlayer public: DataPacketHeader() : m_dataSize(0), m_ackFlags(e_flag_AckUnknown) {} DataPacketHeader(int dataSize, AckFlags ackFlags) : m_dataSize(dataSize), m_ackFlags(ackFlags) { } - AckFlags GetAckFlags() { return (AckFlags)m_ackFlags;} + AckFlags GetAckFlags() { return static_cast(m_ackFlags);} int GetDataSize() { return m_dataSize; } }; diff --git a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp index 02fc73cf6..47beb63c9 100644 --- a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp +++ b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp @@ -29,8 +29,8 @@ static SceRemoteStorageStatus statParams; // void remoteStorageCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) // { // app.DebugPrintf("remoteStorageCallback err : 0x%08x\n"); -// -// app.getRemoteStorage()->getRemoteFileInfo(&statParams, remoteStorageGetInfoCallback, NULL); +// +// app.getRemoteStorage()->getRemoteFileInfo(&statParams, remoteStorageGetInfoCallback, nullptr); // } @@ -39,13 +39,13 @@ static SceRemoteStorageStatus statParams; void SonyRemoteStorage::SetRetrievedDescData() { DescriptionData* pDescDataTest = (DescriptionData*)m_remoteFileInfo->fileDescription; - ESavePlatform testPlatform = (ESavePlatform)MAKE_FOURCC(pDescDataTest->m_platform[0], pDescDataTest->m_platform[1], pDescDataTest->m_platform[2], pDescDataTest->m_platform[3]); + ESavePlatform testPlatform = static_cast(MAKE_FOURCC(pDescDataTest->m_platform[0], pDescDataTest->m_platform[1], pDescDataTest->m_platform[2], pDescDataTest->m_platform[3])); if(testPlatform == SAVE_FILE_PLATFORM_NONE) { // new version of the descData DescriptionData_V2* pDescData2 = (DescriptionData_V2*)m_remoteFileInfo->fileDescription; m_retrievedDescData.m_descDataVersion = GetU32FromHexBytes(pDescData2->m_descDataVersion); - m_retrievedDescData.m_savePlatform = (ESavePlatform)MAKE_FOURCC(pDescData2->m_platform[0], pDescData2->m_platform[1], pDescData2->m_platform[2], pDescData2->m_platform[3]); + m_retrievedDescData.m_savePlatform = static_cast(MAKE_FOURCC(pDescData2->m_platform[0], pDescData2->m_platform[1], pDescData2->m_platform[2], pDescData2->m_platform[3])); m_retrievedDescData.m_seed = GetU64FromHexBytes(pDescData2->m_seed); m_retrievedDescData.m_hostOptions = GetU32FromHexBytes(pDescData2->m_hostOptions); m_retrievedDescData.m_texturePack = GetU32FromHexBytes(pDescData2->m_texturePack); @@ -58,7 +58,7 @@ void SonyRemoteStorage::SetRetrievedDescData() // old version,copy the data across to the new version DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; m_retrievedDescData.m_descDataVersion = 1; - m_retrievedDescData.m_savePlatform = (ESavePlatform)MAKE_FOURCC(pDescData->m_platform[0], pDescData->m_platform[1], pDescData->m_platform[2], pDescData->m_platform[3]); + m_retrievedDescData.m_savePlatform = static_cast(MAKE_FOURCC(pDescData->m_platform[0], pDescData->m_platform[1], pDescData->m_platform[2], pDescData->m_platform[3])); m_retrievedDescData.m_seed = GetU64FromHexBytes(pDescData->m_seed); m_retrievedDescData.m_hostOptions = GetU32FromHexBytes(pDescData->m_hostOptions); m_retrievedDescData.m_texturePack = GetU32FromHexBytes(pDescData->m_texturePack); @@ -73,7 +73,7 @@ void SonyRemoteStorage::SetRetrievedDescData() void getSaveInfoReturnCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) { - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + SonyRemoteStorage* pRemoteStorage = static_cast(lpParam); app.DebugPrintf("remoteStorageGetInfoCallback err : 0x%08x\n", error_code); if(error_code == 0) { @@ -99,7 +99,7 @@ void getSaveInfoReturnCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int static void getSaveInfoInitCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) { - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + SonyRemoteStorage* pRemoteStorage = static_cast(lpParam); if(error_code != 0) { app.DebugPrintf("getSaveInfoInitCallback err : 0x%08x\n", error_code); @@ -143,7 +143,7 @@ bool SonyRemoteStorage::getSaveData( const char* localDirname, CallbackFunc cb, static void setSaveDataInitCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) { - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + SonyRemoteStorage* pRemoteStorage = static_cast(lpParam); if(error_code != 0) { app.DebugPrintf("setSaveDataInitCallback err : 0x%08x\n", error_code); @@ -181,7 +181,7 @@ const char* SonyRemoteStorage::getLocalFilename() const char* SonyRemoteStorage::getSaveNameUTF8() { if(m_getInfoStatus != e_infoFound) - return NULL; + return nullptr; return m_retrievedDescData.m_saveNameUTF8; } @@ -244,7 +244,7 @@ bool SonyRemoteStorage::setData( PSAVE_INFO info, CallbackFunc cb, LPVOID lpPara int SonyRemoteStorage::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) { - SonyRemoteStorage *pClass= (SonyRemoteStorage *)lpParam; + SonyRemoteStorage *pClass= static_cast(lpParam); if(pClass->m_bAborting) { @@ -261,12 +261,12 @@ int SonyRemoteStorage::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThum } else { - app.DebugPrintf("Thumbnail data is NULL, or has size 0\n"); - pClass->m_thumbnailData = NULL; + app.DebugPrintf("Thumbnail data is nullptr, or has size 0\n"); + pClass->m_thumbnailData = nullptr; pClass->m_thumbnailDataSize = 0; } - if(pClass->m_SetDataThread != NULL) + if(pClass->m_SetDataThread != nullptr) delete pClass->m_SetDataThread; pClass->m_SetDataThread = new C4JThread(setDataThread, pClass, "setDataThread"); @@ -277,7 +277,7 @@ int SonyRemoteStorage::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThum int SonyRemoteStorage::setDataThread(void* lpParam) { - SonyRemoteStorage* pClass = (SonyRemoteStorage*)lpParam; + SonyRemoteStorage* pClass = static_cast(lpParam); pClass->m_startTime = System::currentTimeMillis(); pClass->setDataInternal(); return 0; @@ -322,8 +322,8 @@ int SonyRemoteStorage::getDataProgress() int64_t time = System::currentTimeMillis(); int elapsedSecs = (time - m_startTime) / 1000; - float estimatedTransfered = float(elapsedSecs * transferRatePerSec); - int progVal = m_dataProgress + (estimatedTransfered / float(totalSize)) * 100; + float estimatedTransfered = static_cast(elapsedSecs * transferRatePerSec); + int progVal = m_dataProgress + (estimatedTransfered / static_cast(totalSize)) * 100; if(progVal > nextChunk) return nextChunk; if(progVal > 99) @@ -346,7 +346,7 @@ bool SonyRemoteStorage::shutdown() app.DebugPrintf("Term request done \n"); m_bInitialised = false; free(m_memPoolBuffer); - m_memPoolBuffer = NULL; + m_memPoolBuffer = nullptr; return true; } else @@ -406,10 +406,11 @@ void SonyRemoteStorage::GetDescriptionData( DescriptionData& descData) unsigned int uiHostOptions; bool bHostOptionsRead; DWORD uiTexturePack; - char seed[22]; - app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize,(unsigned char *)seed, uiHostOptions, bHostOptionsRead, uiTexturePack); + char seed[22]; + app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize, reinterpret_cast(seed), + uiHostOptions, bHostOptionsRead, uiTexturePack); - int64_t iSeed = strtoll(seed,NULL,10); + int64_t iSeed = strtoll(seed, nullptr,10); SetU64HexBytes(descData.m_seed, iSeed); // Save the host options that this world was last played with SetU32HexBytes(descData.m_hostOptions, uiHostOptions); @@ -448,7 +449,7 @@ void SonyRemoteStorage::GetDescriptionData( DescriptionData_V2& descData) char seed[22]; app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize,(unsigned char *)seed, uiHostOptions, bHostOptionsRead, uiTexturePack); - int64_t iSeed = strtoll(seed,NULL,10); + int64_t iSeed = strtoll(seed, nullptr,10); SetU64HexBytes(descData.m_seed, iSeed); // Save the host options that this world was last played with SetU32HexBytes(descData.m_hostOptions, uiHostOptions); diff --git a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h index 89ecc066c..5740f78d8 100644 --- a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h +++ b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h @@ -140,7 +140,7 @@ public: static int LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes); static int setDataThread(void* lpParam); - SonyRemoteStorage() : m_memPoolBuffer(NULL), m_bInitialised(false),m_getInfoStatus(e_noInfoFound) {} + SonyRemoteStorage() : m_getInfoStatus(e_noInfoFound), m_bInitialised(false),m_memPoolBuffer(nullptr) {} protected: const char* getRemoteSaveFilename(); diff --git a/Minecraft.Client/Common/PostProcesser.h b/Minecraft.Client/Common/PostProcesser.h index 35fa50809..966d58bc6 100644 --- a/Minecraft.Client/Common/PostProcesser.h +++ b/Minecraft.Client/Common/PostProcesser.h @@ -51,7 +51,10 @@ private: struct GammaCBData { float gamma; - float pad[3]; + float pad; + float uvOffsetX, uvOffsetY; + float uvScaleX, uvScaleY; + float pad2[2]; }; static const char* g_gammaVSCode; diff --git a/Minecraft.Client/Common/Telemetry/TelemetryManager.cpp b/Minecraft.Client/Common/Telemetry/TelemetryManager.cpp index 4b04b19c1..5561e2a17 100644 --- a/Minecraft.Client/Common/Telemetry/TelemetryManager.cpp +++ b/Minecraft.Client/Common/Telemetry/TelemetryManager.cpp @@ -148,7 +148,7 @@ This should be tracked independently of saved games (restoring a save should not */ INT CTelemetryManager::GetSecondsSinceInitialize() { - return (INT)(app.getAppTime() - m_initialiseTime); + return static_cast(app.getAppTime() - m_initialiseTime); } /* @@ -165,21 +165,21 @@ INT CTelemetryManager::GetMode(DWORD dwUserId) Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localplayers[dwUserId] != NULL && pMinecraft->localplayers[dwUserId]->level != NULL && pMinecraft->localplayers[dwUserId]->level->getLevelData() != NULL ) + if( pMinecraft->localplayers[dwUserId] != nullptr && pMinecraft->localplayers[dwUserId]->level != nullptr && pMinecraft->localplayers[dwUserId]->level->getLevelData() != nullptr ) { GameType *gameType = pMinecraft->localplayers[dwUserId]->level->getLevelData()->getGameType(); if (gameType->isSurvival()) { - mode = (INT)eTelem_ModeId_Survival; + mode = static_cast(eTelem_ModeId_Survival); } else if (gameType->isCreative()) { - mode = (INT)eTelem_ModeId_Creative; + mode = static_cast(eTelem_ModeId_Creative); } else { - mode = (INT)eTelem_ModeId_Undefined; + mode = static_cast(eTelem_ModeId_Undefined); } } return mode; @@ -198,11 +198,11 @@ INT CTelemetryManager::GetSubMode(DWORD dwUserId) if(Minecraft::GetInstance()->isTutorial()) { - subMode = (INT)eTelem_SubModeId_Tutorial; + subMode = static_cast(eTelem_SubModeId_Tutorial); } else { - subMode = (INT)eTelem_SubModeId_Normal; + subMode = static_cast(eTelem_SubModeId_Normal); } return subMode; @@ -220,7 +220,7 @@ INT CTelemetryManager::GetLevelId(DWORD dwUserId) { INT levelId = (INT)eTelem_LevelId_Undefined; - levelId = (INT)eTelem_LevelId_PlayerGeneratedLevel; + levelId = static_cast(eTelem_LevelId_PlayerGeneratedLevel); return levelId; } @@ -237,18 +237,18 @@ INT CTelemetryManager::GetSubLevelId(DWORD dwUserId) Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[dwUserId] != NULL) + if(pMinecraft->localplayers[dwUserId] != nullptr) { switch(pMinecraft->localplayers[dwUserId]->dimension) { case 0: - subLevelId = (INT)eTelem_SubLevelId_Overworld; + subLevelId = static_cast(eTelem_SubLevelId_Overworld); break; case -1: - subLevelId = (INT)eTelem_SubLevelId_Nether; + subLevelId = static_cast(eTelem_SubLevelId_Nether); break; case 1: - subLevelId = (INT)eTelem_SubLevelId_End; + subLevelId = static_cast(eTelem_SubLevelId_End); break; }; } @@ -272,7 +272,7 @@ Helps differentiate level attempts when a play plays the same mode/level - espec */ INT CTelemetryManager::GetLevelInstanceID() { - return (INT)m_levelInstanceID; + return static_cast(m_levelInstanceID); } /* @@ -314,19 +314,19 @@ INT CTelemetryManager::GetSingleOrMultiplayer() if(app.GetLocalPlayerCount() == 1 && g_NetworkManager.GetOnlinePlayerCount() == 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Single_Player; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Single_Player); } else if(app.GetLocalPlayerCount() > 1 && g_NetworkManager.GetOnlinePlayerCount() == 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Local; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Local); } else if(app.GetLocalPlayerCount() == 1 && g_NetworkManager.GetOnlinePlayerCount() > 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Live; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Live); } else if(app.GetLocalPlayerCount() > 1 && g_NetworkManager.GetOnlinePlayerCount() > 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Both_Local_and_Live; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Both_Local_and_Live); } return singleOrMultiplayer; @@ -343,16 +343,16 @@ INT CTelemetryManager::GetDifficultyLevel(INT diff) switch(diff) { case 0: - difficultyLevel = (INT)eSen_DifficultyLevel_Easiest; + difficultyLevel = static_cast(eSen_DifficultyLevel_Easiest); break; case 1: - difficultyLevel = (INT)eSen_DifficultyLevel_Easier; + difficultyLevel = static_cast(eSen_DifficultyLevel_Easier); break; case 2: - difficultyLevel = (INT)eSen_DifficultyLevel_Normal; + difficultyLevel = static_cast(eSen_DifficultyLevel_Normal); break; case 3: - difficultyLevel = (INT)eSen_DifficultyLevel_Harder; + difficultyLevel = static_cast(eSen_DifficultyLevel_Harder); break; } @@ -372,11 +372,11 @@ INT CTelemetryManager::GetLicense() if(ProfileManager.IsFullVersion()) { - license = (INT)eSen_License_Full_Purchased_Title; + license = static_cast(eSen_License_Full_Purchased_Title); } else { - license = (INT)eSen_License_Trial_or_Demo; + license = static_cast(eSen_License_Trial_or_Demo); } return license; } @@ -411,15 +411,15 @@ INT CTelemetryManager::GetAudioSettings(DWORD dwUserId) if(volume == 0) { - audioSettings = (INT)eSen_AudioSettings_Off; + audioSettings = static_cast(eSen_AudioSettings_Off); } else if(volume == DEFAULT_VOLUME_LEVEL) { - audioSettings = (INT)eSen_AudioSettings_On_Default; + audioSettings = static_cast(eSen_AudioSettings_On_Default); } else { - audioSettings = (INT)eSen_AudioSettings_On_CustomSetting; + audioSettings = static_cast(eSen_AudioSettings_On_CustomSetting); } } return audioSettings; diff --git a/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.cpp b/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.cpp index f01db84e9..06e73d6f7 100644 --- a/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.cpp +++ b/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.cpp @@ -61,9 +61,9 @@ void ChangeStateConstraint::tick(int iPad) // Send update settings packet to server Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = minecraft->localplayers[iPad]; - if(player != NULL && player->connection && player->connection->getNetworkPlayer() != NULL) + if(player != nullptr && player->connection && player->connection->getNetworkPlayer() != nullptr) { - player->connection->send( shared_ptr( new PlayerInfoPacket( player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs) ) ); + player->connection->send(std::make_shared(player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs)); } } } @@ -89,7 +89,7 @@ void ChangeStateConstraint::tick(int iPad) if(m_changeGameMode) { - if(minecraft->localgameModes[iPad] != NULL) + if(minecraft->localgameModes[iPad] != nullptr) { m_changedFromGameMode = minecraft->localplayers[iPad]->abilities.instabuild ? GameType::CREATIVE : GameType::SURVIVAL; @@ -102,9 +102,9 @@ void ChangeStateConstraint::tick(int iPad) // Send update settings packet to server Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = minecraft->localplayers[iPad]; - if(player != NULL && player->connection && player->connection->getNetworkPlayer() != NULL) + if(player != nullptr && player->connection && player->connection->getNetworkPlayer() != nullptr) { - player->connection->send( shared_ptr( new PlayerInfoPacket( player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs) ) ); + player->connection->send(std::make_shared(player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs)); } } } @@ -126,9 +126,9 @@ void ChangeStateConstraint::tick(int iPad) // Send update settings packet to server Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = minecraft->localplayers[iPad]; - if(player != NULL && player->connection && player->connection->getNetworkPlayer() != NULL) + if(player != nullptr && player->connection && player->connection->getNetworkPlayer() != nullptr) { - player->connection->send( shared_ptr( new PlayerInfoPacket( player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs) ) ); + player->connection->send(std::make_shared(player->connection->getNetworkPlayer()->GetSmallId(), -1, playerPrivs)); } } } diff --git a/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.h b/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.h index 2156870d4..e5f2d74bf 100644 --- a/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.h +++ b/Minecraft.Client/Common/Tutorial/ChangeStateConstraint.h @@ -30,7 +30,7 @@ private: public: virtual ConstraintType getType() { return e_ConstraintChangeState; } - ChangeStateConstraint( Tutorial *tutorial, eTutorial_State targetState, eTutorial_State sourceStates[], DWORD sourceStatesCount, double x0, double y0, double z0, double x1, double y1, double z1, bool contains = true, bool changeGameMode = false, GameType *targetGameMode = NULL ); + ChangeStateConstraint( Tutorial *tutorial, eTutorial_State targetState, eTutorial_State sourceStates[], DWORD sourceStatesCount, double x0, double y0, double z0, double x1, double y1, double z1, bool contains = true, bool changeGameMode = false, GameType *targetGameMode = nullptr ); ~ChangeStateConstraint(); virtual void tick(int iPad); diff --git a/Minecraft.Client/Common/Tutorial/ChoiceTask.cpp b/Minecraft.Client/Common/Tutorial/ChoiceTask.cpp index 1ea34ace6..023e4b22c 100644 --- a/Minecraft.Client/Common/Tutorial/ChoiceTask.cpp +++ b/Minecraft.Client/Common/Tutorial/ChoiceTask.cpp @@ -8,11 +8,12 @@ #include "ChoiceTask.h" #include "..\..\..\Minecraft.World\Material.h" #include "..\..\Windows64\KeyboardMouseInput.h" +#include "Common/UI/UI.h" ChoiceTask::ChoiceTask(Tutorial *tutorial, int descriptionId, int promptId /*= -1*/, bool requiresUserInput /*= false*/, - int iConfirmMapping /*= 0*/, int iCancelMapping /*= 0*/, - eTutorial_CompletionAction cancelAction /*= e_Tutorial_Completion_None*/, ETelemetryChallenges telemetryEvent /*= eTelemetryTutorial_NoEvent*/) - : TutorialTask( tutorial, descriptionId, false, NULL, true, false, false ) + int iConfirmMapping /*= 0*/, int iCancelMapping /*= 0*/, + eTutorial_CompletionAction cancelAction /*= e_Tutorial_Completion_None*/, ETelemetryChallenges telemetryEvent /*= eTelemetryTutorial_NoEvent*/) + : TutorialTask( tutorial, descriptionId, false, nullptr, true, false, false ) { if(requiresUserInput == true) { diff --git a/Minecraft.Client/Common/Tutorial/CompleteUsingItemTask.cpp b/Minecraft.Client/Common/Tutorial/CompleteUsingItemTask.cpp index 43b2f7f31..f2fb8c127 100644 --- a/Minecraft.Client/Common/Tutorial/CompleteUsingItemTask.cpp +++ b/Minecraft.Client/Common/Tutorial/CompleteUsingItemTask.cpp @@ -3,7 +3,7 @@ #include "CompleteUsingItemTask.h" CompleteUsingItemTask::CompleteUsingItemTask(Tutorial *tutorial, int descriptionId, int itemIds[], unsigned int itemIdsLength, bool enablePreCompletion) - : TutorialTask( tutorial, descriptionId, enablePreCompletion, NULL) + : TutorialTask( tutorial, descriptionId, enablePreCompletion, nullptr) { m_iValidItemsA= new int [itemIdsLength]; for(int i=0;i *inConstraints /*= NULL*/, + Tutorial *tutorial, int descriptionId, bool enablePreCompletion /*= true*/, vector *inConstraints /*= nullptr*/, bool bShowMinimumTime /*=false*/, bool bAllowFade /*=true*/, bool m_bTaskReminders /*=true*/ ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_quantity( quantity ), @@ -17,7 +17,7 @@ CraftTask::CraftTask( int itemId, int auxValue, int quantity, } CraftTask::CraftTask( int *items, int *auxValues, int numItems, int quantity, - Tutorial *tutorial, int descriptionId, bool enablePreCompletion /*= true*/, vector *inConstraints /*= NULL*/, + Tutorial *tutorial, int descriptionId, bool enablePreCompletion /*= true*/, vector *inConstraints /*= nullptr*/, bool bShowMinimumTime /*=false*/, bool bAllowFade /*=true*/, bool m_bTaskReminders /*=true*/ ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_quantity( quantity ), diff --git a/Minecraft.Client/Common/Tutorial/CraftTask.h b/Minecraft.Client/Common/Tutorial/CraftTask.h index 1496f07a4..4246711e0 100644 --- a/Minecraft.Client/Common/Tutorial/CraftTask.h +++ b/Minecraft.Client/Common/Tutorial/CraftTask.h @@ -5,10 +5,10 @@ class CraftTask : public TutorialTask { public: CraftTask( int itemId, int auxValue, int quantity, - Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = NULL, + Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ); CraftTask( int *items, int *auxValues, int numItems, int quantity, - Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = NULL, + Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ); ~CraftTask(); diff --git a/Minecraft.Client/Common/Tutorial/DiggerItemHint.cpp b/Minecraft.Client/Common/Tutorial/DiggerItemHint.cpp index 86dbe5005..428bbe3c0 100644 --- a/Minecraft.Client/Common/Tutorial/DiggerItemHint.cpp +++ b/Minecraft.Client/Common/Tutorial/DiggerItemHint.cpp @@ -22,7 +22,7 @@ DiggerItemHint::DiggerItemHint(eTutorial_Hint id, Tutorial *tutorial, int descri int DiggerItemHint::startDestroyBlock(shared_ptr item, Tile *tile) { - if(item != NULL) + if(item != nullptr) { bool itemFound = false; for(unsigned int i=0;i item, Tile *tile) int DiggerItemHint::attack(shared_ptr item, shared_ptr entity) { - if(item != NULL) + if(item != nullptr) { bool itemFound = false; for(unsigned int i=0;iid, this, IDS_TUTORIAL_TASK_PLACE_DOOR) ); addTask(e_Tutorial_State_Gameplay, new CraftTask( Tile::torch_Id, -1, 1, this, IDS_TUTORIAL_TASK_CREATE_TORCH) ); - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"tutorialArea"); - if(area != NULL) + if(area != nullptr) { vector *areaConstraints = new vector(); areaConstraints->push_back( new AreaConstraint( IDS_TUTORIAL_CONSTRAINT_TUTORIAL_AREA, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -283,10 +283,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * MINECART * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"minecartArea"); - if(area != NULL) + if(area != nullptr) { addHint(e_Tutorial_State_Gameplay, new AreaHint(e_Tutorial_Hint_Always_On, this, e_Tutorial_State_Gameplay, e_Tutorial_State_Riding_Minecart, IDS_TUTORIAL_HINT_MINECART, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1 ) ); } @@ -298,10 +298,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * BOAT * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"boatArea"); - if(area != NULL) + if(area != nullptr) { addHint(e_Tutorial_State_Gameplay, new AreaHint(e_Tutorial_Hint_Always_On, this, e_Tutorial_State_Gameplay, e_Tutorial_State_Riding_Boat, IDS_TUTORIAL_HINT_BOAT, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1 ) ); } @@ -313,10 +313,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * FISHING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"fishingArea"); - if(area != NULL) + if(area != nullptr) { addHint(e_Tutorial_State_Gameplay, new AreaHint(e_Tutorial_Hint_Always_On, this, e_Tutorial_State_Gameplay, e_Tutorial_State_Fishing, IDS_TUTORIAL_HINT_FISHING, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1 ) ); } @@ -328,10 +328,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * PISTON - SELF-REPAIRING BRIDGE * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"pistonBridgeArea"); - if(area != NULL) + if(area != nullptr) { addHint(e_Tutorial_State_Gameplay, new AreaHint(e_Tutorial_Hint_Always_On, this, e_Tutorial_State_Gameplay, e_Tutorial_State_None, IDS_TUTORIAL_HINT_PISTON_SELF_REPAIRING_BRIDGE, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1, true ) ); } @@ -343,10 +343,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * PISTON - PISTON AND REDSTONE CIRCUITS * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"pistonArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State redstoneAndPistonStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Redstone_And_Piston, redstoneAndPistonStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -368,10 +368,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * PORTAL * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"portalArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State portalStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Portal, portalStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -391,10 +391,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * CREATIVE * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"creativeArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State creativeStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_CreativeMode, creativeStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1,true,true,GameType::CREATIVE) ); @@ -411,7 +411,7 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) ProcedureCompoundTask *creativeFinalTask = new ProcedureCompoundTask( this ); AABB *exitArea = app.getGameRuleDefinitions()->getNamedArea(L"creativeExitArea"); - if(exitArea != NULL) + if(exitArea != nullptr) { vector *creativeExitAreaConstraints = new vector(); creativeExitAreaConstraints->push_back( new AreaConstraint( -1, exitArea->x0,exitArea->y0,exitArea->z0,exitArea->x1,exitArea->y1,exitArea->z1,true,false) ); @@ -434,10 +434,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * BREWING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"brewingArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State brewingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Brewing, brewingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -467,10 +467,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * ENCHANTING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"enchantingArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State enchantingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Enchanting, enchantingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -492,10 +492,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * ANVIL * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"anvilArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State enchantingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Anvil, enchantingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -517,10 +517,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * TRADING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"tradingArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State tradingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Trading, tradingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -541,10 +541,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * FIREWORKS * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"fireworksArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State fireworkStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Fireworks, fireworkStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -563,10 +563,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * BEACON * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"beaconArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State beaconStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Beacon, beaconStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -585,10 +585,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * HOPPER * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"hopperArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State hopperStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Hopper, hopperStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -610,10 +610,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * ENDERCHEST * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"enderchestArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State enchantingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Enderchests, enchantingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -632,10 +632,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * FARMING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"farmingArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State farmingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Farming, farmingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -661,10 +661,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * BREEDING * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"breedingArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State breedingStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Breeding, breedingStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); @@ -689,10 +689,10 @@ FullTutorial::FullTutorial(int iPad, bool isTrial /*= false*/) * SNOW AND IRON GOLEM * */ - if(app.getGameRuleDefinitions() != NULL) + if(app.getGameRuleDefinitions() != nullptr) { AABB *area = app.getGameRuleDefinitions()->getNamedArea(L"golemArea"); - if(area != NULL) + if(area != nullptr) { eTutorial_State golemStates[] = {e_Tutorial_State_Gameplay}; AddGlobalConstraint( new ChangeStateConstraint(this, e_Tutorial_State_Golem, golemStates, 1, area->x0,area->y0,area->z0,area->x1,area->y1,area->z1) ); diff --git a/Minecraft.Client/Common/Tutorial/FullTutorialActiveTask.cpp b/Minecraft.Client/Common/Tutorial/FullTutorialActiveTask.cpp index 54985d218..f1357c6c5 100644 --- a/Minecraft.Client/Common/Tutorial/FullTutorialActiveTask.cpp +++ b/Minecraft.Client/Common/Tutorial/FullTutorialActiveTask.cpp @@ -3,7 +3,7 @@ #include "FullTutorialActiveTask.h" FullTutorialActiveTask::FullTutorialActiveTask(Tutorial *tutorial, eTutorial_CompletionAction completeAction /*= e_Tutorial_Completion_None*/) - : TutorialTask( tutorial, -1, false, NULL, false, false, false ) + : TutorialTask( tutorial, -1, false, nullptr, false, false, false ) { m_completeAction = completeAction; } diff --git a/Minecraft.Client/Common/Tutorial/InfoTask.cpp b/Minecraft.Client/Common/Tutorial/InfoTask.cpp index 6a78ed92a..2e4818047 100644 --- a/Minecraft.Client/Common/Tutorial/InfoTask.cpp +++ b/Minecraft.Client/Common/Tutorial/InfoTask.cpp @@ -8,10 +8,11 @@ #include "InfoTask.h" #include "..\..\..\Minecraft.World\Material.h" #include "..\..\Windows64\KeyboardMouseInput.h" +#include "Common/UI/UI.h" InfoTask::InfoTask(Tutorial *tutorial, int descriptionId, int promptId /*= -1*/, bool requiresUserInput /*= false*/, - int iMapping /*= 0*/, ETelemetryChallenges telemetryEvent /*= eTelemetryTutorial_NoEvent*/) - : TutorialTask( tutorial, descriptionId, false, NULL, true, false, false ) + int iMapping /*= 0*/, ETelemetryChallenges telemetryEvent /*= eTelemetryTutorial_NoEvent*/) + : TutorialTask( tutorial, descriptionId, false, nullptr, true, false, false ) { if(requiresUserInput == true) { diff --git a/Minecraft.Client/Common/Tutorial/PickupTask.h b/Minecraft.Client/Common/Tutorial/PickupTask.h index 68e1d4793..9f2d2426e 100644 --- a/Minecraft.Client/Common/Tutorial/PickupTask.h +++ b/Minecraft.Client/Common/Tutorial/PickupTask.h @@ -8,7 +8,7 @@ class PickupTask : public TutorialTask { public: PickupTask( int itemId, unsigned int quantity, int auxValue, - Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = NULL, + Tutorial *tutorial, int descriptionId, bool enablePreCompletion = true, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_itemId( itemId), diff --git a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp index 0e3b3e377..ddf15a55c 100644 --- a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp +++ b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp @@ -11,7 +11,7 @@ ProcedureCompoundTask::~ProcedureCompoundTask() void ProcedureCompoundTask::AddTask(TutorialTask *task) { - if(task != NULL) + if(task != nullptr) { m_taskSequence.push_back(task); } diff --git a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.h b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.h index 36b327984..0a5b7eee4 100644 --- a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.h +++ b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.h @@ -8,7 +8,7 @@ class ProcedureCompoundTask : public TutorialTask { public: ProcedureCompoundTask(Tutorial *tutorial ) - : TutorialTask(tutorial, -1, false, NULL, false, true, false ) + : TutorialTask(tutorial, -1, false, nullptr, false, true, false ) {} ~ProcedureCompoundTask(); diff --git a/Minecraft.Client/Common/Tutorial/ProgressFlagTask.h b/Minecraft.Client/Common/Tutorial/ProgressFlagTask.h index b96e1bc01..9baea5a57 100644 --- a/Minecraft.Client/Common/Tutorial/ProgressFlagTask.h +++ b/Minecraft.Client/Common/Tutorial/ProgressFlagTask.h @@ -17,7 +17,7 @@ private: EProgressFlagType m_type; public: ProgressFlagTask(char *flags, char mask, EProgressFlagType type, Tutorial *tutorial ) : - TutorialTask(tutorial, -1, false, NULL ), + TutorialTask(tutorial, -1, false, nullptr ), flags( flags ), m_mask( mask ), m_type( type ) {} diff --git a/Minecraft.Client/Common/Tutorial/RideEntityTask.cpp b/Minecraft.Client/Common/Tutorial/RideEntityTask.cpp index 29fe592d5..29b776453 100644 --- a/Minecraft.Client/Common/Tutorial/RideEntityTask.cpp +++ b/Minecraft.Client/Common/Tutorial/RideEntityTask.cpp @@ -23,7 +23,7 @@ bool RideEntityTask::isCompleted() void RideEntityTask::onRideEntity(shared_ptr entity) { - if (entity->instanceof((eINSTANCEOF) m_eType)) + if (entity->instanceof(static_cast(m_eType))) { bIsCompleted = true; } diff --git a/Minecraft.Client/Common/Tutorial/RideEntityTask.h b/Minecraft.Client/Common/Tutorial/RideEntityTask.h index d9b6d41e4..749b187f8 100644 --- a/Minecraft.Client/Common/Tutorial/RideEntityTask.h +++ b/Minecraft.Client/Common/Tutorial/RideEntityTask.h @@ -13,7 +13,7 @@ protected: public: RideEntityTask(const int eTYPE, Tutorial *tutorial, int descriptionId, - bool enablePreCompletion = false, vector *inConstraints = NULL, + bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true ); virtual bool isCompleted(); diff --git a/Minecraft.Client/Common/Tutorial/StatTask.cpp b/Minecraft.Client/Common/Tutorial/StatTask.cpp index 5f8b215e3..c2dc82aa4 100644 --- a/Minecraft.Client/Common/Tutorial/StatTask.cpp +++ b/Minecraft.Client/Common/Tutorial/StatTask.cpp @@ -6,7 +6,7 @@ #include "StatTask.h" StatTask::StatTask(Tutorial *tutorial, int descriptionId, bool enablePreCompletion, Stat *stat, int variance /*= 1*/) - : TutorialTask( tutorial, descriptionId, enablePreCompletion, NULL ) + : TutorialTask( tutorial, descriptionId, enablePreCompletion, nullptr ) { this->stat = stat; @@ -20,6 +20,6 @@ bool StatTask::isCompleted() return true; Minecraft *minecraft = Minecraft::GetInstance(); - bIsCompleted = minecraft->stats[ProfileManager.GetPrimaryPad()]->getTotalValue( stat ) >= (unsigned int)targetValue; + bIsCompleted = minecraft->stats[ProfileManager.GetPrimaryPad()]->getTotalValue( stat ) >= static_cast(targetValue); return bIsCompleted; } \ No newline at end of file diff --git a/Minecraft.Client/Common/Tutorial/StateChangeTask.h b/Minecraft.Client/Common/Tutorial/StateChangeTask.h index fb9e63966..ab34d35dc 100644 --- a/Minecraft.Client/Common/Tutorial/StateChangeTask.h +++ b/Minecraft.Client/Common/Tutorial/StateChangeTask.h @@ -9,7 +9,7 @@ private: eTutorial_State m_state; public: StateChangeTask(eTutorial_State state, - Tutorial *tutorial, int descriptionId = -1, bool enablePreCompletion = false, vector *inConstraints = NULL, + Tutorial *tutorial, int descriptionId = -1, bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_state( state ) diff --git a/Minecraft.Client/Common/Tutorial/TakeItemHint.cpp b/Minecraft.Client/Common/Tutorial/TakeItemHint.cpp index a1a5c37a9..3a3184889 100644 --- a/Minecraft.Client/Common/Tutorial/TakeItemHint.cpp +++ b/Minecraft.Client/Common/Tutorial/TakeItemHint.cpp @@ -19,7 +19,7 @@ TakeItemHint::TakeItemHint(eTutorial_Hint id, Tutorial *tutorial, int items[], u bool TakeItemHint::onTake(shared_ptr item) { - if(item != NULL) + if(item != nullptr) { bool itemFound = false; for(unsigned int i=0;i Tutorial::s_completableTasks; @@ -31,7 +32,7 @@ int Tutorial::m_iTutorialFreezeTimeValue = 8000; bool Tutorial::PopupMessageDetails::isSameContent(PopupMessageDetails *other) { - if(other == NULL) return false; + if(other == nullptr) return false; bool textTheSame = (m_messageId == other->m_messageId) && (m_messageString.compare(other->m_messageString) == 0); bool titleTheSame = (m_titleId == other->m_titleId) && (m_titleString.compare(other->m_titleString) == 0); @@ -360,12 +361,12 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) m_hintDisplayed = false; m_freezeTime = false; m_timeFrozen = false; - m_UIScene = NULL; + m_UIScene = nullptr; m_allowShow = true; m_bHasTickedOnce = false; m_firstTickTime = 0; - m_lastMessage = NULL; + m_lastMessage = nullptr; lastMessageTime = 0; m_iTaskReminders = 0; @@ -374,13 +375,13 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) m_CurrentState = e_Tutorial_State_Gameplay; m_hasStateChanged = false; #ifdef _XBOX - m_hTutorialScene=NULL; + m_hTutorialScene=nullptr; #endif for(unsigned int i = 0; i < e_Tutorial_State_Max; ++i) { - currentTask[i] = NULL; - currentFailedConstraint[i] = NULL; + currentTask[i] = nullptr; + currentFailedConstraint[i] = nullptr; } // DEFAULT TASKS THAT ALL TUTORIALS SHARE @@ -1012,7 +1013,7 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) addTask(e_Tutorial_State_Horse, new InfoTask(this, IDS_TUTORIAL_TASK_HORSE_TAMING2, IDS_TUTORIAL_PROMPT_PRESS_A_TO_CONTINUE, true, ACTION_MENU_A) ); // 4J-JEV: Only force the RideEntityTask if we're on the full-tutorial. - if (isFullTutorial) addTask(e_Tutorial_State_Horse, new RideEntityTask(eTYPE_HORSE, this, IDS_TUTORIAL_TASK_HORSE_RIDE, true, NULL, false, false, false) ); + if (isFullTutorial) addTask(e_Tutorial_State_Horse, new RideEntityTask(eTYPE_HORSE, this, IDS_TUTORIAL_TASK_HORSE_RIDE, true, nullptr, false, false, false) ); else addTask(e_Tutorial_State_Horse, new InfoTask(this, IDS_TUTORIAL_TASK_HORSE_RIDE, IDS_TUTORIAL_PROMPT_PRESS_A_TO_CONTINUE, true, ACTION_MENU_A) ); addTask(e_Tutorial_State_Horse, new InfoTask(this, IDS_TUTORIAL_TASK_HORSE_SADDLES, IDS_TUTORIAL_PROMPT_PRESS_A_TO_CONTINUE, true, ACTION_MENU_A) ); @@ -1163,8 +1164,8 @@ Tutorial::~Tutorial() delete it; } - currentTask[i] = NULL; - currentFailedConstraint[i] = NULL; + currentTask[i] = nullptr; + currentFailedConstraint[i] = nullptr; } } @@ -1173,7 +1174,7 @@ void Tutorial::debugResetPlayerSavedProgress(int iPad) #if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__) GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)StorageManager.GetGameDefinedProfileData(iPad); #else - GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)ProfileManager.GetGameDefinedProfileData(iPad); + GAME_SETTINGS *pGameSettings = static_cast(ProfileManager.GetGameDefinedProfileData(iPad)); #endif ZeroMemory( pGameSettings->ucTutorialCompletion, TUTORIAL_PROFILE_STORAGE_BYTES ); pGameSettings->uiSpecialTutorialBitmask = 0; @@ -1202,7 +1203,7 @@ void Tutorial::setCompleted( int completableId ) #if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__) GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)StorageManager.GetGameDefinedProfileData(m_iPad); #else - GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)ProfileManager.GetGameDefinedProfileData(m_iPad); + GAME_SETTINGS *pGameSettings = static_cast(ProfileManager.GetGameDefinedProfileData(m_iPad)); #endif int arrayIndex = completableIndex >> 3; int bitIndex = 7 - (completableIndex % 8); @@ -1235,7 +1236,7 @@ bool Tutorial::getCompleted( int completableId ) #if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__) GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)StorageManager.GetGameDefinedProfileData(m_iPad); #else - GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)ProfileManager.GetGameDefinedProfileData(m_iPad); + GAME_SETTINGS *pGameSettings = static_cast(ProfileManager.GetGameDefinedProfileData(m_iPad)); #endif int arrayIndex = completableIndex >> 3; int bitIndex = 7 - (completableIndex % 8); @@ -1362,7 +1363,7 @@ void Tutorial::tick() if(!m_allowShow) { - if( currentTask[m_CurrentState] != NULL && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) + if( currentTask[m_CurrentState] != nullptr && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) { uiTempDisabled = true; } @@ -1412,7 +1413,7 @@ void Tutorial::tick() if(ui.IsPauseMenuDisplayed( m_iPad ) ) { - if( currentTask[m_CurrentState] != NULL && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) + if( currentTask[m_CurrentState] != nullptr && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) { uiTempDisabled = true; } @@ -1460,12 +1461,12 @@ void Tutorial::tick() // Check constraints // Only need to update these if we aren't already failing something - if( !m_allTutorialsComplete && (currentFailedConstraint[m_CurrentState] == NULL || currentFailedConstraint[m_CurrentState]->isConstraintSatisfied(m_iPad)) ) + if( !m_allTutorialsComplete && (currentFailedConstraint[m_CurrentState] == nullptr || currentFailedConstraint[m_CurrentState]->isConstraintSatisfied(m_iPad)) ) { - if( currentFailedConstraint[m_CurrentState] != NULL && currentFailedConstraint[m_CurrentState]->isConstraintSatisfied(m_iPad) ) + if( currentFailedConstraint[m_CurrentState] != nullptr && currentFailedConstraint[m_CurrentState]->isConstraintSatisfied(m_iPad) ) { constraintChanged = true; - currentFailedConstraint[m_CurrentState] = NULL; + currentFailedConstraint[m_CurrentState] = nullptr; } for (auto& constraint : constraints[m_CurrentState]) { @@ -1477,7 +1478,7 @@ void Tutorial::tick() } } - if( !m_allTutorialsComplete && currentFailedConstraint[m_CurrentState] == NULL ) + if( !m_allTutorialsComplete && currentFailedConstraint[m_CurrentState] == nullptr ) { // Update tasks bool isCurrentTask = true; @@ -1496,7 +1497,7 @@ void Tutorial::tick() eTutorial_CompletionAction compAction = task->getCompletionAction(); it = activeTasks[m_CurrentState].erase( it ); delete task; - task = NULL; + task = nullptr; if( activeTasks[m_CurrentState].size() > 0 ) { @@ -1552,12 +1553,12 @@ void Tutorial::tick() { setStateCompleted( m_CurrentState ); - currentTask[m_CurrentState] = NULL; + currentTask[m_CurrentState] = nullptr; } taskChanged = true; // If we can complete this early, check if we can complete it right now - if( currentTask[m_CurrentState] != NULL && currentTask[m_CurrentState]->isPreCompletionEnabled() ) + if( currentTask[m_CurrentState] != nullptr && currentTask[m_CurrentState]->isPreCompletionEnabled() ) { isCurrentTask = true; } @@ -1566,7 +1567,7 @@ void Tutorial::tick() { ++it; } - if( task != NULL && task->ShowMinimumTime() && task->hasBeenActivated() && (lastMessageTime + m_iTutorialMinimumDisplayMessageTime ) < GetTickCount() ) + if( task != nullptr && task->ShowMinimumTime() && task->hasBeenActivated() && (lastMessageTime + m_iTutorialMinimumDisplayMessageTime ) < GetTickCount() ) { task->setShownForMinimumTime(); @@ -1587,7 +1588,7 @@ void Tutorial::tick() } } - if( currentTask[m_CurrentState] == NULL && activeTasks[m_CurrentState].size() > 0 ) + if( currentTask[m_CurrentState] == nullptr && activeTasks[m_CurrentState].size() > 0 ) { currentTask[m_CurrentState] = activeTasks[m_CurrentState][0]; currentTask[m_CurrentState]->setAsCurrentTask(); @@ -1616,17 +1617,17 @@ void Tutorial::tick() } if( constraintChanged || taskChanged || m_hasStateChanged || - (currentFailedConstraint[m_CurrentState] == NULL && currentTask[m_CurrentState] != NULL && (m_lastMessage == NULL || currentTask[m_CurrentState]->getDescriptionId() != m_lastMessage->m_messageId) && !m_hintDisplayed) + (currentFailedConstraint[m_CurrentState] == nullptr && currentTask[m_CurrentState] != nullptr && (m_lastMessage == nullptr || currentTask[m_CurrentState]->getDescriptionId() != m_lastMessage->m_messageId) && !m_hintDisplayed) ) { - if( currentFailedConstraint[m_CurrentState] != NULL ) + if( currentFailedConstraint[m_CurrentState] != nullptr ) { PopupMessageDetails *message = new PopupMessageDetails(); message->m_messageId = currentFailedConstraint[m_CurrentState]->getDescriptionId(); message->m_allowFade = false; setMessage( message ); } - else if( currentTask[m_CurrentState] != NULL ) + else if( currentTask[m_CurrentState] != nullptr ) { PopupMessageDetails *message = new PopupMessageDetails(); message->m_messageId = currentTask[m_CurrentState]->getDescriptionId(); @@ -1637,7 +1638,7 @@ void Tutorial::tick() } else { - setMessage( NULL ); + setMessage( nullptr ); } } @@ -1646,7 +1647,7 @@ void Tutorial::tick() m_hintDisplayed = false; } - if( currentFailedConstraint[m_CurrentState] == NULL && currentTask[m_CurrentState] != NULL && (m_iTaskReminders!=0) && (lastMessageTime + (m_iTaskReminders * m_iTutorialReminderTime) ) < GetTickCount() ) + if( currentFailedConstraint[m_CurrentState] == nullptr && currentTask[m_CurrentState] != nullptr && (m_iTaskReminders!=0) && (lastMessageTime + (m_iTaskReminders * m_iTutorialReminderTime) ) < GetTickCount() ) { // Reminder PopupMessageDetails *message = new PopupMessageDetails(); @@ -1671,7 +1672,7 @@ void Tutorial::tick() bool Tutorial::setMessage(PopupMessageDetails *message) { - if(message != NULL && !message->m_forceDisplay && + if(message != nullptr && !message->m_forceDisplay && m_lastMessageState == m_CurrentState && message->isSameContent(m_lastMessage) && ( !message->m_isReminder || ( (lastMessageTime + m_iTutorialReminderTime ) > GetTickCount() && message->m_isReminder ) ) @@ -1681,7 +1682,7 @@ bool Tutorial::setMessage(PopupMessageDetails *message) return false; } - if(message != NULL && (message->m_messageId > 0 || !message->m_messageString.empty()) ) + if(message != nullptr && (message->m_messageId > 0 || !message->m_messageString.empty()) ) { m_lastMessageState = m_CurrentState; @@ -1695,7 +1696,7 @@ bool Tutorial::setMessage(PopupMessageDetails *message) else { auto it = messages.find(message->m_messageId); - if( it != messages.end() && it->second != NULL ) + if( it != messages.end() && it->second != nullptr ) { TutorialMessage *messageString = it->second; text = wstring( messageString->getMessageForDisplay() ); @@ -1725,7 +1726,7 @@ bool Tutorial::setMessage(PopupMessageDetails *message) else if(message->m_promptId >= 0) { auto it = messages.find(message->m_promptId); - if(it != messages.end() && it->second != NULL) + if(it != messages.end() && it->second != nullptr) { TutorialMessage *prompt = it->second; text.append( prompt->getMessageForDisplay() ); @@ -1754,7 +1755,7 @@ bool Tutorial::setMessage(PopupMessageDetails *message) ui.SetTutorialDescription( m_iPad, &popupInfo ); } } - else if( (m_lastMessage != NULL && m_lastMessage->m_messageId != -1) ) //&& (lastMessageTime + m_iTutorialReminderTime ) > GetTickCount() ) + else if( (m_lastMessage != nullptr && m_lastMessage->m_messageId != -1) ) //&& (lastMessageTime + m_iTutorialReminderTime ) > GetTickCount() ) { // This should cause the popup to dissappear TutorialPopupInfo popupInfo; @@ -1763,7 +1764,7 @@ bool Tutorial::setMessage(PopupMessageDetails *message) ui.SetTutorialDescription( m_iPad, &popupInfo ); } - if(m_lastMessage != NULL) delete m_lastMessage; + if(m_lastMessage != nullptr) delete m_lastMessage; m_lastMessage = message; return true; @@ -1777,7 +1778,7 @@ bool Tutorial::setMessage(TutorialHint *hint, PopupMessageDetails *message) bool messageShown = false; DWORD time = GetTickCount(); - if(message != NULL && (message->m_forceDisplay || hintsOn) && + if(message != nullptr && (message->m_forceDisplay || hintsOn) && (!message->m_delay || ( (m_hintDisplayed && (time - m_lastHintDisplayedTime) > m_iTutorialHintDelayTime ) || @@ -1792,7 +1793,7 @@ bool Tutorial::setMessage(TutorialHint *hint, PopupMessageDetails *message) { m_lastHintDisplayedTime = time; m_hintDisplayed = true; - if(hint!=NULL) setHintCompleted( hint ); + if(hint!=nullptr) setHintCompleted( hint ); } } return messageShown; @@ -1815,7 +1816,7 @@ void Tutorial::showTutorialPopup(bool show) if(!show) { - if( currentTask[m_CurrentState] != NULL && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) + if( currentTask[m_CurrentState] != nullptr && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) { uiTempDisabled = true; } @@ -1926,7 +1927,7 @@ void Tutorial::handleUIInput(int iAction) { if( m_hintDisplayed ) return; - if(currentTask[m_CurrentState] != NULL) + if(currentTask[m_CurrentState] != nullptr) currentTask[m_CurrentState]->handleUIInput(iAction); } @@ -1988,7 +1989,7 @@ void Tutorial::onSelectedItemChanged(shared_ptr item) // Menus and states like riding in a minecart will NOT allow this if( isSelectedItemState() ) { - if(item != NULL) + if(item != nullptr) { switch(item->id) { @@ -2151,7 +2152,7 @@ void Tutorial::AddConstraint(TutorialConstraint *c) void Tutorial::RemoveConstraint(TutorialConstraint *c, bool delayedRemove /*= false*/) { if( currentFailedConstraint[m_CurrentState] == c ) - currentFailedConstraint[m_CurrentState] = NULL; + currentFailedConstraint[m_CurrentState] = nullptr; if( c->getQueuedForRemoval() ) { @@ -2211,16 +2212,16 @@ void Tutorial::addMessage(int messageId, bool limitRepeats /*= false*/, unsigned } #ifdef _XBOX -void Tutorial::changeTutorialState(eTutorial_State newState, CXuiScene *scene /*= NULL*/) +void Tutorial::changeTutorialState(eTutorial_State newState, CXuiScene *scene /*= nullptr*/) #else -void Tutorial::changeTutorialState(eTutorial_State newState, UIScene *scene /*= NULL*/) +void Tutorial::changeTutorialState(eTutorial_State newState, UIScene *scene /*= nullptr*/) #endif { if(newState == m_CurrentState) { // If clearing the scene, make sure that the tutorial popup has its reference to this scene removed #ifndef _XBOX - if( scene == NULL ) + if( scene == nullptr ) { ui.RemoveInteractSceneReference(m_iPad, m_UIScene); } @@ -2241,7 +2242,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() ) + if( currentTask[m_CurrentState] != nullptr && currentTask[m_CurrentState]->isCompleted() ) { activeTasks[m_CurrentState].erase( find( activeTasks[m_CurrentState].begin(), activeTasks[m_CurrentState].end(), currentTask[m_CurrentState]) ); @@ -2252,21 +2253,21 @@ void Tutorial::changeTutorialState(eTutorial_State newState, UIScene *scene /*= } else { - currentTask[m_CurrentState] = NULL; + currentTask[m_CurrentState] = nullptr; } } - if( currentTask[m_CurrentState] != NULL ) + if( currentTask[m_CurrentState] != nullptr ) { currentTask[m_CurrentState]->onStateChange(newState); } // Make sure that the current message is cleared - setMessage( NULL ); + setMessage( nullptr ); // If clearing the scene, make sure that the tutorial popup has its reference to this scene removed #ifndef _XBOX - if( scene == NULL ) + if( scene == nullptr ) { ui.RemoveInteractSceneReference(m_iPad, m_UIScene); } diff --git a/Minecraft.Client/Common/Tutorial/Tutorial.h b/Minecraft.Client/Common/Tutorial/Tutorial.h index 169c33e3e..c36a9086e 100644 --- a/Minecraft.Client/Common/Tutorial/Tutorial.h +++ b/Minecraft.Client/Common/Tutorial/Tutorial.h @@ -139,9 +139,9 @@ public: bool getCompleted( int completableId ); #ifdef _XBOX - void changeTutorialState(eTutorial_State newState, CXuiScene *scene = NULL); + void changeTutorialState(eTutorial_State newState, CXuiScene *scene = nullptr); #else - void changeTutorialState(eTutorial_State newState, UIScene *scene = NULL); + void changeTutorialState(eTutorial_State newState, UIScene *scene = nullptr); #endif bool isSelectedItemState(); diff --git a/Minecraft.Client/Common/Tutorial/TutorialHint.cpp b/Minecraft.Client/Common/Tutorial/TutorialHint.cpp index 5f0808bf2..d80d7d16e 100644 --- a/Minecraft.Client/Common/Tutorial/TutorialHint.cpp +++ b/Minecraft.Client/Common/Tutorial/TutorialHint.cpp @@ -9,7 +9,7 @@ TutorialHint::TutorialHint(eTutorial_Hint id, Tutorial *tutorial, int descriptionId, eHintType type, bool allowFade /*= true*/) : m_id( id ), m_tutorial(tutorial), m_descriptionId( descriptionId ), m_type( type ), m_counter( 0 ), - m_lastTile( NULL ), m_hintNeeded( true ), m_allowFade(allowFade) + m_lastTile( nullptr ), m_hintNeeded( true ), m_allowFade(allowFade) { tutorial->addMessage(descriptionId, type != e_Hint_NoIngredients); } diff --git a/Minecraft.Client/Common/Tutorial/TutorialMode.cpp b/Minecraft.Client/Common/Tutorial/TutorialMode.cpp index 82c81598f..50a45a42d 100644 --- a/Minecraft.Client/Common/Tutorial/TutorialMode.cpp +++ b/Minecraft.Client/Common/Tutorial/TutorialMode.cpp @@ -15,7 +15,7 @@ TutorialMode::TutorialMode(int iPad, Minecraft *minecraft, ClientConnection *con TutorialMode::~TutorialMode() { - if(tutorial != NULL) + if(tutorial != nullptr) delete tutorial; } @@ -38,7 +38,7 @@ bool TutorialMode::destroyBlock(int x, int y, int z, int face) } shared_ptr item = minecraft->player->getSelectedItem(); int damageBefore; - if(item != NULL) + if(item != nullptr) { damageBefore = item->getDamageValue(); } @@ -46,7 +46,7 @@ bool TutorialMode::destroyBlock(int x, int y, int z, int face) if(!tutorial->m_allTutorialsComplete) { - if ( item != NULL && item->isDamageableItem() ) + if ( item != nullptr && item->isDamageableItem() ) { int max = item->getMaxDamage(); int damageNow = item->getDamageValue(); @@ -88,7 +88,7 @@ bool TutorialMode::useItemOn(shared_ptr player, Level *level, shared_ptr if(!bTestUseOnly) { - if(item != NULL) + if(item != nullptr) { haveItem = true; itemCount = item->count; diff --git a/Minecraft.Client/Common/Tutorial/TutorialMode.h b/Minecraft.Client/Common/Tutorial/TutorialMode.h index 75e24edf0..2263a91c6 100644 --- a/Minecraft.Client/Common/Tutorial/TutorialMode.h +++ b/Minecraft.Client/Common/Tutorial/TutorialMode.h @@ -19,7 +19,7 @@ public: virtual void startDestroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face); virtual void tick(); - virtual bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=NULL); + virtual bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=nullptr); virtual void attack(shared_ptr player, shared_ptr entity); virtual bool isInputAllowed(int mapping); diff --git a/Minecraft.Client/Common/Tutorial/TutorialTask.cpp b/Minecraft.Client/Common/Tutorial/TutorialTask.cpp index 53fdd275a..1b6d84b2a 100644 --- a/Minecraft.Client/Common/Tutorial/TutorialTask.cpp +++ b/Minecraft.Client/Common/Tutorial/TutorialTask.cpp @@ -9,7 +9,7 @@ TutorialTask::TutorialTask(Tutorial *tutorial, int descriptionId, bool enablePre areConstraintsEnabled( false ), bIsCompleted( false ), bHasBeenActivated( false ), m_bAllowFade(bAllowFade), m_bTaskReminders(bTaskReminders), m_bShowMinimumTime( bShowMinimumTime), m_bShownForMinimumTime( false ) { - if(inConstraints != NULL) + if(inConstraints != nullptr) { for(auto& constraint : *inConstraints) { diff --git a/Minecraft.Client/Common/Tutorial/UseItemTask.h b/Minecraft.Client/Common/Tutorial/UseItemTask.h index 6c7295407..9c8f01921 100644 --- a/Minecraft.Client/Common/Tutorial/UseItemTask.h +++ b/Minecraft.Client/Common/Tutorial/UseItemTask.h @@ -13,7 +13,7 @@ private: public: UseItemTask(const int itemId, Tutorial *tutorial, int descriptionId, - bool enablePreCompletion = false, vector *inConstraints = NULL, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true ); + bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true ); virtual bool isCompleted(); virtual void useItem(shared_ptr item, bool bTestUseOnly=false); }; \ No newline at end of file diff --git a/Minecraft.Client/Common/Tutorial/UseTileTask.h b/Minecraft.Client/Common/Tutorial/UseTileTask.h index 74b3a40cc..1f72fb2ed 100644 --- a/Minecraft.Client/Common/Tutorial/UseTileTask.h +++ b/Minecraft.Client/Common/Tutorial/UseTileTask.h @@ -16,9 +16,9 @@ private: public: UseTileTask(const int tileId, int x, int y, int z, Tutorial *tutorial, int descriptionId, - bool enablePreCompletion = false, vector *inConstraints = NULL, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true ); + bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true ); UseTileTask(const int tileId, Tutorial *tutorial, int descriptionId, - bool enablePreCompletion = false, vector *inConstraints = NULL, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true); + bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime = false, bool bAllowFade = true, bool bTaskReminders = true); virtual bool isCompleted(); virtual void useItemOn(Level *level, shared_ptr item, int x, int y, int z, bool bTestUseOnly=false); }; \ No newline at end of file diff --git a/Minecraft.Client/Common/Tutorial/XuiCraftingTask.cpp b/Minecraft.Client/Common/Tutorial/XuiCraftingTask.cpp index 71b884790..d0217d195 100644 --- a/Minecraft.Client/Common/Tutorial/XuiCraftingTask.cpp +++ b/Minecraft.Client/Common/Tutorial/XuiCraftingTask.cpp @@ -22,13 +22,13 @@ bool XuiCraftingTask::isCompleted() switch(m_type) { case e_Crafting_SelectGroup: - if(craftScene != NULL && craftScene->getCurrentGroup() == m_group) + if(craftScene != nullptr && craftScene->getCurrentGroup() == m_group) { completed = true; } break; case e_Crafting_SelectItem: - if(craftScene != NULL && craftScene->isItemSelected(m_item)) + if(craftScene != nullptr && craftScene->isItemSelected(m_item)) { completed = true; } diff --git a/Minecraft.Client/Common/Tutorial/XuiCraftingTask.h b/Minecraft.Client/Common/Tutorial/XuiCraftingTask.h index 2dc48709d..146b1554a 100644 --- a/Minecraft.Client/Common/Tutorial/XuiCraftingTask.h +++ b/Minecraft.Client/Common/Tutorial/XuiCraftingTask.h @@ -12,7 +12,7 @@ public: }; // Select group - XuiCraftingTask(Tutorial *tutorial, int descriptionId, Recipy::_eGroupType groupToSelect, bool enablePreCompletion = false, vector *inConstraints = NULL, + XuiCraftingTask(Tutorial *tutorial, int descriptionId, Recipy::_eGroupType groupToSelect, bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_group(groupToSelect), @@ -20,7 +20,7 @@ public: {} // Select Item - XuiCraftingTask(Tutorial *tutorial, int descriptionId, int itemId, bool enablePreCompletion = false, vector *inConstraints = NULL, + XuiCraftingTask(Tutorial *tutorial, int descriptionId, int itemId, bool enablePreCompletion = false, vector *inConstraints = nullptr, bool bShowMinimumTime=false, bool bAllowFade=true, bool m_bTaskReminders=true ) : TutorialTask(tutorial, descriptionId, enablePreCompletion, inConstraints, bShowMinimumTime, bAllowFade, m_bTaskReminders ), m_item(itemId), diff --git a/Minecraft.Client/Common/UI/IUIController.h b/Minecraft.Client/Common/UI/IUIController.h index 3040c2ccd..35a808c5d 100644 --- a/Minecraft.Client/Common/UI/IUIController.h +++ b/Minecraft.Client/Common/UI/IUIController.h @@ -12,7 +12,7 @@ public: virtual void StartReloadSkinThread() = 0; virtual bool IsReloadingSkin() = 0; virtual void CleanUpSkinReload() = 0; - virtual bool NavigateToScene(int iPad, EUIScene scene, void *initData = NULL, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD) = 0; + virtual bool NavigateToScene(int iPad, EUIScene scene, void *initData = nullptr, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD) = 0; virtual bool NavigateBack(int iPad, bool forceUsePad = false, EUIScene eScene = eUIScene_COUNT, EUILayer eLayer = eUILayer_COUNT) = 0; virtual void CloseUIScenes(int iPad, bool forceIPad = false) = 0; virtual void CloseAllPlayersScenes() = 0; diff --git a/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.cpp index e55f207d4..7502d6bf2 100644 --- a/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.cpp @@ -2,6 +2,7 @@ #include "IUIScene_AbstractContainerMenu.h" +#include "UI.h" #include "..\..\..\Minecraft.World\net.minecraft.world.inventory.h" #include "..\..\..\Minecraft.World\net.minecraft.world.item.h" #include "..\..\..\Minecraft.World\net.minecraft.world.item.crafting.h" @@ -21,9 +22,9 @@ SavedInventoryCursorPos g_savedInventoryCursorPos = { 0.0f, 0.0f, false }; IUIScene_AbstractContainerMenu::IUIScene_AbstractContainerMenu() { - m_menu = NULL; + m_menu = nullptr; m_autoDeleteMenu = false; - m_lastPointerLabelSlot = NULL; + m_lastPointerLabelSlot = nullptr; m_pointerPos.x = 0.0f; m_pointerPos.y = 0.0f; @@ -41,7 +42,7 @@ IUIScene_AbstractContainerMenu::~IUIScene_AbstractContainerMenu() void IUIScene_AbstractContainerMenu::Initialize(int iPad, AbstractContainerMenu* menu, bool autoDeleteMenu, int startIndex,ESceneSection firstSection,ESceneSection maxSection, bool bNavigateBack) { - assert( menu != NULL ); + assert( menu != nullptr ); m_menu = menu; m_autoDeleteMenu = autoDeleteMenu; @@ -267,10 +268,10 @@ void IUIScene_AbstractContainerMenu::UpdateTooltips() void IUIScene_AbstractContainerMenu::onMouseTick() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[getPad()] != NULL) + if( pMinecraft->localgameModes[getPad()] != nullptr) { Tutorial *tutorial = pMinecraft->localgameModes[getPad()]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { if(ui.IsTutorialVisible(getPad()) && !tutorial->isInputAllowed(ACTION_MENU_UP)) { @@ -296,8 +297,8 @@ void IUIScene_AbstractContainerMenu::onMouseTick() int iPad = getPad(); bool bStickInput = false; - float fInputX = InputManager.GetJoypadStick_LX( iPad, false )*((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InMenu)/100.0f); // apply the sensitivity - float fInputY = InputManager.GetJoypadStick_LY( iPad, false )*((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InMenu)/100.0f); // apply the sensitivity + float fInputX = InputManager.GetJoypadStick_LX( iPad, false )*(static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InMenu))/100.0f); // apply the sensitivity + float fInputY = InputManager.GetJoypadStick_LY( iPad, false )*(static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InMenu))/100.0f); // apply the sensitivity #ifdef __ORBIS__ // should have sensitivity for the touchpad @@ -406,7 +407,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() if ( m_iConsectiveInputTicks < MAX_INPUT_TICKS_FOR_SCALING ) { ++m_iConsectiveInputTicks; - fInputScale = ( (float)( m_iConsectiveInputTicks) / (float)(MAX_INPUT_TICKS_FOR_SCALING) ); + fInputScale = ( static_cast(m_iConsectiveInputTicks) / static_cast((MAX_INPUT_TICKS_FOR_SCALING)) ); } #ifdef TAP_DETECTION else if ( m_iConsectiveInputTicks < MAX_INPUT_TICKS_FOR_TAPPING ) @@ -481,25 +482,14 @@ void IUIScene_AbstractContainerMenu::onMouseTick() #endif #ifdef _WINDOWS64 - if (!g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsKBMActive()) + if (iPad == 0 && !g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsKBMActive()) { int deltaX = g_KBMInput.GetMouseDeltaX(); int deltaY = g_KBMInput.GetMouseDeltaY(); - - extern HWND g_hWnd; - RECT rc; - GetClientRect(g_hWnd, &rc); - int winW = rc.right - rc.left; - int winH = rc.bottom - rc.top; - - if (winW > 0 && winH > 0) - { - float scaleX = (float)getMovieWidth() / (float)winW; - float scaleY = (float)getMovieHeight() / (float)winH; - - vPointerPos.x += (float)deltaX * scaleX; - vPointerPos.y += (float)deltaY * scaleY; - } + float scaleX, scaleY; + getMouseToSWFScale(scaleX, scaleY); + vPointerPos.x += static_cast(deltaX) * scaleX; + vPointerPos.y += static_cast(deltaY) * scaleY; if (deltaX != 0 || deltaY != 0) { @@ -527,7 +517,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() } else if ( eSectionUnderPointer == eSectionNone ) { - ESceneSection eSection = ( ESceneSection )( iSection ); + ESceneSection eSection = static_cast(iSection); // Get position of this section. UIVec2D sectionPos; @@ -758,17 +748,17 @@ void IUIScene_AbstractContainerMenu::onMouseTick() // What are we carrying on pointer. shared_ptr player = Minecraft::GetInstance()->localplayers[getPad()]; shared_ptr carriedItem = nullptr; - if(player != NULL) carriedItem = player->inventory->getCarried(); + if(player != nullptr) carriedItem = player->inventory->getCarried(); shared_ptr slotItem = nullptr; - Slot *slot = NULL; + Slot *slot = nullptr; int slotIndex = 0; if(bPointerIsOverSlot) { slotIndex = iNewSlotIndex + getSectionStartOffset( eSectionUnderPointer ); slot = m_menu->getSlot(slotIndex); } - bool bIsItemCarried = carriedItem != NULL; + bool bIsItemCarried = carriedItem != nullptr; int iCarriedCount = 0; bool bCarriedIsSameAsSlot = false; // Indicates if same item is carried on pointer as is in slot under pointer. if ( bIsItemCarried ) @@ -788,7 +778,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() if ( bPointerIsOverSlot ) { slotItem = slot->getItem(); - bSlotHasItem = slotItem != NULL; + bSlotHasItem = slotItem != nullptr; if ( bSlotHasItem ) { iSlotCount = slotItem->GetCount(); @@ -829,13 +819,13 @@ void IUIScene_AbstractContainerMenu::onMouseTick() { vector *desc = GetSectionHoverText(eSectionUnderPointer); SetPointerText(desc, false); - m_lastPointerLabelSlot = NULL; + m_lastPointerLabelSlot = nullptr; delete desc; } else { - SetPointerText(NULL, false); - m_lastPointerLabelSlot = NULL; + SetPointerText(nullptr, false); + m_lastPointerLabelSlot = nullptr; } EToolTipItem buttonA, buttonX, buttonY, buttonRT, buttonBack; @@ -1021,7 +1011,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() // Get the info on this item. shared_ptr item = getSlotItem(eSectionUnderPointer, iNewSlotIndex); bool bValidFuel = FurnaceTileEntity::isFuel(item); - bool bValidIngredient = FurnaceRecipes::getInstance()->getResult(item->getItem()->id) != NULL; + bool bValidIngredient = FurnaceRecipes::getInstance()->getResult(item->getItem()->id) != nullptr; if(bValidIngredient) { @@ -1036,7 +1026,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() } else { - if(FurnaceRecipes::getInstance()->getResult(item->id)==NULL) + if(FurnaceRecipes::getInstance()->getResult(item->id)==nullptr) { buttonY = eToolTipQuickMove; } @@ -1076,7 +1066,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick() } else { - if(FurnaceRecipes::getInstance()->getResult(item->id)==NULL) + if(FurnaceRecipes::getInstance()->getResult(item->id)==nullptr) { buttonY = eToolTipQuickMove; } @@ -1308,10 +1298,8 @@ void IUIScene_AbstractContainerMenu::onMouseTick() } } - vPointerPos.x = floor(vPointerPos.x); - vPointerPos.x += ( (int)vPointerPos.x%2); - vPointerPos.y = floor(vPointerPos.y); - vPointerPos.y += ( (int)vPointerPos.y%2); + vPointerPos.x = static_cast(floor(vPointerPos.x + 0.5f)); + vPointerPos.y = static_cast(floor(vPointerPos.y + 0.5f)); m_pointerPos = vPointerPos; adjustPointerForSafeZone(); @@ -1322,10 +1310,10 @@ bool IUIScene_AbstractContainerMenu::handleKeyDown(int iPad, int iAction, bool b bool bHandled = false; Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[getPad()] != NULL ) + if( pMinecraft->localgameModes[getPad()] != nullptr ) { Tutorial *tutorial = pMinecraft->localgameModes[getPad()]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { tutorial->handleUIInput(iAction); if(ui.IsTutorialVisible(getPad()) && !tutorial->isInputAllowed(iAction)) @@ -1527,20 +1515,20 @@ bool IUIScene_AbstractContainerMenu::handleKeyDown(int iPad, int iAction, bool b if ( bSlotHasItem ) { shared_ptr item = getSlotItem(m_eCurrSection, currentIndex); - if( Minecraft::GetInstance()->localgameModes[iPad] != NULL ) + if( Minecraft::GetInstance()->localgameModes[iPad] != nullptr ) { Tutorial::PopupMessageDetails *message = new Tutorial::PopupMessageDetails; message->m_messageId = item->getUseDescriptionId(); - if(Item::items[item->id] != NULL) message->m_titleString = Item::items[item->id]->getHoverName(item); + if(Item::items[item->id] != nullptr) message->m_titleString = Item::items[item->id]->getHoverName(item); message->m_titleId = item->getDescriptionId(); message->m_icon = item->id; message->m_iAuxVal = item->getAuxValue(); message->m_forceDisplay = true; - TutorialMode *gameMode = (TutorialMode *)Minecraft::GetInstance()->localgameModes[iPad]; - gameMode->getTutorial()->setMessage(NULL, message); + TutorialMode *gameMode = static_cast(Minecraft::GetInstance()->localgameModes[iPad]); + gameMode->getTutorial()->setMessage(nullptr, message); ui.PlayUISFX(eSFX_Press); } } @@ -1642,7 +1630,7 @@ void IUIScene_AbstractContainerMenu::handleSlotListClicked(ESceneSection eSectio void IUIScene_AbstractContainerMenu::slotClicked(int slotId, int buttonNum, bool quickKey) { // 4J Stu - Removed this line as unused - //if (slot != NULL) slotId = slot->index; + //if (slot != nullptr) slotId = slot->index; Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->localgameModes[getPad()]->handleInventoryMouseClick(m_menu->containerId, slotId, buttonNum, quickKey, pMinecraft->localplayers[getPad()] ); @@ -1659,7 +1647,7 @@ int IUIScene_AbstractContainerMenu::getCurrentIndex(ESceneSection eSection) bool IUIScene_AbstractContainerMenu::IsSameItemAs(shared_ptr itemA, shared_ptr itemB) { - if(itemA == NULL || itemB == NULL) return false; + if(itemA == nullptr || itemB == nullptr) return false; return (itemA->id == itemB->id && (!itemB->isStackedByData() || itemB->getAuxValue() == itemA->getAuxValue()) && ItemInstance::tagMatches(itemB, itemA) ); } @@ -1668,7 +1656,7 @@ int IUIScene_AbstractContainerMenu::GetEmptyStackSpace(Slot *slot) { int iResult = 0; - if(slot != NULL && slot->hasItem()) + if(slot != nullptr && slot->hasItem()) { shared_ptr item = slot->getItem(); if ( item->isStackable() ) @@ -1687,7 +1675,7 @@ int IUIScene_AbstractContainerMenu::GetEmptyStackSpace(Slot *slot) vector *IUIScene_AbstractContainerMenu::GetItemDescription(Slot *slot) { - if(slot == NULL) return NULL; + if(slot == nullptr) return nullptr; vector *lines = slot->getItem()->getHoverText(nullptr, false); @@ -1707,5 +1695,5 @@ vector *IUIScene_AbstractContainerMenu::GetItemDescription(Slot *slo vector *IUIScene_AbstractContainerMenu::GetSectionHoverText(ESceneSection eSection) { - return NULL; + return nullptr; } diff --git a/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.h b/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.h index 4877cfce8..718a2d447 100644 --- a/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.h +++ b/Minecraft.Client/Common/UI/IUIScene_AbstractContainerMenu.h @@ -277,4 +277,5 @@ public: virtual int getPad() = 0; virtual int getMovieWidth() = 0; virtual int getMovieHeight() = 0; + virtual void getMouseToSWFScale(float &scaleX, float &scaleY) = 0; }; diff --git a/Minecraft.Client/Common/UI/IUIScene_AnvilMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_AnvilMenu.cpp index 10d1bcc41..1e6fa6fa0 100644 --- a/Minecraft.Client/Common/UI/IUIScene_AnvilMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_AnvilMenu.cpp @@ -10,7 +10,7 @@ IUIScene_AnvilMenu::IUIScene_AnvilMenu() { m_inventory = nullptr; - m_repairMenu = NULL; + m_repairMenu = nullptr; m_itemName = L""; } @@ -231,7 +231,7 @@ void IUIScene_AnvilMenu::handleTick() void IUIScene_AnvilMenu::updateItemName() { Slot *slot = m_repairMenu->getSlot(AnvilMenu::INPUT_SLOT); - if (slot != NULL && slot->hasItem()) + if (slot != nullptr && slot->hasItem()) { if (!slot->getItem()->hasCustomHoverName() && m_itemName.compare(slot->getItem()->getHoverName())==0) { @@ -245,7 +245,7 @@ void IUIScene_AnvilMenu::updateItemName() ByteArrayOutputStream baos; DataOutputStream dos(&baos); dos.writeUTF(m_itemName); - Minecraft::GetInstance()->localplayers[getPad()]->connection->send(shared_ptr(new CustomPayloadPacket(CustomPayloadPacket::SET_ITEM_NAME_PACKET, baos.toByteArray()))); + Minecraft::GetInstance()->localplayers[getPad()]->connection->send(std::make_shared(CustomPayloadPacket::SET_ITEM_NAME_PACKET, baos.toByteArray())); } void IUIScene_AnvilMenu::refreshContainer(AbstractContainerMenu *container, vector > *items) @@ -257,10 +257,10 @@ void IUIScene_AnvilMenu::slotChanged(AbstractContainerMenu *container, int slotI { if (slotIndex == AnvilMenu::INPUT_SLOT) { - m_itemName = item == NULL ? L"" : item->getHoverName(); + m_itemName = item == nullptr ? L"" : item->getHoverName(); setEditNameValue(m_itemName); - setEditNameEditable(item != NULL); - if (item != NULL) + setEditNameEditable(item != nullptr); + if (item != nullptr) { updateItemName(); } diff --git a/Minecraft.Client/Common/UI/IUIScene_BeaconMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_BeaconMenu.cpp index bb13deb89..3dede3d94 100644 --- a/Minecraft.Client/Common/UI/IUIScene_BeaconMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_BeaconMenu.cpp @@ -216,13 +216,13 @@ void IUIScene_BeaconMenu::handleOtherClicked(int iPad, ESceneSection eSection, i { case eSectionBeaconConfirm: { - if( (m_beacon->getItem(0) == NULL) || (m_beacon->getPrimaryPower() <= 0) ) return; + if( (m_beacon->getItem(0) == nullptr) || (m_beacon->getPrimaryPower() <= 0) ) return; ByteArrayOutputStream baos; DataOutputStream dos(&baos); dos.writeInt(m_beacon->getPrimaryPower()); dos.writeInt(m_beacon->getSecondaryPower()); - Minecraft::GetInstance()->localplayers[getPad()]->connection->send(shared_ptr(new CustomPayloadPacket(CustomPayloadPacket::SET_BEACON_PACKET, baos.toByteArray()))); + Minecraft::GetInstance()->localplayers[getPad()]->connection->send(std::make_shared(CustomPayloadPacket::SET_BEACON_PACKET, baos.toByteArray())); if (m_beacon->getPrimaryPower() > 0) { @@ -286,7 +286,7 @@ void IUIScene_BeaconMenu::handleTick() for (int c = 0; c < count; c++) { - if(BeaconTileEntity::BEACON_EFFECTS[tier][c] == NULL) continue; + if(BeaconTileEntity::BEACON_EFFECTS[tier][c] == nullptr) continue; int effectId = BeaconTileEntity::BEACON_EFFECTS[tier][c]->id; int icon = BeaconTileEntity::BEACON_EFFECTS[tier][c]->getIcon(); @@ -315,7 +315,7 @@ void IUIScene_BeaconMenu::handleTick() for (int c = 0; c < count - 1; c++) { - if(BeaconTileEntity::BEACON_EFFECTS[tier][c] == NULL) continue; + if(BeaconTileEntity::BEACON_EFFECTS[tier][c] == nullptr) continue; int effectId = BeaconTileEntity::BEACON_EFFECTS[tier][c]->id; int icon = BeaconTileEntity::BEACON_EFFECTS[tier][c]->getIcon(); @@ -355,7 +355,7 @@ void IUIScene_BeaconMenu::handleTick() } } - SetConfirmButtonEnabled( (m_beacon->getItem(0) != NULL) && (m_beacon->getPrimaryPower() > 0) ); + SetConfirmButtonEnabled( (m_beacon->getItem(0) != nullptr) && (m_beacon->getPrimaryPower() > 0) ); } int IUIScene_BeaconMenu::GetId(int tier, int effectId) @@ -365,7 +365,7 @@ int IUIScene_BeaconMenu::GetId(int tier, int effectId) vector *IUIScene_BeaconMenu::GetSectionHoverText(ESceneSection eSection) { - vector *desc = NULL; + vector *desc = nullptr; switch(eSection) { case eSectionBeaconSecondaryTwo: diff --git a/Minecraft.Client/Common/UI/IUIScene_CommandBlockMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_CommandBlockMenu.cpp index 4371b4e58..3af01678e 100644 --- a/Minecraft.Client/Common/UI/IUIScene_CommandBlockMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_CommandBlockMenu.cpp @@ -20,6 +20,6 @@ void IUIScene_CommandBlockMenu::ConfirmButtonClicked() dos.writeInt(m_commandBlock->z); dos.writeUTF(GetCommand()); - Minecraft::GetInstance()->localplayers[GetPad()]->connection->send(shared_ptr(new CustomPayloadPacket(CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET, baos.toByteArray()))); + Minecraft::GetInstance()->localplayers[GetPad()]->connection->send(std::make_shared(CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET, baos.toByteArray())); } diff --git a/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp index fc012be3f..6fddece9c 100644 --- a/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp @@ -6,6 +6,8 @@ #include "..\..\LocalPlayer.h" #include "IUIScene_CraftingMenu.h" +#include "UI.h" + Recipy::_eGroupType IUIScene_CraftingMenu::m_GroupTypeMapping4GridA[IUIScene_CraftingMenu::m_iMaxGroup2x2]= { Recipy::eGroupType_Structure, @@ -154,10 +156,10 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[getPad()] != NULL ) + if( pMinecraft->localgameModes[getPad()] != nullptr ) { Tutorial *tutorial = pMinecraft->localgameModes[getPad()]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { tutorial->handleUIInput(iAction); if(ui.IsTutorialVisible(getPad()) && !tutorial->isInputAllowed(iAction)) @@ -211,10 +213,10 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) shared_ptr pTempItemInst=pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); //int iIcon=pTempItemInst->getItem()->getIcon(pTempItemInst->getAuxValue()); - if( pMinecraft->localgameModes[iPad] != NULL) + if( pMinecraft->localgameModes[iPad] != nullptr) { Tutorial *tutorial = pMinecraft->localgameModes[iPad]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { tutorial->onCrafted(pTempItemInst); } @@ -247,10 +249,10 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) shared_ptr pTempItemInst=pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); //int iIcon=pTempItemInst->getItem()->getIcon(pTempItemInst->getAuxValue()); - if( pMinecraft->localgameModes[iPad] != NULL ) + if( pMinecraft->localgameModes[iPad] != nullptr ) { Tutorial *tutorial = pMinecraft->localgameModes[iPad]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { tutorial->createItemSelected(pTempItemInst, pRecipeIngredientsRequired[iRecipe].bCanMake[iPad]); } @@ -288,12 +290,12 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) } // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when crafting Cake - if (ingItemInst != NULL) + if (ingItemInst != nullptr) { if (ingItemInst->getItem()->hasCraftingRemainingItem()) { // replace item with remaining result - m_pPlayer->inventory->add( shared_ptr( new ItemInstance(ingItemInst->getItem()->getCraftingRemainingItem()) ) ); + m_pPlayer->inventory->add(std::make_shared(ingItemInst->getItem()->getCraftingRemainingItem())); } } @@ -608,7 +610,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // dump out the inventory /* for (unsigned int k = 0; k < m_pPlayer->inventory->items.length; k++) { - if (m_pPlayer->inventory->items[k] != NULL) + if (m_pPlayer->inventory->items[k] != nullptr) { wstring itemstring=m_pPlayer->inventory->items[k]->toString(); @@ -620,15 +622,15 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() */ RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); - int iRecipeC=(int)recipes->size(); + int iRecipeC=static_cast(recipes->size()); auto itRecipe = recipes->begin(); // dump out the recipe products // for (int i = 0; i < iRecipeC; i++) // { - // shared_ptr pTempItemInst=pRecipeIngredientsRequired[i].pRecipy->assemble(NULL); - // if (pTempItemInst != NULL) + // shared_ptr pTempItemInst=pRecipeIngredientsRequired[i].pRecipy->assemble(nullptr); + // if (pTempItemInst != nullptr) // { // wstring itemstring=pTempItemInst->toString(); // @@ -683,7 +685,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // Does the player have this ingredient? for (unsigned int k = 0; k < m_pPlayer->inventory->items.length; k++) { - if (m_pPlayer->inventory->items[k] != NULL) + if (m_pPlayer->inventory->items[k] != nullptr) { // 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]) && @@ -703,7 +705,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() for(unsigned int l=0;linventory->items.length;l++) { - if (m_pPlayer->inventory->items[l] != NULL) + if (m_pPlayer->inventory->items[l] != nullptr) { if( (m_pPlayer->inventory->items[l]->id == pRecipeIngredientsRequired[i].iIngIDA[j]) && @@ -1071,7 +1073,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() int iAuxVal=pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]; Item *item = Item::items[id]; - shared_ptr itemInst= shared_ptr(new ItemInstance(item,pRecipeIngredientsRequired[iRecipe].iIngValA[i],iAuxVal)); + shared_ptr itemInst= std::make_shared(item, pRecipeIngredientsRequired[iRecipe].iIngValA[i], iAuxVal); // 4J-PB - a very special case - the bed can use any kind of wool, so we can't use the item description // and the same goes for the painting @@ -1156,7 +1158,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() { iAuxVal = 1; } - shared_ptr itemInst= shared_ptr(new ItemInstance(id,1,iAuxVal)); + shared_ptr itemInst= std::make_shared(id, 1, iAuxVal); setIngredientSlotItem(getPad(),index,itemInst); // show the ingredients we don't have if we can't make the recipe if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L< > IUIScene_CreativeMenu::categoryGroups[eCreativeInventoryGroupsCount]; @@ -21,7 +22,6 @@ vector< shared_ptr > IUIScene_CreativeMenu::categoryGroups[eCreati #define ITEM_AUX(id, aux) list->push_back( shared_ptr(new ItemInstance(id, 1, aux)) ); #define DEF(index) list = &categoryGroups[index]; - void IUIScene_CreativeMenu::staticCtor() { vector< shared_ptr > *list; @@ -488,14 +488,14 @@ void IUIScene_CreativeMenu::staticCtor() for(unsigned int i = 0; i < Enchantment::enchantments.length; ++i) { Enchantment *enchantment = Enchantment::enchantments[i]; - if (enchantment == NULL || enchantment->category == NULL) continue; + if (enchantment == nullptr || enchantment->category == nullptr) continue; list->push_back(Item::enchantedBook->createForEnchantment(new EnchantmentInstance(enchantment, enchantment->getMaxLevel()))); } #ifndef _CONTENT_PACKAGE if(app.DebugSettingsOn()) { - shared_ptr debugSword = shared_ptr(new ItemInstance(Item::sword_diamond_Id, 1, 0)); + shared_ptr debugSword = std::make_shared(Item::sword_diamond_Id, 1, 0); debugSword->enchant( Enchantment::damageBonus, 50 ); debugSword->setHoverName(L"Sword of Debug"); list->push_back(debugSword); @@ -673,7 +673,7 @@ void IUIScene_CreativeMenu::staticCtor() #ifndef _CONTENT_PACKAGE ECreative_Inventory_Groups decorationsGroup[] = {eCreativeInventory_Decoration}; ECreative_Inventory_Groups debugDecorationsGroup[] = {eCreativeInventory_ArtToolsDecorations}; - specs[eCreativeInventoryTab_Decorations] = new TabSpec(L"Decoration", IDS_GROUPNAME_DECORATIONS, 1, decorationsGroup, 0, NULL, 1, debugDecorationsGroup); + specs[eCreativeInventoryTab_Decorations] = new TabSpec(L"Decoration", IDS_GROUPNAME_DECORATIONS, 1, decorationsGroup, 0, nullptr, 1, debugDecorationsGroup); #else ECreative_Inventory_Groups decorationsGroup[] = {eCreativeInventory_Decoration}; specs[eCreativeInventoryTab_Decorations] = new TabSpec(L"Decoration", IDS_GROUPNAME_DECORATIONS, 1, decorationsGroup); @@ -707,7 +707,7 @@ void IUIScene_CreativeMenu::staticCtor() #ifndef _CONTENT_PACKAGE ECreative_Inventory_Groups miscGroup[] = {eCreativeInventory_Misc}; ECreative_Inventory_Groups debugMiscGroup[] = {eCreativeInventory_ArtToolsMisc}; - specs[eCreativeInventoryTab_Misc] = new TabSpec(L"Misc", IDS_GROUPNAME_MISCELLANEOUS, 1, miscGroup, 0, NULL, 1, debugMiscGroup); + specs[eCreativeInventoryTab_Misc] = new TabSpec(L"Misc", IDS_GROUPNAME_MISCELLANEOUS, 1, miscGroup, 0, nullptr, 1, debugMiscGroup); #else ECreative_Inventory_Groups miscGroup[] = {eCreativeInventory_Misc}; specs[eCreativeInventoryTab_Misc] = new TabSpec(L"Misc", IDS_GROUPNAME_MISCELLANEOUS, 1, miscGroup); @@ -766,12 +766,12 @@ void IUIScene_CreativeMenu::ScrollBar(UIVec2D pointerPos) // 4J JEV - Tab Spec Struct -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*/) +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 /*= nullptr*/) : m_icon(icon), m_descriptionId(descriptionId), m_staticGroupsCount(staticGroupsCount), m_dynamicGroupsCount(dynamicGroupsCount), m_debugGroupsCount(debugGroupsCount) { m_pages = 0; - m_staticGroupsA = NULL; + m_staticGroupsA = nullptr; unsigned int dynamicItems = 0; m_staticItems = 0; @@ -786,7 +786,7 @@ IUIScene_CreativeMenu::TabSpec::TabSpec(LPCWSTR icon, int descriptionId, int sta } } - m_debugGroupsA = NULL; + m_debugGroupsA = nullptr; m_debugItems = 0; if(debugGroupsCount > 0) { @@ -798,8 +798,8 @@ IUIScene_CreativeMenu::TabSpec::TabSpec(LPCWSTR icon, int descriptionId, int sta } } - m_dynamicGroupsA = NULL; - if(dynamicGroupsCount > 0 && dynamicGroups != NULL) + m_dynamicGroupsA = nullptr; + if(dynamicGroupsCount > 0 && dynamicGroups != nullptr) { m_dynamicGroupsA = new ECreative_Inventory_Groups[dynamicGroupsCount]; for(int i = 0; i < dynamicGroupsCount; ++i) @@ -816,9 +816,9 @@ IUIScene_CreativeMenu::TabSpec::TabSpec(LPCWSTR icon, int descriptionId, int sta IUIScene_CreativeMenu::TabSpec::~TabSpec() { - if(m_staticGroupsA != NULL) delete [] m_staticGroupsA; - if(m_dynamicGroupsA != NULL) delete [] m_dynamicGroupsA; - if(m_debugGroupsA != NULL) delete [] m_debugGroupsA; + if(m_staticGroupsA != nullptr) delete [] m_staticGroupsA; + if(m_dynamicGroupsA != nullptr) delete [] m_dynamicGroupsA; + if(m_debugGroupsA != nullptr) delete [] m_debugGroupsA; } void IUIScene_CreativeMenu::TabSpec::populateMenu(AbstractContainerMenu *menu, int dynamicIndex, unsigned int page) @@ -826,7 +826,7 @@ void IUIScene_CreativeMenu::TabSpec::populateMenu(AbstractContainerMenu *menu, i int lastSlotIndex = 0; // Fill the dynamic group - if(m_dynamicGroupsCount > 0 && m_dynamicGroupsA != NULL) + if(m_dynamicGroupsCount > 0 && m_dynamicGroupsA != nullptr) { for (auto it = categoryGroups[m_dynamicGroupsA[dynamicIndex]].rbegin(); it != categoryGroups[m_dynamicGroupsA[dynamicIndex]].rend() && lastSlotIndex < MAX_SIZE; ++it) { @@ -957,7 +957,7 @@ IUIScene_CreativeMenu::ItemPickerMenu::ItemPickerMenu( shared_ptrsize(); - Slot *slot = NULL; + Slot *slot = nullptr; for (int i = 0; i < TabSpec::MAX_SIZE; i++) { // 4J JEV - These values get set by addSlot anyway. @@ -1036,11 +1036,11 @@ bool IUIScene_CreativeMenu::handleValidKeyPress(int iPad, int buttonNum, BOOL qu { shared_ptr newItem = m_menu->getSlot(i)->getItem(); - if(newItem != NULL) + if(newItem != nullptr) { m_menu->getSlot(i)->set(nullptr); // call this function to synchronize multiplayer item bar - pMinecraft->localgameModes[iPad]->handleCreativeModeItemAdd(nullptr, i - (int)m_menu->slots.size() + 9 + InventoryMenu::USE_ROW_SLOT_START); + pMinecraft->localgameModes[iPad]->handleCreativeModeItemAdd(nullptr, i - static_cast(m_menu->slots.size()) + 9 + InventoryMenu::USE_ROW_SLOT_START); } } return true; @@ -1054,7 +1054,7 @@ void IUIScene_CreativeMenu::handleOutsideClicked(int iPad, int buttonNum, BOOL q Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr playerInventory = pMinecraft->localplayers[iPad]->inventory; - if (playerInventory->getCarried() != NULL) + if (playerInventory->getCarried() != nullptr) { if (buttonNum == 0) { @@ -1082,8 +1082,8 @@ void IUIScene_CreativeMenu::handleAdditionalKeyPress(int iAction) // Fall through intentional case ACTION_MENU_RIGHT_SCROLL: { - ECreativeInventoryTabs tab = (ECreativeInventoryTabs)(m_curTab + dir); - if (tab < 0) tab = (ECreativeInventoryTabs)(eCreativeInventoryTab_COUNT - 1); + ECreativeInventoryTabs tab = static_cast(m_curTab + dir); + if (tab < 0) tab = static_cast(eCreativeInventoryTab_COUNT - 1); if (tab >= eCreativeInventoryTab_COUNT) tab = eCreativeInventoryTab_BuildingBlocks; switchTab(tab); ui.PlayUISFX(eSFX_Focus); @@ -1143,7 +1143,7 @@ void IUIScene_CreativeMenu::handleSlotListClicked(ESceneSection eSection, int bu shared_ptr playerInventory = pMinecraft->localplayers[getPad()]->inventory; shared_ptr carried = playerInventory->getCarried(); shared_ptr clicked = m_menu->getSlot(currentIndex)->getItem(); - if (clicked != NULL) + if (clicked != nullptr) { playerInventory->setCarried(ItemInstance::clone(clicked)); carried = playerInventory->getCarried(); @@ -1176,7 +1176,7 @@ void IUIScene_CreativeMenu::handleSlotListClicked(ESceneSection eSection, int bu m_menu->clicked(currentIndex, buttonNum, quickKeyHeld?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, pMinecraft->localplayers[getPad()]); shared_ptr newItem = m_menu->getSlot(currentIndex)->getItem(); // call this function to synchronize multiplayer item bar - pMinecraft->localgameModes[getPad()]->handleCreativeModeItemAdd(newItem, currentIndex - (int)m_menu->slots.size() + 9 + InventoryMenu::USE_ROW_SLOT_START); + pMinecraft->localgameModes[getPad()]->handleCreativeModeItemAdd(newItem, currentIndex - static_cast(m_menu->slots.size()) + 9 + InventoryMenu::USE_ROW_SLOT_START); if(m_bCarryingCreativeItem) { @@ -1224,7 +1224,7 @@ bool IUIScene_CreativeMenu::getEmptyInventorySlot(shared_ptr item, for(unsigned int i = TabSpec::MAX_SIZE; i < TabSpec::MAX_SIZE + 9; ++i) { shared_ptr slotItem = m_menu->getSlot(i)->getItem(); - if( slotItem != NULL && slotItem->sameItemWithTags(item) && (slotItem->GetCount() + item->GetCount() <= item->getMaxStackSize() )) + if( slotItem != nullptr && slotItem->sameItemWithTags(item) && (slotItem->GetCount() + item->GetCount() <= item->getMaxStackSize() )) { sameItemFound = true; slotX = i - TabSpec::MAX_SIZE; @@ -1237,7 +1237,7 @@ bool IUIScene_CreativeMenu::getEmptyInventorySlot(shared_ptr item, // Find an empty slot for(unsigned int i = TabSpec::MAX_SIZE; i < TabSpec::MAX_SIZE + 9; ++i) { - if( m_menu->getSlot(i)->getItem() == NULL ) + if( m_menu->getSlot(i)->getItem() == nullptr ) { slotX = i - TabSpec::MAX_SIZE; emptySlotFound = true; @@ -1316,7 +1316,7 @@ void IUIScene_CreativeMenu::BuildFirework(vector > *lis // diamonds give trails if (trail) expTag->putBoolean(FireworksItem::TAG_E_TRAIL, true); - intArray colorArray(colors.size()); + intArray colorArray(static_cast(colors.size())); for (int i = 0; i < colorArray.length; i++) { colorArray[i] = colors.at(i); @@ -1335,7 +1335,7 @@ void IUIScene_CreativeMenu::BuildFirework(vector > *lis vector colors; colors.push_back(DyePowderItem::COLOR_RGB[fadeColor]); - intArray colorArray(colors.size()); + intArray colorArray(static_cast(colors.size())); for (int i = 0; i < colorArray.length; i++) { colorArray[i] = colors.at(i); @@ -1350,7 +1350,7 @@ void IUIScene_CreativeMenu::BuildFirework(vector > *lis shared_ptr firework; { - firework = shared_ptr( new ItemInstance(Item::fireworks) ); + firework = std::make_shared(Item::fireworks); CompoundTag *itemTag = new CompoundTag(); CompoundTag *fireTag = new CompoundTag(FireworksItem::TAG_FIREWORKS); ListTag *expTags = new ListTag(FireworksItem::TAG_EXPLOSIONS); @@ -1358,7 +1358,7 @@ void IUIScene_CreativeMenu::BuildFirework(vector > *lis expTags->add(expTag); fireTag->put(FireworksItem::TAG_EXPLOSIONS, expTags); - fireTag->putByte(FireworksItem::TAG_FLIGHT, (byte) sulphur); + fireTag->putByte(FireworksItem::TAG_FLIGHT, static_cast(sulphur)); itemTag->put(FireworksItem::TAG_FIREWORKS, fireTag); diff --git a/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.h b/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.h index 64b78029b..864fb5606 100644 --- a/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.h +++ b/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.h @@ -69,7 +69,7 @@ public: unsigned int m_debugItems; public: - TabSpec( LPCWSTR icon, int descriptionId, int staticGroupsCount, ECreative_Inventory_Groups *staticGroups, int dynamicGroupsCount = 0, ECreative_Inventory_Groups *dynamicGroups = NULL, int debugGroupsCount = 0, ECreative_Inventory_Groups *debugGroups = NULL ); + TabSpec( LPCWSTR icon, int descriptionId, int staticGroupsCount, ECreative_Inventory_Groups *staticGroups, int dynamicGroupsCount = 0, ECreative_Inventory_Groups *dynamicGroups = nullptr, int debugGroupsCount = 0, ECreative_Inventory_Groups *debugGroups = nullptr ); ~TabSpec(); void populateMenu(AbstractContainerMenu *menu, int dynamicIndex, unsigned int page); diff --git a/Minecraft.Client/Common/UI/IUIScene_EnchantingMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_EnchantingMenu.cpp index c73f7dc5c..fbbf7c24f 100644 --- a/Minecraft.Client/Common/UI/IUIScene_EnchantingMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_EnchantingMenu.cpp @@ -181,5 +181,5 @@ bool IUIScene_EnchantingMenu::IsSectionSlotList( ESceneSection eSection ) EnchantmentMenu *IUIScene_EnchantingMenu::getMenu() { - return (EnchantmentMenu *)m_menu; + return static_cast(m_menu); } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/IUIScene_HUD.cpp b/Minecraft.Client/Common/UI/IUIScene_HUD.cpp index 03adbd2c2..d2754789c 100644 --- a/Minecraft.Client/Common/UI/IUIScene_HUD.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_HUD.cpp @@ -7,6 +7,8 @@ #include "..\..\..\Minecraft.World\net.minecraft.world.entity.monster.h" #include "IUIScene_HUD.h" +#include "UI.h" + IUIScene_HUD::IUIScene_HUD() { m_lastActiveSlot = -1; @@ -79,7 +81,7 @@ void IUIScene_HUD::updateFrameTick() { //SetRidingHorse(false, 0); shared_ptr riding = pMinecraft->localplayers[iPad]->riding; - if(riding == NULL) + if(riding == nullptr) { SetRidingHorse(false, false, 0); } @@ -146,8 +148,8 @@ void IUIScene_HUD::updateFrameTick() { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -156,7 +158,7 @@ void IUIScene_HUD::updateFrameTick() } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else @@ -166,12 +168,12 @@ void IUIScene_HUD::updateFrameTick() { ucAlpha=15; } - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } SetOpacity(fVal); bool bDisplayGui=app.GetGameStarted() && !ui.GetMenuDisplayed(iPad) && !(app.GetXuiAction(iPad)==eAppAction_AutosaveSaveGameCapturedThumbnail) && app.GetGameSettings(iPad,eGameSetting_DisplayHUD)!=0; - if(bDisplayGui && pMinecraft->localplayers[iPad] != NULL) + if(bDisplayGui && pMinecraft->localplayers[iPad] != nullptr) { SetVisible(true); } @@ -193,12 +195,12 @@ void IUIScene_HUD::renderPlayerHealth() // Update health bool blink = pMinecraft->localplayers[iPad]->invulnerableTime / 3 % 2 == 1; if (pMinecraft->localplayers[iPad]->invulnerableTime < 10) blink = false; - int currentHealth = pMinecraft->localplayers[iPad]->getHealth(); - int oldHealth = pMinecraft->localplayers[iPad]->lastHealth; + int currentHealth = static_cast(ceil(pMinecraft->localplayers[iPad]->getHealth())); + int oldHealth = static_cast(ceil(pMinecraft->localplayers[iPad]->lastHealth)); bool bHasPoison = pMinecraft->localplayers[iPad]->hasEffect(MobEffect::poison); bool bHasWither = pMinecraft->localplayers[iPad]->hasEffect(MobEffect::wither); AttributeInstance *maxHealthAttribute = pMinecraft->localplayers[iPad]->getAttribute(SharedMonsterAttributes::MAX_HEALTH); - float maxHealth = (float)maxHealthAttribute->getValue(); + float maxHealth = static_cast(maxHealthAttribute->getValue()); float totalAbsorption = pMinecraft->localplayers[iPad]->getAbsorptionAmount(); // Update armour @@ -219,7 +221,7 @@ void IUIScene_HUD::renderPlayerHealth() shared_ptr riding = pMinecraft->localplayers[iPad]->riding; - if(riding == NULL || riding && !riding->instanceof(eTYPE_LIVINGENTITY)) + if(riding == nullptr || riding && !riding->instanceof(eTYPE_LIVINGENTITY)) { SetRidingHorse(false, false, 0); @@ -242,8 +244,8 @@ void IUIScene_HUD::renderPlayerHealth() if (pMinecraft->localplayers[iPad]->isUnderLiquid(Material::water)) { ShowAir(true); - int count = (int) ceil((pMinecraft->localplayers[iPad]->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY); - int extra = (int) ceil((pMinecraft->localplayers[iPad]->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY) - count; + int count = static_cast(ceil((pMinecraft->localplayers[iPad]->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY)); + int extra = static_cast(ceil((pMinecraft->localplayers[iPad]->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY)) - count; SetAir(count, extra); } else @@ -254,7 +256,7 @@ void IUIScene_HUD::renderPlayerHealth() else if(riding->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr living = dynamic_pointer_cast(riding); - int riderCurrentHealth = (int) ceil(living->getHealth()); + int riderCurrentHealth = static_cast(ceil(living->getHealth())); float maxRiderHealth = living->getMaxHealth(); SetRidingHorse(true, pMinecraft->localplayers[iPad]->isRidingJumpable(), maxRiderHealth); diff --git a/Minecraft.Client/Common/UI/IUIScene_PauseMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_PauseMenu.cpp index ab1767d4f..e88ed08cd 100644 --- a/Minecraft.Client/Common/UI/IUIScene_PauseMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_PauseMenu.cpp @@ -52,7 +52,7 @@ int IUIScene_PauseMenu::ExitGameSaveDialogReturned(void *pParam,int iPad,C4JStor if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) @@ -229,7 +229,7 @@ int IUIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4 { // 4J-PB - need to check this user can access the store bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -248,7 +248,7 @@ int IUIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4 app.DebugPrintf("Texture Pack - %s\n",pchPackName); SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo((char *)pchPackName); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chSkuID[SCE_NP_COMMERCE2_SKU_ID_LEN]; @@ -300,7 +300,7 @@ int IUIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4 DLC_INFO *pDLCInfo=app.GetDLCInfoForProductName((WCHAR *)pDLCPack->getName().c_str()); - StorageManager.InstallOffer(1,(WCHAR *)pDLCInfo->wsProductId.c_str(),NULL,NULL); + StorageManager.InstallOffer(1,(WCHAR *)pDLCInfo->wsProductId.c_str(),nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } @@ -336,7 +336,7 @@ int IUIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4 // need to allow downloads here, or the player would need to quit the game to let the download of a texture pack happen. This might affect the network traffic, since the download could take all the bandwidth... XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } else @@ -352,7 +352,7 @@ int IUIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4 int IUIScene_PauseMenu::SaveWorldThreadProc( LPVOID lpParameter ) { - bool bAutosave=(bool)lpParameter; + bool bAutosave=static_cast(lpParameter); if(bAutosave) { app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_AutoSaveGame); @@ -421,7 +421,7 @@ void IUIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) bool saveStats = true; if (pMinecraft->isClientSide() || g_NetworkManager.IsInSession()) { - if(lpParameter != NULL ) + if(lpParameter != nullptr ) { // 4J-PB - check if we have lost connection to Live if(ProfileManager.GetLiveConnectionStatus()!=XONLINE_S_LOGON_CONNECTION_ESTABLISHED ) @@ -522,17 +522,17 @@ void IUIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) exitReasonStringId = -1; // 4J - Force a disconnection, this handles the situation that the server has already disconnected - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(false); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(false); - if( pMinecraft->levels[2] != NULL ) pMinecraft->levels[2]->disconnect(false); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(false); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(false); + if( pMinecraft->levels[2] != nullptr ) pMinecraft->levels[2]->disconnect(false); } else { exitReasonStringId = IDS_EXITING_GAME; pMinecraft->progressRenderer->progressStartNoAbort( IDS_EXITING_GAME ); - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(); - if( pMinecraft->levels[2] != NULL ) pMinecraft->levels[2]->disconnect(); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(); + if( pMinecraft->levels[2] != nullptr ) pMinecraft->levels[2]->disconnect(); } // 4J Stu - This only does something if we actually have a server, so don't need to do any other checks @@ -548,7 +548,7 @@ void IUIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) } else { - if(lpParameter != NULL && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad()) ) + if(lpParameter != nullptr && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad()) ) { switch( app.GetDisconnectReason() ) { @@ -625,7 +625,7 @@ void IUIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) { Sleep(1); } - pMinecraft->setLevel(NULL,exitReasonStringId,nullptr,saveStats); + pMinecraft->setLevel(nullptr,exitReasonStringId,nullptr,saveStats); TelemetryManager->Flush(); diff --git a/Minecraft.Client/Common/UI/IUIScene_StartGame.cpp b/Minecraft.Client/Common/UI/IUIScene_StartGame.cpp index d3a9e8f08..735da438a 100644 --- a/Minecraft.Client/Common/UI/IUIScene_StartGame.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_StartGame.cpp @@ -45,7 +45,7 @@ void IUIScene_StartGame::HandleDLCMountingComplete() // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this // REMOVE UNTIL WORKING - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -86,7 +86,7 @@ void IUIScene_StartGame::HandleDLCMountingComplete() // add a TMS request for them app.DebugPrintf("+++ Adding TMSPP request for texture pack data\n"); app.AddTMSPPFileTypeRequest(e_DLC_TexturePackData); - if(m_iConfigA!=NULL) + if(m_iConfigA!=nullptr) { delete m_iConfigA; } @@ -123,7 +123,7 @@ void IUIScene_StartGame::HandleDLCMountingComplete() void IUIScene_StartGame::handleSelectionChanged(F64 selectedId) { - m_iSetTexturePackDescription = (int)selectedId; + m_iSetTexturePackDescription = static_cast(selectedId); if(!m_texturePackDescDisplayed) { @@ -135,13 +135,13 @@ void IUIScene_StartGame::UpdateTexturePackDescription(int index) { TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackByIndex(index); - if(tp==NULL) + if(tp==nullptr) { #if TO_BE_IMPLEMENTED // this is probably a texture pack icon added from TMS DWORD dwBytes=0,dwFileBytes=0; - PBYTE pbData=NULL,pbFileData=NULL; + PBYTE pbData=nullptr,pbFileData=nullptr; CXuiCtrl4JList::LIST_ITEM_INFO ListItem; // get the current index of the list, and then get the data @@ -171,7 +171,7 @@ void IUIScene_StartGame::UpdateTexturePackDescription(int index) } else { - m_texturePackComparison->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); } #endif } @@ -214,7 +214,7 @@ void IUIScene_StartGame::UpdateCurrentTexturePack(int iSlot) TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackByIndex(m_currentTexturePackIndex); // if the texture pack is null, you don't have it yet - if(tp==NULL) + if(tp==nullptr) { #if TO_BE_IMPLEMENTED // Upsell @@ -254,7 +254,7 @@ void IUIScene_StartGame::UpdateCurrentTexturePack(int iSlot) int IUIScene_StartGame::TrialTexturePackWarningReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - IUIScene_StartGame* pScene = (IUIScene_StartGame*)pParam; + IUIScene_StartGame* pScene = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -269,7 +269,7 @@ int IUIScene_StartGame::TrialTexturePackWarningReturned(void *pParam,int iPad,C4 int IUIScene_StartGame::UnlockTexturePackReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - IUIScene_StartGame* pScene = (IUIScene_StartGame*)pParam; + IUIScene_StartGame* pScene = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -279,7 +279,7 @@ int IUIScene_StartGame::UnlockTexturePackReturned(void *pParam,int iPad,C4JStora ULONGLONG ullIndexA[1]; DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(pScene->m_pDLCPack->getPurchaseOfferId()); - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullIndexA[0]=pDLCInfo->ullOfferID_Full; } @@ -289,9 +289,9 @@ int IUIScene_StartGame::UnlockTexturePackReturned(void *pParam,int iPad,C4JStora } - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); #elif defined _XBOX_ONE - //StorageManager.InstallOffer(1,StorageManager.GetOffer(iIndex).wszProductID,NULL,NULL); + //StorageManager.InstallOffer(1,StorageManager.GetOffer(iIndex).wszProductID,nullptr,nullptr); #endif // the license change coming in when the offer has been installed will cause this scene to refresh @@ -311,7 +311,7 @@ int IUIScene_StartGame::UnlockTexturePackReturned(void *pParam,int iPad,C4JStora int IUIScene_StartGame::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - IUIScene_StartGame *pClass = (IUIScene_StartGame *)pParam; + IUIScene_StartGame *pClass = static_cast(pParam); #ifdef _XBOX @@ -332,7 +332,7 @@ int IUIScene_StartGame::TexturePackDialogReturned(void *pParam,int iPad,C4JStora if( result==C4JStorage::EMessage_ResultAccept ) // Full version { ullIndexA[0]=ullOfferID_Full; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } else // trial version @@ -343,7 +343,7 @@ int IUIScene_StartGame::TexturePackDialogReturned(void *pParam,int iPad,C4JStora { ullIndexA[0]=pDLCInfo->ullOfferID_Trial; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } } @@ -360,7 +360,7 @@ int IUIScene_StartGame::TexturePackDialogReturned(void *pParam,int iPad,C4JStora app.GetDLCFullOfferIDForPackID(pClass->m_MoreOptionsParams.dwTexturePack,ProductId); - StorageManager.InstallOffer(1,(WCHAR *)ProductId.c_str(),NULL,NULL); + StorageManager.InstallOffer(1,(WCHAR *)ProductId.c_str(),nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } diff --git a/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp index 059f9b755..0b1e0df24 100644 --- a/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp @@ -8,12 +8,14 @@ #include "..\..\ClientConnection.h" #include "IUIScene_TradingMenu.h" +#include "UI.h" + IUIScene_TradingMenu::IUIScene_TradingMenu() { m_validOffersCount = 0; m_selectedSlot = 0; m_offersStartIndex = 0; - m_menu = NULL; + m_menu = nullptr; m_bHasUpdatedOnce = false; } @@ -31,10 +33,10 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[getPad()] != NULL ) + if( pMinecraft->localgameModes[getPad()] != nullptr ) { Tutorial *tutorial = pMinecraft->localgameModes[getPad()]->getTutorial(); - if(tutorial != NULL) + if(tutorial != nullptr) { tutorial->handleUIInput(iAction); if(ui.IsTutorialVisible(getPad()) && !tutorial->isInputAllowed(iAction)) @@ -76,7 +78,7 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) shared_ptr player = Minecraft::GetInstance()->localplayers[getPad()]; int buyAMatches = player->inventory->countMatches(buyAItem); int buyBMatches = player->inventory->countMatches(buyBItem); - if( (buyAItem != NULL && buyAMatches >= buyAItem->count) && (buyBItem == NULL || buyBMatches >= buyBItem->count) ) + if( (buyAItem != nullptr && buyAMatches >= buyAItem->count) && (buyBItem == nullptr || 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. int actualShopItem = m_activeOffers.at(selectedShopItem).second; @@ -95,7 +97,7 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) } // Send a packet to the server - player->connection->send( shared_ptr( new TradeItemPacket(m_menu->containerId, actualShopItem) ) ); + player->connection->send(std::make_shared(m_menu->containerId, actualShopItem)); updateDisplay(); } @@ -152,7 +154,7 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) ByteArrayOutputStream rawOutput; DataOutputStream output(&rawOutput); output.writeInt(actualShopItem); - Minecraft::GetInstance()->getConnection(getPad())->send(shared_ptr( new CustomPayloadPacket(CustomPayloadPacket::TRADER_SELECTION_PACKET, rawOutput.toByteArray()))); + Minecraft::GetInstance()->getConnection(getPad())->send(std::make_shared(CustomPayloadPacket::TRADER_SELECTION_PACKET, rawOutput.toByteArray())); } } return handled; @@ -162,7 +164,7 @@ void IUIScene_TradingMenu::handleTick() { int offerCount = 0; MerchantRecipeList *offers = m_merchant->getOffers(Minecraft::GetInstance()->localplayers[getPad()]); - if (offers != NULL) + if (offers != nullptr) { offerCount = offers->size(); @@ -181,7 +183,7 @@ void IUIScene_TradingMenu::updateDisplay() int iA = -1; MerchantRecipeList *unfilteredOffers = m_merchant->getOffers(Minecraft::GetInstance()->localplayers[getPad()]); - if (unfilteredOffers != NULL) + if (unfilteredOffers != nullptr) { m_activeOffers.clear(); int unfilteredIndex = 0; @@ -205,7 +207,7 @@ void IUIScene_TradingMenu::updateDisplay() ByteArrayOutputStream rawOutput; DataOutputStream output(&rawOutput); output.writeInt(firstValidTrade); - Minecraft::GetInstance()->getConnection(getPad())->send(shared_ptr( new CustomPayloadPacket(CustomPayloadPacket::TRADER_SELECTION_PACKET, rawOutput.toByteArray()))); + Minecraft::GetInstance()->getConnection(getPad())->send(std::make_shared(CustomPayloadPacket::TRADER_SELECTION_PACKET, rawOutput.toByteArray())); } } @@ -241,7 +243,7 @@ void IUIScene_TradingMenu::updateDisplay() // 4J-PB - need to get the villager type here wsTemp = app.GetString(IDS_VILLAGER_OFFERS_ITEM); wsTemp = replaceAll(wsTemp,L"{*VILLAGER_TYPE*}",m_merchant->getDisplayName()); - int iPos=wsTemp.find(L"%s"); + size_t iPos=wsTemp.find(L"%s"); wsTemp.replace(iPos,2,activeRecipe->getSellItem()->getHoverName()); setTitle(wsTemp.c_str()); @@ -255,10 +257,10 @@ void IUIScene_TradingMenu::updateDisplay() setRequest1Item(buyAItem); setRequest2Item(buyBItem); - if(buyAItem != NULL) setRequest1Name(buyAItem->getHoverName()); + if(buyAItem != nullptr) setRequest1Name(buyAItem->getHoverName()); else setRequest1Name(L""); - if(buyBItem != NULL) setRequest2Name(buyBItem->getHoverName()); + if(buyBItem != nullptr) setRequest2Name(buyBItem->getHoverName()); else setRequest2Name(L""); bool canMake = true; @@ -284,15 +286,15 @@ void IUIScene_TradingMenu::updateDisplay() } else { - if(buyBItem!=NULL) + if(buyBItem!=nullptr) { setRequest2RedBox(true); canMake = false; } else { - setRequest2RedBox(buyBItem != NULL); - canMake = canMake && buyBItem == NULL; + setRequest2RedBox(buyBItem != nullptr); + canMake = canMake && buyBItem == nullptr; } } @@ -320,7 +322,7 @@ void IUIScene_TradingMenu::updateDisplay() bool IUIScene_TradingMenu::canMake(MerchantRecipe *recipe) { bool canMake = false; - if (recipe != NULL) + if (recipe != nullptr) { if(recipe->isDeprecated()) return false; @@ -335,7 +337,7 @@ bool IUIScene_TradingMenu::canMake(MerchantRecipe *recipe) } else { - canMake = buyAItem == NULL; + canMake = buyAItem == nullptr; } int buyBMatches = player->inventory->countMatches(buyBItem); @@ -345,7 +347,7 @@ bool IUIScene_TradingMenu::canMake(MerchantRecipe *recipe) } else { - canMake = canMake && buyBItem == NULL; + canMake = canMake && buyBItem == nullptr; } } return canMake; diff --git a/Minecraft.Client/Common/UI/UI.h b/Minecraft.Client/Common/UI/UI.h index 428b3b904..a7c416f8e 100644 --- a/Minecraft.Client/Common/UI/UI.h +++ b/Minecraft.Client/Common/UI/UI.h @@ -123,4 +123,6 @@ #include "UIScene_TeleportMenu.h" #include "UIScene_EndPoem.h" #include "UIScene_EULA.h" -#include "UIScene_NewUpdateMessage.h" \ No newline at end of file +#include "UIScene_NewUpdateMessage.h" + +extern ConsoleUIController ui; \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIBitmapFont.cpp b/Minecraft.Client/Common/UI/UIBitmapFont.cpp index afc2b1392..2b1518c4c 100644 --- a/Minecraft.Client/Common/UI/UIBitmapFont.cpp +++ b/Minecraft.Client/Common/UI/UIBitmapFont.cpp @@ -53,42 +53,42 @@ void UIAbstractBitmapFont::registerFont() IggyFontMetrics * RADLINK UIAbstractBitmapFont::GetFontMetrics_Callback(void *user_context,IggyFontMetrics *metrics) { - return ((UIAbstractBitmapFont *) user_context)->GetFontMetrics(metrics); + return static_cast(user_context)->GetFontMetrics(metrics); } S32 RADLINK UIAbstractBitmapFont::GetCodepointGlyph_Callback(void *user_context,U32 codepoint) { - return ((UIAbstractBitmapFont *) user_context)->GetCodepointGlyph(codepoint); + return static_cast(user_context)->GetCodepointGlyph(codepoint); } IggyGlyphMetrics * RADLINK UIAbstractBitmapFont::GetGlyphMetrics_Callback(void *user_context,S32 glyph,IggyGlyphMetrics *metrics) { - return ((UIAbstractBitmapFont *) user_context)->GetGlyphMetrics(glyph,metrics); + return static_cast(user_context)->GetGlyphMetrics(glyph,metrics); } rrbool RADLINK UIAbstractBitmapFont::IsGlyphEmpty_Callback(void *user_context,S32 glyph) { - return ((UIAbstractBitmapFont *) user_context)->IsGlyphEmpty(glyph); + return static_cast(user_context)->IsGlyphEmpty(glyph); } F32 RADLINK UIAbstractBitmapFont::GetKerningForGlyphPair_Callback(void *user_context,S32 first_glyph,S32 second_glyph) { - return ((UIAbstractBitmapFont *) user_context)->GetKerningForGlyphPair(first_glyph,second_glyph); + return static_cast(user_context)->GetKerningForGlyphPair(first_glyph,second_glyph); } rrbool RADLINK UIAbstractBitmapFont::CanProvideBitmap_Callback(void *user_context,S32 glyph,F32 pixel_scale) { - return ((UIAbstractBitmapFont *) user_context)->CanProvideBitmap(glyph,pixel_scale); + return static_cast(user_context)->CanProvideBitmap(glyph,pixel_scale); } rrbool RADLINK UIAbstractBitmapFont::GetGlyphBitmap_Callback(void *user_context,S32 glyph,F32 pixel_scale,IggyBitmapCharacter *bitmap) { - return ((UIAbstractBitmapFont *) user_context)->GetGlyphBitmap(glyph,pixel_scale,bitmap); + return static_cast(user_context)->GetGlyphBitmap(glyph,pixel_scale,bitmap); } void RADLINK UIAbstractBitmapFont::FreeGlyphBitmap_Callback(void *user_context,S32 glyph,F32 pixel_scale,IggyBitmapCharacter *bitmap) { - return ((UIAbstractBitmapFont *) user_context)->FreeGlyphBitmap(glyph,pixel_scale,bitmap); + return static_cast(user_context)->FreeGlyphBitmap(glyph,pixel_scale,bitmap); } UIBitmapFont::UIBitmapFont( SFontData &sfontdata ) @@ -250,15 +250,22 @@ rrbool UIBitmapFont::GetGlyphBitmap(S32 glyph,F32 pixel_scale,IggyBitmapCharacte // Choose a reasonable glyph scale. float glyphScale = 1.0f, truePixelScale = 1.0f / m_cFontData->getFontData()->m_fAdvPerPixel; - F32 targetPixelScale = pixel_scale; - //if(!RenderManager.IsWidescreen()) - //{ - // // Fix for different scales in 480 - // targetPixelScale = pixel_scale*2/3; - //} - while ( (0.5f + glyphScale) * truePixelScale < targetPixelScale) + while ( (0.5f + glyphScale) * truePixelScale < pixel_scale) glyphScale++; + // Debug: log each unique (font, pixel_scale) pair + { + static std::unordered_set s_loggedScaleKeys; + // Encode font pointer + quantized scale into a key to log each combo once + int scaleKey = (int)(pixel_scale * 100.0f) ^ (int)(uintptr_t)m_cFontData; + if (s_loggedScaleKeys.find(scaleKey) == s_loggedScaleKeys.end() && s_loggedScaleKeys.size() < 50) { + s_loggedScaleKeys.insert(scaleKey); + float tps = truePixelScale; + app.DebugPrintf("[FONT-DBG] GetGlyphBitmap: font=%s glyph=%d pixel_scale=%.3f truePixelScale=%.1f glyphScale=%.0f\n", + m_cFontData->getFontName().c_str(), glyph, pixel_scale, tps, glyphScale); + } + } + // 4J-JEV: Debug code to check which font sizes are being used. #if (!defined _CONTENT_PACKAGE) && (VERBOSE_FONT_OUTPUT > 0) @@ -303,9 +310,6 @@ rrbool UIBitmapFont::GetGlyphBitmap(S32 glyph,F32 pixel_scale,IggyBitmapCharacte } #endif - //app.DebugPrintf("Request glyph_%d (U+%.4X) at %f, converted to %f (%f)\n", - // glyph, GetUnicode(glyph), pixel_scale, targetPixelScale, glyphScale); - // It is not necessary to shrink the glyph width here // as its already been done in 'GetGlyphMetrics' by: // > metrics->x1 = m_kerningTable[glyph] * ratio; @@ -321,37 +325,67 @@ rrbool UIBitmapFont::GetGlyphBitmap(S32 glyph,F32 pixel_scale,IggyBitmapCharacte // 4J-PB - this was chopping off the top of the characters, so accented ones were losing a couple of pixels at the top // DaveK has reduced the height of the accented capitalised characters, and we've dropped this from 0.65 to 0.64 - bitmap->top_left_y = -((S32) m_cFontData->getFontData()->m_uiGlyphHeight) * m_cFontData->getFontData()->m_fAscent; + bitmap->top_left_y = -static_cast(m_cFontData->getFontData()->m_uiGlyphHeight) * m_cFontData->getFontData()->m_fAscent; bitmap->oversample = 0; - bitmap->point_sample = true; - // 4J-JEV: - // pixel_scale == font size chosen in flash. - // bitmap->pixel_scale_correct = (float) m_glyphHeight; // Scales the glyph to desired size. - // bitmap->pixel_scale_correct = pixel_scale; // Always the same size (not desired size). - // bitmap->pixel_scale_correct = pixel_scale * 0.5; // Doubles original size. - // bitmap->pixel_scale_correct = pixel_scale * 2; // Halves original size. - - // Actual scale, and possible range of scales. - bitmap->pixel_scale_correct = pixel_scale / glyphScale; - bitmap->pixel_scale_max = 99.0f; - bitmap->pixel_scale_min = 0.0f; - - /* 4J-JEV: Some of Sean's code. - int glyphScaleMin = 1; - int glyphScaleMax = 3; - float actualScale = pixel_scale / glyphScale; - bitmap->pixel_scale_correct = actualScale; - bitmap->pixel_scale_min = actualScale * glyphScaleMin * 0.999f; - bitmap->pixel_scale_max = actualScale * glyphScaleMax * 1.001f; */ +#ifdef _WINDOWS64 + // On Windows64 the window can be any size, producing fractional + // pixel_scale values that don't align to integer multiples of + // truePixelScale. The original console code cached glyphs with a + // broad [truePixelScale, 99] range in the "normal" branch, which + // works on consoles (fixed 1080p — font sizes are exact multiples) + // but causes cache pollution on Windows: the first glyph cached in + // that range sets pixel_scale_correct for ALL subsequent requests, + // so different font sizes get scaled by wrong ratios, producing + // mixed letter sizes on screen. + // + // Fix: always use pixel_scale_correct = truePixelScale so every + // cache entry is consistent. Two ranges: downscale (bilinear for + // smooth reduction) and upscale (point_sample for crisp pixel-art). + bitmap->pixel_scale_correct = truePixelScale; + if (pixel_scale < truePixelScale) + { + bitmap->pixel_scale_min = 0.0f; + bitmap->pixel_scale_max = truePixelScale; + bitmap->point_sample = false; + } + else + { + bitmap->pixel_scale_min = truePixelScale; + bitmap->pixel_scale_max = 99.0f; + bitmap->point_sample = true; + } +#else + if (glyphScale <= 1 && pixel_scale < truePixelScale) + { + // Small display: pixel_scale is less than the native glyph size. + // Report the bitmap at its true native scale so Iggy downscales it + // to match the layout metrics (bilinear for smooth downscaling). + bitmap->pixel_scale_correct = truePixelScale; + bitmap->pixel_scale_min = 0.0f; + bitmap->pixel_scale_max = truePixelScale * 1.001f; + bitmap->point_sample = false; + } + else + { + // Normal/upscale case: integer-multiple scaling for pixel-art look. + // Console-only — fixed resolution means pixel_scale values are exact + // integer multiples of truePixelScale, so cache sharing is safe. + float actualScale = pixel_scale / glyphScale; + bitmap->pixel_scale_correct = actualScale; + bitmap->pixel_scale_min = truePixelScale; + bitmap->pixel_scale_max = 99.0f; + bitmap->point_sample = true; + } +#endif // 4J-JEV: Nothing to do with glyph placement, // entirely to do with cropping your glyph out of an archive. bitmap->stride_in_bytes = m_cFontData->getFontData()->m_uiGlyphMapX; // 4J-JEV: Additional information needed to release memory afterwards. - bitmap->user_context_for_free = NULL; + bitmap->user_context_for_free = nullptr; return true; } diff --git a/Minecraft.Client/Common/UI/UIComponent_Chat.cpp b/Minecraft.Client/Common/UI/UIComponent_Chat.cpp index 901b5a773..49c5d5d21 100644 --- a/Minecraft.Client/Common/UI/UIComponent_Chat.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_Chat.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "UI.h" #include "UIComponent_Chat.h" +#include "UISplitScreenHelpers.h" #include "..\..\Minecraft.h" #include "..\..\Gui.h" @@ -46,7 +47,7 @@ void UIComponent_Chat::handleTimerComplete(int id) Minecraft *pMinecraft = Minecraft::GetInstance(); bool anyVisible = false; - if(pMinecraft->localplayers[m_iPad]!= NULL) + if(pMinecraft->localplayers[m_iPad]!= nullptr) { Gui *pGui = pMinecraft->gui; //DWORD messagesToDisplay = min( CHAT_LINES_COUNT, pGui->getMessagesCount(m_iPad) ); @@ -102,15 +103,15 @@ void UIComponent_Chat::render(S32 width, S32 height, C4JRender::eViewportType vi { case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(ui.getScreenHeight() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; } ui.setupRenderPosition(xPos, yPos); @@ -120,32 +121,42 @@ void UIComponent_Chat::render(S32 width, S32 height, C4JRender::eViewportType vi S32 tileWidth = width; S32 tileHeight = height; + bool needsYTile = false; switch( viewport ) { case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - tileHeight = (S32)(ui.getScreenHeight()); + tileHeight = static_cast(ui.getScreenHeight()); break; case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); - break; case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); + tileWidth = static_cast(ui.getScreenWidth()); + needsYTile = true; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - tileYStart = (S32)(m_movieHeight / 2); + needsYTile = true; break; } - IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); + F32 scale; + ComputeTileScale(tileWidth, tileHeight, m_movieWidth, m_movieHeight, needsYTile, scale, tileYStart); + + // For vertical split, scale down to fit the full SWF height when the + // window is shorter than the movie (same fix as HUD). + if(!needsYTile && m_movieHeight > 0) + { + F32 scaleH = (F32)tileHeight / (F32)m_movieHeight; + if(scaleH < scale) + scale = scaleH; + } + + IggyPlayerSetDisplaySize( getMovie(), (S32)(m_movieWidth * scale), (S32)(m_movieHeight * scale) ); IggyPlayerDrawTilesStart ( getMovie() ); - + m_renderWidth = tileWidth; m_renderHeight = tileHeight; IggyPlayerDrawTile ( getMovie() , @@ -153,7 +164,7 @@ void UIComponent_Chat::render(S32 width, S32 height, C4JRender::eViewportType vi tileYStart , tileXStart + tileWidth , tileYStart + tileHeight , - 0 ); + 0 ); IggyPlayerDrawTilesEnd ( getMovie() ); } else diff --git a/Minecraft.Client/Common/UI/UIComponent_DebugUIMarketingGuide.cpp b/Minecraft.Client/Common/UI/UIComponent_DebugUIMarketingGuide.cpp index 240429bc5..3aab5b983 100644 --- a/Minecraft.Client/Common/UI/UIComponent_DebugUIMarketingGuide.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_DebugUIMarketingGuide.cpp @@ -10,7 +10,7 @@ UIComponent_DebugUIMarketingGuide::UIComponent_DebugUIMarketingGuide(int iPad, v IggyDataValue result; IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (F64)0; // WIN64 + value[0].number = static_cast(0); // WIN64 #if defined _XBOX value[0].number = (F64)1; #elif defined _DURANGO @@ -22,7 +22,7 @@ UIComponent_DebugUIMarketingGuide::UIComponent_DebugUIMarketingGuide(int iPad, v #elif defined __PSVITA__ value[0].number = (F64)5; #elif defined _WINDOWS64 - value[0].number = (F64)0; + value[0].number = static_cast(0); #endif IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetPlatform , 1 , value ); } diff --git a/Minecraft.Client/Common/UI/UIComponent_MenuBackground.cpp b/Minecraft.Client/Common/UI/UIComponent_MenuBackground.cpp index d3a4c4c00..b7c4ebbdb 100644 --- a/Minecraft.Client/Common/UI/UIComponent_MenuBackground.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_MenuBackground.cpp @@ -2,6 +2,8 @@ #include "UI.h" #include "UIComponent_MenuBackground.h" +#include + UIComponent_MenuBackground::UIComponent_MenuBackground(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { m_bSplitscreen = false; @@ -42,15 +44,15 @@ void UIComponent_MenuBackground::render(S32 width, S32 height, C4JRender::eViewp { case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(ui.getScreenHeight() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; } ui.setupRenderPosition(xPos, yPos); @@ -64,28 +66,33 @@ void UIComponent_MenuBackground::render(S32 width, S32 height, C4JRender::eViewp { case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - tileHeight = (S32)(ui.getScreenHeight()); + tileHeight = static_cast(ui.getScreenHeight()); break; case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); + tileWidth = static_cast(ui.getScreenWidth()); + tileYStart = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); + tileWidth = static_cast(ui.getScreenWidth()); + tileYStart = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - tileYStart = (S32)(m_movieHeight / 2); + tileYStart = static_cast(ui.getScreenHeight() / 2); break; } - IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); + F32 scaleW = static_cast(tileXStart + tileWidth) / static_cast(m_movieWidth); + F32 scaleH = static_cast(tileYStart + tileHeight) / static_cast(m_movieHeight); + F32 scale = (scaleW > scaleH) ? scaleW : scaleH; + scale = max(scale, 1.0f); + + IggyPlayerSetDisplaySize( getMovie(), static_cast(m_movieWidth * scale), static_cast(m_movieHeight * scale) ); IggyPlayerDrawTilesStart ( getMovie() ); - + m_renderWidth = tileWidth; m_renderHeight = tileHeight; IggyPlayerDrawTile ( getMovie() , @@ -93,11 +100,15 @@ void UIComponent_MenuBackground::render(S32 width, S32 height, C4JRender::eViewp tileYStart , tileXStart + tileWidth , tileYStart + tileHeight , - 0 ); + 0 ); IggyPlayerDrawTilesEnd ( getMovie() ); } else { - UIScene::render(width, height, viewport); + if(m_bIsReloading) return; + if(!m_hasTickedOnce || !getMovie()) return; + ui.setupRenderPosition(0, 0); + IggyPlayerSetDisplaySize( getMovie(), static_cast(ui.getScreenWidth()), static_cast(ui.getScreenHeight()) ); + IggyPlayerDraw( getMovie() ); } } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIComponent_Panorama.cpp b/Minecraft.Client/Common/UI/UIComponent_Panorama.cpp index a52ebd727..3da8174c7 100644 --- a/Minecraft.Client/Common/UI/UIComponent_Panorama.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_Panorama.cpp @@ -45,7 +45,7 @@ void UIComponent_Panorama::tick() Minecraft *pMinecraft = Minecraft::GetInstance(); EnterCriticalSection(&pMinecraft->m_setLevelCS); - if(pMinecraft->level!=NULL) + if(pMinecraft->level!=nullptr) { int64_t i64TimeOfDay =0; // are we in the Nether? - Leave the time as 0 if we are, so we show daylight @@ -85,46 +85,55 @@ void UIComponent_Panorama::render(S32 width, S32 height, C4JRender::eViewportTyp switch( viewport ) { case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - yPos = (S32)(ui.getScreenHeight() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); break; } ui.setupRenderPosition(xPos, yPos); - if((viewport == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT) || (viewport == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT)) + S32 tileXStart = 0; + S32 tileYStart = 0; + S32 tileWidth = width; + S32 tileHeight = height; + + if((viewport == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT) || (viewport == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT)) { - // Need to render at full height, but only the left side of the scene - S32 tileXStart = 0; - S32 tileYStart = 0; - S32 tileWidth = width; - S32 tileHeight = (S32)(ui.getScreenHeight()); - - IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); - - IggyPlayerDrawTilesStart ( getMovie() ); - - m_renderWidth = tileWidth; - m_renderHeight = tileHeight; - IggyPlayerDrawTile ( getMovie() , - tileXStart , - tileYStart , - tileXStart + tileWidth , - tileYStart + tileHeight , - 0 ); - IggyPlayerDrawTilesEnd ( getMovie() ); + tileHeight = static_cast(ui.getScreenHeight()); } else { - // Need to render at full height, and full width. But compressed into the viewport - IggyPlayerSetDisplaySize( getMovie(), ui.getScreenWidth(), ui.getScreenHeight()/2 ); - IggyPlayerDraw( getMovie() ); + tileWidth = static_cast(ui.getScreenWidth()); + tileYStart = static_cast(ui.getScreenHeight() / 2); } + + F32 scaleW = static_cast(tileXStart + tileWidth) / static_cast(m_movieWidth); + F32 scaleH = static_cast(tileYStart + tileHeight) / static_cast(m_movieHeight); + F32 scale = (scaleW > scaleH) ? scaleW : scaleH; + if(scale < 1.0f) scale = 1.0f; + + IggyPlayerSetDisplaySize( getMovie(), static_cast(m_movieWidth * scale), static_cast(m_movieHeight * scale) ); + + IggyPlayerDrawTilesStart ( getMovie() ); + + m_renderWidth = tileWidth; + m_renderHeight = tileHeight; + IggyPlayerDrawTile ( getMovie() , + tileXStart , + tileYStart , + tileXStart + tileWidth , + tileYStart + tileHeight , + 0 ); + IggyPlayerDrawTilesEnd ( getMovie() ); } else { - UIScene::render(width, height, viewport); + if(m_bIsReloading) return; + if(!m_hasTickedOnce || !getMovie()) return; + ui.setupRenderPosition(0, 0); + IggyPlayerSetDisplaySize( getMovie(), static_cast(ui.getScreenWidth()), static_cast(ui.getScreenHeight()) ); + IggyPlayerDraw( getMovie() ); } } diff --git a/Minecraft.Client/Common/UI/UIComponent_Tooltips.cpp b/Minecraft.Client/Common/UI/UIComponent_Tooltips.cpp index 255740c9a..4f60de5fd 100644 --- a/Minecraft.Client/Common/UI/UIComponent_Tooltips.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_Tooltips.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "UI.h" #include "UIComponent_Tooltips.h" +#include "UISplitScreenHelpers.h" UIComponent_Tooltips::UIComponent_Tooltips(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { @@ -92,18 +93,22 @@ void UIComponent_Tooltips::updateSafeZone() case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: safeTop = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - safeBottom = getSafeZoneHalfHeight(); + safeTop = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - safeLeft = getSafeZoneHalfWidth(); + safeTop = getSafeZoneHalfHeight(); safeBottom = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - safeRight = getSafeZoneHalfWidth(); + safeTop = getSafeZoneHalfHeight(); safeBottom = getSafeZoneHalfHeight(); + break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: safeTop = getSafeZoneHalfHeight(); @@ -111,22 +116,22 @@ void UIComponent_Tooltips::updateSafeZone() break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: safeTop = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - safeBottom = getSafeZoneHalfHeight(); + safeTop = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - safeBottom = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); + safeTop = getSafeZoneHalfHeight(); + break; case C4JRender::VIEWPORT_TYPE_FULLSCREEN: default: safeTop = getSafeZoneHalfHeight(); safeBottom = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); - safeRight = getSafeZoneHalfWidth(); + break; } setSafeZone(safeTop, safeBottom, safeLeft, safeRight); @@ -154,8 +159,8 @@ void UIComponent_Tooltips::tick() { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -164,7 +169,7 @@ void UIComponent_Tooltips::tick() } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else @@ -174,7 +179,7 @@ void UIComponent_Tooltips::tick() { ucAlpha=15; } - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } setOpacity(fVal); @@ -206,15 +211,15 @@ void UIComponent_Tooltips::render(S32 width, S32 height, C4JRender::eViewportTyp { case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(ui.getScreenHeight() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); + xPos = static_cast(ui.getScreenWidth() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); break; } ui.setupRenderPosition(xPos, yPos); @@ -224,32 +229,42 @@ void UIComponent_Tooltips::render(S32 width, S32 height, C4JRender::eViewportTyp S32 tileWidth = width; S32 tileHeight = height; + bool needsYTile = false; switch( viewport ) { case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - tileHeight = (S32)(ui.getScreenHeight()); + tileHeight = static_cast(ui.getScreenHeight()); break; case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); - break; case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); + tileWidth = static_cast(ui.getScreenWidth()); + needsYTile = true; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - tileYStart = (S32)(m_movieHeight / 2); + needsYTile = true; break; } - IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); + F32 scale; + ComputeTileScale(tileWidth, tileHeight, m_movieWidth, m_movieHeight, needsYTile, scale, tileYStart); + + // For vertical split, scale down to fit the full SWF height when the + // window is shorter than the movie (same fix as HUD). + if(!needsYTile && m_movieHeight > 0) + { + F32 scaleH = (F32)tileHeight / (F32)m_movieHeight; + if(scaleH < scale) + scale = scaleH; + } + + IggyPlayerSetDisplaySize( getMovie(), (S32)(m_movieWidth * scale), (S32)(m_movieHeight * scale) ); IggyPlayerDrawTilesStart ( getMovie() ); - + m_renderWidth = tileWidth; m_renderHeight = tileHeight; IggyPlayerDrawTile ( getMovie() , @@ -257,7 +272,7 @@ void UIComponent_Tooltips::render(S32 width, S32 height, C4JRender::eViewportTyp tileYStart , tileXStart + tileWidth , tileYStart + tileHeight , - 0 ); + 0 ); IggyPlayerDrawTilesEnd ( getMovie() ); } else @@ -351,7 +366,7 @@ void UIComponent_Tooltips::_SetTooltip(unsigned int iToolTipId, UIString label, void UIComponent_Tooltips::_Relayout() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcUpdateLayout, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcUpdateLayout, 0 , nullptr ); #ifdef __PSVITA__ // rebuild touchboxes diff --git a/Minecraft.Client/Common/UI/UIComponent_TutorialPopup.cpp b/Minecraft.Client/Common/UI/UIComponent_TutorialPopup.cpp index 3b4eb097f..76d3babfb 100644 --- a/Minecraft.Client/Common/UI/UIComponent_TutorialPopup.cpp +++ b/Minecraft.Client/Common/UI/UIComponent_TutorialPopup.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "UI.h" #include "UIComponent_TutorialPopup.h" +#include "UISplitScreenHelpers.h" #include "..\..\Common\Tutorial\Tutorial.h" #include "..\..\..\Minecraft.World\StringHelpers.h" #include "..\..\MultiplayerLocalPlayer.h" @@ -12,8 +13,8 @@ UIComponent_TutorialPopup::UIComponent_TutorialPopup(int iPad, void *initData, U // Setup all the Iggy references we need for this scene initialiseMovie(); - m_interactScene = NULL; - m_lastInteractSceneMoved = NULL; + m_interactScene = nullptr; + m_lastInteractSceneMoved = nullptr; m_lastSceneMovedLeft = false; m_bAllowFade = false; m_iconItem = nullptr; @@ -90,7 +91,7 @@ void UIComponent_TutorialPopup::RemoveInteractSceneReference(UIScene *scene) { if( m_interactScene == scene ) { - m_interactScene = NULL; + m_interactScene = nullptr; } } @@ -132,7 +133,7 @@ void UIComponent_TutorialPopup::_SetDescription(UIScene *interactScene, const ws { m_interactScene = interactScene; app.DebugPrintf("Setting m_interactScene to %08x\n", m_interactScene); - if( interactScene != m_lastInteractSceneMoved ) m_lastInteractSceneMoved = NULL; + if( interactScene != m_lastInteractSceneMoved ) m_lastInteractSceneMoved = nullptr; if(desc.empty()) { SetVisible( false ); @@ -212,20 +213,20 @@ wstring UIComponent_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, if( icon != TUTORIAL_NO_ICON ) { m_iconIsFoil = false; - m_iconItem = shared_ptr(new ItemInstance(icon,1,iAuxVal)); + m_iconItem = std::make_shared(icon, 1, iAuxVal); } else { m_iconItem = nullptr; wstring openTag(L"{*ICON*}"); wstring closeTag(L"{*/ICON*}"); - int iconTagStartPos = (int)temp.find(openTag); - int iconStartPos = iconTagStartPos + (int)openTag.length(); - if( iconTagStartPos > 0 && iconStartPos < (int)temp.length() ) + size_t iconTagStartPos = temp.find(openTag); + size_t iconStartPos = iconTagStartPos + openTag.length(); + if( iconTagStartPos > 0 && iconStartPos < temp.length() ) { - int iconEndPos = (int)temp.find( closeTag, iconStartPos ); + size_t iconEndPos = temp.find(closeTag, iconStartPos); - if(iconEndPos > iconStartPos && iconEndPos < (int)temp.length() ) + if(iconEndPos > iconStartPos && iconEndPos < temp.length() ) { wstring id = temp.substr(iconStartPos, iconEndPos - iconStartPos); @@ -241,7 +242,7 @@ wstring UIComponent_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, { iAuxVal = 0; } - m_iconItem = shared_ptr(new ItemInstance(iconId,1,iAuxVal)); + m_iconItem = std::make_shared(iconId, 1, iAuxVal); temp.replace(iconTagStartPos, iconEndPos - iconTagStartPos + closeTag.length(), L""); } @@ -250,63 +251,63 @@ wstring UIComponent_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, // remove any icon text else if(temp.find(L"{*CraftingTableIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::workBench_Id,1,0)); + m_iconItem = std::make_shared(Tile::workBench_Id, 1, 0); } else if(temp.find(L"{*SticksIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::stick_Id,1,0)); + m_iconItem = std::make_shared(Item::stick_Id, 1, 0); } else if(temp.find(L"{*PlanksIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::wood_Id,1,0)); + m_iconItem = std::make_shared(Tile::wood_Id, 1, 0); } else if(temp.find(L"{*WoodenShovelIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::shovel_wood_Id,1,0)); + m_iconItem = std::make_shared(Item::shovel_wood_Id, 1, 0); } else if(temp.find(L"{*WoodenHatchetIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::hatchet_wood_Id,1,0)); + m_iconItem = std::make_shared(Item::hatchet_wood_Id, 1, 0); } else if(temp.find(L"{*WoodenPickaxeIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::pickAxe_wood_Id,1,0)); + m_iconItem = std::make_shared(Item::pickAxe_wood_Id, 1, 0); } else if(temp.find(L"{*FurnaceIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::furnace_Id,1,0)); + m_iconItem = std::make_shared(Tile::furnace_Id, 1, 0); } else if(temp.find(L"{*WoodenDoorIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::door_wood,1,0)); + m_iconItem = std::make_shared(Item::door_wood, 1, 0); } else if(temp.find(L"{*TorchIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::torch_Id,1,0)); + m_iconItem = std::make_shared(Tile::torch_Id, 1, 0); } else if(temp.find(L"{*BoatIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::boat_Id,1,0)); + m_iconItem = std::make_shared(Item::boat_Id, 1, 0); } else if(temp.find(L"{*FishingRodIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::fishingRod_Id,1,0)); + m_iconItem = std::make_shared(Item::fishingRod_Id, 1, 0); } else if(temp.find(L"{*FishIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::fish_raw_Id,1,0)); + m_iconItem = std::make_shared(Item::fish_raw_Id, 1, 0); } else if(temp.find(L"{*MinecartIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Item::minecart_Id,1,0)); + m_iconItem = std::make_shared(Item::minecart_Id, 1, 0); } else if(temp.find(L"{*RailIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::rail_Id,1,0)); + m_iconItem = std::make_shared(Tile::rail_Id, 1, 0); } else if(temp.find(L"{*PoweredRailIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::goldenRail_Id,1,0)); + m_iconItem = std::make_shared(Tile::goldenRail_Id, 1, 0); } else if(temp.find(L"{*StructuresIcon*}")!=wstring::npos) { @@ -320,15 +321,15 @@ wstring UIComponent_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, } else if(temp.find(L"{*StoneIcon*}")!=wstring::npos) { - m_iconItem = shared_ptr(new ItemInstance(Tile::stone_Id,1,0)); + m_iconItem = std::make_shared(Tile::stone_Id, 1, 0); } else { m_iconItem = nullptr; } } - if(!isFixedIcon && m_iconItem != NULL) setupIconHolder(e_ICON_TYPE_IGGY); - m_controlIconHolder.setVisible( isFixedIcon || m_iconItem != NULL); + if(!isFixedIcon && m_iconItem != nullptr) setupIconHolder(e_ICON_TYPE_IGGY); + m_controlIconHolder.setVisible( isFixedIcon || m_iconItem != nullptr); return temp; } @@ -341,13 +342,13 @@ wstring UIComponent_TutorialPopup::_SetImage(wstring &desc) wstring openTag(L"{*IMAGE*}"); wstring closeTag(L"{*/IMAGE*}"); - int imageTagStartPos = (int)desc.find(openTag); - int imageStartPos = imageTagStartPos + (int)openTag.length(); - if( imageTagStartPos > 0 && imageStartPos < (int)desc.length() ) + size_t imageTagStartPos = desc.find(openTag); + size_t imageStartPos = imageTagStartPos + openTag.length(); + if( imageTagStartPos > 0 && imageStartPos < desc.length() ) { - int imageEndPos = (int)desc.find( closeTag, imageStartPos ); + size_t imageEndPos = desc.find( closeTag, imageStartPos ); - if(imageEndPos > imageStartPos && imageEndPos < (int)desc.length() ) + if(imageEndPos > imageStartPos && imageEndPos < desc.length() ) { wstring id = desc.substr(imageStartPos, imageEndPos - imageStartPos); m_image.SetImagePath( id.c_str() ); @@ -425,7 +426,7 @@ wstring UIComponent_TutorialPopup::ParseDescription(int iPad, wstring &text) void UIComponent_TutorialPopup::UpdateInteractScenePosition(bool visible) { - if( m_interactScene == NULL ) return; + if( m_interactScene == nullptr ) return; // 4J-PB - check this players screen section to see if we should allow the animation bool bAllowAnim=false; @@ -474,27 +475,17 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo { if(viewport != C4JRender::VIEWPORT_TYPE_FULLSCREEN) { - S32 xPos = 0; - S32 yPos = 0; - switch( viewport ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(ui.getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); - break; - } + // Derive the viewport origin and fit a 16:9 box inside it (same as UIScene::render), + // then apply safezone nudges so the popup stays clear of screen edges. + F32 originX, originY, viewW, viewH; + GetViewportRect(ui.getScreenWidth(), ui.getScreenHeight(), viewport, originX, originY, viewW, viewH); + + S32 fitW, fitH, offsetX, offsetY; + Fit16x9(viewW, viewH, fitW, fitH, offsetX, offsetY); + + S32 xPos = static_cast(originX) + offsetX; + S32 yPos = static_cast(originY) + offsetY; + //Adjust for safezone switch( viewport ) { @@ -505,6 +496,7 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: yPos += getSafeZoneHalfHeight(); break; + default: break; } switch( viewport ) { @@ -515,10 +507,11 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: xPos -= getSafeZoneHalfWidth(); break; + default: break; } ui.setupRenderPosition(xPos, yPos); - IggyPlayerSetDisplaySize( getMovie(), width, height ); + IggyPlayerSetDisplaySize( getMovie(), fitW, fitH ); IggyPlayerDraw( getMovie() ); } else @@ -529,7 +522,7 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo void UIComponent_TutorialPopup::customDraw(IggyCustomDrawCallbackRegion *region) { - if(m_iconItem != NULL) customDrawSlotControl(region,m_iPad,m_iconItem,1.0f,m_iconItem->isFoil() || m_iconIsFoil,false); + if(m_iconItem != nullptr) customDrawSlotControl(region,m_iPad,m_iconItem,1.0f,m_iconItem->isFoil() || m_iconIsFoil,false); } void UIComponent_TutorialPopup::setupIconHolder(EIcons icon) @@ -538,7 +531,7 @@ void UIComponent_TutorialPopup::setupIconHolder(EIcons icon) IggyDataValue result; IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (F64)icon; + value[0].number = static_cast(icon); IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetupIconHolder , 1 , value ); m_iconType = icon; diff --git a/Minecraft.Client/Common/UI/UIControl.cpp b/Minecraft.Client/Common/UI/UIControl.cpp index 3d853ac46..7582e82ff 100644 --- a/Minecraft.Client/Common/UI/UIControl.cpp +++ b/Minecraft.Client/Common/UI/UIControl.cpp @@ -6,7 +6,7 @@ UIControl::UIControl() { - m_parentScene = NULL; + m_parentScene = nullptr; m_lastOpacity = 1.0f; m_controlName = ""; m_isVisible = true; @@ -31,15 +31,15 @@ bool UIControl::setupControl(UIScene *scene, IggyValuePath *parent, const string m_nameVisible = registerFastName(L"visible"); F64 fx, fy, fwidth, fheight; - IggyValueGetF64RS( getIggyValuePath() , m_nameXPos , NULL , &fx ); - IggyValueGetF64RS( getIggyValuePath() , m_nameYPos , NULL , &fy ); - IggyValueGetF64RS( getIggyValuePath() , m_nameWidth , NULL , &fwidth ); - IggyValueGetF64RS( getIggyValuePath() , m_nameHeight , NULL , &fheight ); + IggyValueGetF64RS( getIggyValuePath() , m_nameXPos , nullptr , &fx ); + IggyValueGetF64RS( getIggyValuePath() , m_nameYPos , nullptr , &fy ); + IggyValueGetF64RS( getIggyValuePath() , m_nameWidth , nullptr , &fwidth ); + IggyValueGetF64RS( getIggyValuePath() , m_nameHeight , nullptr , &fheight ); - m_x = (S32)fx; - m_y = (S32)fy; - m_width = (S32)Math::round(fwidth); - m_height = (S32)Math::round(fheight); + m_x = static_cast(fx); + m_y = static_cast(fy); + m_width = static_cast(Math::round(fwidth)); + m_height = static_cast(Math::round(fheight)); return res; } @@ -47,14 +47,14 @@ bool UIControl::setupControl(UIScene *scene, IggyValuePath *parent, const string void UIControl::UpdateControl() { F64 fx, fy, fwidth, fheight; - IggyValueGetF64RS( getIggyValuePath() , m_nameXPos , NULL , &fx ); - IggyValueGetF64RS( getIggyValuePath() , m_nameYPos , NULL , &fy ); - IggyValueGetF64RS( getIggyValuePath() , m_nameWidth , NULL , &fwidth ); - IggyValueGetF64RS( getIggyValuePath() , m_nameHeight , NULL , &fheight ); - m_x = (S32)fx; - m_y = (S32)fy; - m_width = (S32)Math::round(fwidth); - m_height = (S32)Math::round(fheight); + IggyValueGetF64RS( getIggyValuePath() , m_nameXPos , nullptr , &fx ); + IggyValueGetF64RS( getIggyValuePath() , m_nameYPos , nullptr , &fy ); + IggyValueGetF64RS( getIggyValuePath() , m_nameWidth , nullptr , &fwidth ); + IggyValueGetF64RS( getIggyValuePath() , m_nameHeight , nullptr , &fheight ); + m_x = static_cast(fx); + m_y = static_cast(fy); + m_width = static_cast(Math::round(fwidth)); + m_height = static_cast(Math::round(fheight)); } void UIControl::ReInit() @@ -76,7 +76,7 @@ void UIControl::ReInit() IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, m_parentScene->m_rootPath , m_funcSetAlpha , 2 , value ); } - IggyValueSetBooleanRS( getIggyValuePath(), m_nameVisible, NULL, m_isVisible ); + IggyValueSetBooleanRS( getIggyValuePath(), m_nameVisible, nullptr, m_isVisible ); } IggyValuePath *UIControl::getIggyValuePath() @@ -130,7 +130,7 @@ void UIControl::setVisible(bool visible) { if(visible != m_isVisible) { - rrbool succ = IggyValueSetBooleanRS( getIggyValuePath(), m_nameVisible, NULL, visible ); + rrbool succ = IggyValueSetBooleanRS( getIggyValuePath(), m_nameVisible, nullptr, visible ); if(succ) m_isVisible = visible; else app.DebugPrintf("Failed to set visibility for control\n"); } @@ -140,7 +140,7 @@ bool UIControl::getVisible() { rrbool bVisible = false; - IggyResult result = IggyValueGetBooleanRS ( getIggyValuePath() , m_nameVisible, NULL, &bVisible ); + IggyResult result = IggyValueGetBooleanRS ( getIggyValuePath() , m_nameVisible, nullptr, &bVisible ); m_isVisible = bVisible; diff --git a/Minecraft.Client/Common/UI/UIControl_Base.cpp b/Minecraft.Client/Common/UI/UIControl_Base.cpp index 7a4a24e5e..87c2862f4 100644 --- a/Minecraft.Client/Common/UI/UIControl_Base.cpp +++ b/Minecraft.Client/Common/UI/UIControl_Base.cpp @@ -72,7 +72,7 @@ void UIControl_Base::setLabel(UIString label, bool instant, bool force) const wchar_t* UIControl_Base::getLabel() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS(m_parentScene->getMovie(), &result, getIggyValuePath(), m_funcGetLabel, 0, NULL); + IggyResult out = IggyPlayerCallMethodRS(m_parentScene->getMovie(), &result, getIggyValuePath(), m_funcGetLabel, 0, nullptr); if(result.type == IGGY_DATATYPE_string_UTF16) { @@ -90,7 +90,7 @@ void UIControl_Base::setAllPossibleLabels(int labelCount, wchar_t labels[][256]) for(unsigned int i = 0; i < labelCount; ++i) { - stringVal[i].string = (IggyUTF16 *)labels[i]; + stringVal[i].string = static_cast(labels[i]); stringVal[i].length = wcslen(labels[i]); value[i].type = IGGY_DATATYPE_string_UTF16; value[i].string16 = stringVal[i]; diff --git a/Minecraft.Client/Common/UI/UIControl_ButtonList.cpp b/Minecraft.Client/Common/UI/UIControl_ButtonList.cpp index 4d60a477c..4f0e5ca08 100644 --- a/Minecraft.Client/Common/UI/UIControl_ButtonList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_ButtonList.cpp @@ -60,7 +60,7 @@ void UIControl_ButtonList::ReInit() void UIControl_ButtonList::clearList() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_removeAllItemsFunc , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_removeAllItemsFunc , 0 , nullptr ); m_itemCount = 0; } @@ -82,7 +82,7 @@ void UIControl_ButtonList::addItem(const string &label, int data) IggyStringUTF8 stringVal; stringVal.string = (char*)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF8; value[0].string8 = stringVal; diff --git a/Minecraft.Client/Common/UI/UIControl_CheckBox.cpp b/Minecraft.Client/Common/UI/UIControl_CheckBox.cpp index 1c3e8afee..e5f4da7a5 100644 --- a/Minecraft.Client/Common/UI/UIControl_CheckBox.cpp +++ b/Minecraft.Client/Common/UI/UIControl_CheckBox.cpp @@ -60,7 +60,7 @@ void UIControl_CheckBox::init(UIString label, int id, bool checked) bool UIControl_CheckBox::IsChecked() { rrbool checked = false; - IggyResult result = IggyValueGetBooleanRS ( &m_iggyPath , m_checkedProp, NULL, &checked ); + IggyResult result = IggyValueGetBooleanRS ( &m_iggyPath , m_checkedProp, nullptr, &checked ); m_bChecked = checked; return checked; } diff --git a/Minecraft.Client/Common/UI/UIControl_DLCList.cpp b/Minecraft.Client/Common/UI/UIControl_DLCList.cpp index 35e6b08a4..39f8ff39a 100644 --- a/Minecraft.Client/Common/UI/UIControl_DLCList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_DLCList.cpp @@ -20,7 +20,7 @@ void UIControl_DLCList::addItem(const string &label, bool showTick, int iId) IggyStringUTF8 stringVal; stringVal.string = (char*)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF8; value[0].string8 = stringVal; @@ -41,7 +41,7 @@ void UIControl_DLCList::addItem(const wstring &label, bool showTick, int iId) IggyStringUTF16 stringVal; stringVal.string = (IggyUTF16 *)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF16; value[0].string16 = stringVal; diff --git a/Minecraft.Client/Common/UI/UIControl_DynamicLabel.cpp b/Minecraft.Client/Common/UI/UIControl_DynamicLabel.cpp index fa29a1375..8c2758931 100644 --- a/Minecraft.Client/Common/UI/UIControl_DynamicLabel.cpp +++ b/Minecraft.Client/Common/UI/UIControl_DynamicLabel.cpp @@ -74,12 +74,12 @@ void UIControl_DynamicLabel::TouchScroll(S32 iY, bool bActive) S32 UIControl_DynamicLabel::GetRealWidth() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth, 0 , nullptr ); S32 iRealWidth = m_width; if(result.type == IGGY_DATATYPE_number) { - iRealWidth = (S32)result.number; + iRealWidth = static_cast(result.number); } return iRealWidth; } @@ -87,12 +87,12 @@ S32 UIControl_DynamicLabel::GetRealWidth() S32 UIControl_DynamicLabel::GetRealHeight() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , nullptr ); S32 iRealHeight = m_height; if(result.type == IGGY_DATATYPE_number) { - iRealHeight = (S32)result.number; + iRealHeight = static_cast(result.number); } return iRealHeight; } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIControl_EnchantmentBook.cpp b/Minecraft.Client/Common/UI/UIControl_EnchantmentBook.cpp index 9664dbf4f..f091b0fcc 100644 --- a/Minecraft.Client/Common/UI/UIControl_EnchantmentBook.cpp +++ b/Minecraft.Client/Common/UI/UIControl_EnchantmentBook.cpp @@ -12,7 +12,7 @@ UIControl_EnchantmentBook::UIControl_EnchantmentBook() { UIControl::setControlType(UIControl::eEnchantmentBook); - model = NULL; + model = nullptr; last = nullptr; time = 0; @@ -69,12 +69,12 @@ void UIControl_EnchantmentBook::render(IggyCustomDrawCallbackRegion *region) glEnable(GL_CULL_FACE); - if(model == NULL) + if(model == nullptr) { // Share the model the the EnchantTableRenderer - EnchantTableRenderer *etr = (EnchantTableRenderer*)TileEntityRenderDispatcher::instance->getRenderer(eTYPE_ENCHANTMENTTABLEENTITY); - if(etr != NULL) + EnchantTableRenderer *etr = static_cast(TileEntityRenderDispatcher::instance->getRenderer(eTYPE_ENCHANTMENTTABLEENTITY)); + if(etr != nullptr) { model = etr->bookModel; } @@ -96,7 +96,7 @@ void UIControl_EnchantmentBook::render(IggyCustomDrawCallbackRegion *region) void UIControl_EnchantmentBook::tickBook() { - UIScene_EnchantingMenu *m_containerScene = (UIScene_EnchantingMenu *)m_parentScene; + UIScene_EnchantingMenu *m_containerScene = static_cast(m_parentScene); EnchantmentMenu *menu = m_containerScene->getMenu(); shared_ptr current = menu->getSlot(0)->getItem(); if (!ItemInstance::matches(current, last)) diff --git a/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp b/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp index f1e2735ae..156f98156 100644 --- a/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp +++ b/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp @@ -55,7 +55,7 @@ void UIControl_EnchantmentButton::tick() void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) { - UIScene_EnchantingMenu *enchantingScene = (UIScene_EnchantingMenu *)m_parentScene; + UIScene_EnchantingMenu *enchantingScene = static_cast(m_parentScene); EnchantmentMenu *menu = enchantingScene->getMenu(); float width = region->x1 - region->x0; @@ -108,7 +108,7 @@ void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) if (pMinecraft->localplayers[enchantingScene->getPad()]->experienceLevel < cost && !pMinecraft->localplayers[enchantingScene->getPad()]->abilities.instabuild) { col = m_textDisabledColour; - font->drawWordWrap(m_enchantmentString, 0, 0, (float)m_width/ss, col, (float)m_height/ss); + font->drawWordWrap(m_enchantmentString, 0, 0, static_cast(m_width)/ss, col, static_cast(m_height)/ss); font = pMinecraft->font; //col = (0x80ff20 & 0xfefefe) >> 1; //font->drawShadow(line, (bwidth - font->width(line))/ss, 7, col); @@ -120,7 +120,7 @@ void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) //col = 0xffff80; col = m_textFocusColour; } - font->drawWordWrap(m_enchantmentString, 0, 0, (float)m_width/ss, col, (float)m_height/ss); + font->drawWordWrap(m_enchantmentString, 0, 0, static_cast(m_width)/ss, col, static_cast(m_height)/ss); font = pMinecraft->font; //col = 0x80ff20; //font->drawShadow(line, (bwidth - font->width(line))/ss, 7, col); @@ -137,7 +137,7 @@ void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) void UIControl_EnchantmentButton::updateState() { - UIScene_EnchantingMenu *enchantingScene = (UIScene_EnchantingMenu *)m_parentScene; + UIScene_EnchantingMenu *enchantingScene = static_cast(m_parentScene); EnchantmentMenu *menu = enchantingScene->getMenu(); EState state = eState_Inactive; @@ -182,7 +182,7 @@ void UIControl_EnchantmentButton::updateState() IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (int)state; + value[0].number = static_cast(state); IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcChangeState , 1 , value ); if(out == IGGY_RESULT_SUCCESS) m_lastState = state; diff --git a/Minecraft.Client/Common/UI/UIControl_HTMLLabel.cpp b/Minecraft.Client/Common/UI/UIControl_HTMLLabel.cpp index 8b7eb9a1f..b6bd3e472 100644 --- a/Minecraft.Client/Common/UI/UIControl_HTMLLabel.cpp +++ b/Minecraft.Client/Common/UI/UIControl_HTMLLabel.cpp @@ -23,7 +23,7 @@ bool UIControl_HTMLLabel::setupControl(UIScene *scene, IggyValuePath *parent, co void UIControl_HTMLLabel::startAutoScroll() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcStartAutoScroll , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcStartAutoScroll , 0 , nullptr ); } void UIControl_HTMLLabel::ReInit() @@ -79,12 +79,12 @@ void UIControl_HTMLLabel::TouchScroll(S32 iY, bool bActive) S32 UIControl_HTMLLabel::GetRealWidth() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth, 0 , nullptr ); S32 iRealWidth = m_width; if(result.type == IGGY_DATATYPE_number) { - iRealWidth = (S32)result.number; + iRealWidth = static_cast(result.number); } return iRealWidth; } @@ -92,12 +92,12 @@ S32 UIControl_HTMLLabel::GetRealWidth() S32 UIControl_HTMLLabel::GetRealHeight() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , nullptr ); S32 iRealHeight = m_height; if(result.type == IGGY_DATATYPE_number) { - iRealHeight = (S32)result.number; + iRealHeight = static_cast(result.number); } return iRealHeight; } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIControl_LeaderboardList.cpp b/Minecraft.Client/Common/UI/UIControl_LeaderboardList.cpp index c34b5e875..3920e0040 100644 --- a/Minecraft.Client/Common/UI/UIControl_LeaderboardList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_LeaderboardList.cpp @@ -45,7 +45,7 @@ void UIControl_LeaderboardList::ReInit() void UIControl_LeaderboardList::clearList() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_funcResetLeaderboard , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_funcResetLeaderboard , 0 , nullptr ); } void UIControl_LeaderboardList::setupTitles(const wstring &rank, const wstring &gamertag) diff --git a/Minecraft.Client/Common/UI/UIControl_MinecraftHorse.cpp b/Minecraft.Client/Common/UI/UIControl_MinecraftHorse.cpp index 457e20286..25fc0316d 100644 --- a/Minecraft.Client/Common/UI/UIControl_MinecraftHorse.cpp +++ b/Minecraft.Client/Common/UI/UIControl_MinecraftHorse.cpp @@ -27,10 +27,10 @@ UIControl_MinecraftHorse::UIControl_MinecraftHorse() Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); } void UIControl_MinecraftHorse::render(IggyCustomDrawCallbackRegion *region) @@ -49,7 +49,7 @@ void UIControl_MinecraftHorse::render(IggyCustomDrawCallbackRegion *region) glTranslatef(xo, yo - (height / 7.5f), 50.0f); //UIScene_InventoryMenu *containerMenu = (UIScene_InventoryMenu *)m_parentScene; - UIScene_HorseInventoryMenu *containerMenu = (UIScene_HorseInventoryMenu *)m_parentScene; + UIScene_HorseInventoryMenu *containerMenu = static_cast(m_parentScene); shared_ptr entityHorse = containerMenu->m_horse; diff --git a/Minecraft.Client/Common/UI/UIControl_MinecraftPlayer.cpp b/Minecraft.Client/Common/UI/UIControl_MinecraftPlayer.cpp index d0625bce8..ae65ac2b5 100644 --- a/Minecraft.Client/Common/UI/UIControl_MinecraftPlayer.cpp +++ b/Minecraft.Client/Common/UI/UIControl_MinecraftPlayer.cpp @@ -19,10 +19,10 @@ UIControl_MinecraftPlayer::UIControl_MinecraftPlayer() Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); } void UIControl_MinecraftPlayer::render(IggyCustomDrawCallbackRegion *region) @@ -49,7 +49,7 @@ void UIControl_MinecraftPlayer::render(IggyCustomDrawCallbackRegion *region) glScalef(-ss, ss, ss); glRotatef(180, 0, 0, 1); - UIScene_InventoryMenu *containerMenu = (UIScene_InventoryMenu *)m_parentScene; + UIScene_InventoryMenu *containerMenu = static_cast(m_parentScene); float oybr = pMinecraft->localplayers[containerMenu->getPad()]->yBodyRot; float oyr = pMinecraft->localplayers[containerMenu->getPad()]->yRot; diff --git a/Minecraft.Client/Common/UI/UIControl_PlayerList.cpp b/Minecraft.Client/Common/UI/UIControl_PlayerList.cpp index 41534dc23..0703919fb 100644 --- a/Minecraft.Client/Common/UI/UIControl_PlayerList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_PlayerList.cpp @@ -21,7 +21,7 @@ void UIControl_PlayerList::addItem(const wstring &label, int iPlayerIcon, int iV IggyStringUTF16 stringVal; stringVal.string = (IggyUTF16*)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF16; value[0].string16 = stringVal; diff --git a/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp b/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp index d74bd185c..b8c439b1a 100644 --- a/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp +++ b/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp @@ -23,10 +23,10 @@ UIControl_PlayerSkinPreview::UIControl_PlayerSkinPreview() Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); m_customTextureUrl = L"default"; m_backupTexture = TN_MOB_CHAR; @@ -55,7 +55,7 @@ UIControl_PlayerSkinPreview::UIControl_PlayerSkinPreview() m_fOriginalRotation = 0.0f; m_framesAnimatingRotation = 0; m_bAnimatingToFacing = false; - m_pvAdditionalModelParts=NULL; + m_pvAdditionalModelParts=nullptr; m_uiAnimOverrideBitmask=0L; } @@ -167,7 +167,7 @@ void UIControl_PlayerSkinPreview::SetFacing(ESkinPreviewFacing facing, bool bAni void UIControl_PlayerSkinPreview::CycleNextAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation + 1); + m_currentAnimation = static_cast(m_currentAnimation + 1); if(m_currentAnimation >= e_SkinPreviewAnimation_Count) m_currentAnimation = e_SkinPreviewAnimation_Walking; m_swingTime = 0.0f; @@ -175,8 +175,8 @@ void UIControl_PlayerSkinPreview::CycleNextAnimation() void UIControl_PlayerSkinPreview::CyclePreviousAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); - if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = (ESkinPreviewAnimations)(e_SkinPreviewAnimation_Count - 1); + m_currentAnimation = static_cast(m_currentAnimation - 1); + if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = static_cast(e_SkinPreviewAnimation_Count - 1); m_swingTime = 0.0f; } @@ -210,7 +210,7 @@ void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) Lighting::turnOn(); //glRotatef(-45 - 90, 0, 1, 0); - glRotatef(-(float)m_xRot, 1, 0, 0); + glRotatef(-static_cast(m_xRot), 1, 0, 0); // 4J Stu - Turning on hideGui while we do this stops the name rendering in split-screen bool wasHidingGui = pMinecraft->options->hideGui; @@ -218,7 +218,7 @@ void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) //EntityRenderDispatcher::instance->render(pMinecraft->localplayers[0], 0, 0, 0, 0, 1); EntityRenderer *renderer = EntityRenderDispatcher::instance->getRenderer(eTYPE_LOCALPLAYER); - if (renderer != NULL) + if (renderer != nullptr) { // 4J-PB - any additional parts to turn on for this player (skin dependent) //vector *pAdditionalModelParts=mob->GetAdditionalModelParts(); @@ -257,12 +257,12 @@ void UIControl_PlayerSkinPreview::render(EntityRenderer *renderer, double x, dou glPushMatrix(); glDisable(GL_CULL_FACE); - HumanoidModel *model = (HumanoidModel *)renderer->getModel(); + HumanoidModel *model = static_cast(renderer->getModel()); //getAttackAnim(mob, a); - //if (armor != NULL) armor->attackTime = model->attackTime; + //if (armor != nullptr) armor->attackTime = model->attackTime; //model->riding = mob->isRiding(); - //if (armor != NULL) armor->riding = model->riding; + //if (armor != nullptr) armor->riding = model->riding; // 4J Stu - Remember to reset these values once the rendering is done if you add another one model->attackTime = 0; @@ -292,7 +292,7 @@ void UIControl_PlayerSkinPreview::render(EntityRenderer *renderer, double x, dou { m_swingTime = 0; } - model->attackTime = m_swingTime / (float) (Player::SWING_DURATION * 3); + model->attackTime = m_swingTime / static_cast(Player::SWING_DURATION * 3); break; default: break; @@ -306,7 +306,7 @@ void UIControl_PlayerSkinPreview::render(EntityRenderer *renderer, double x, dou //setupPosition(mob, x, y, z); // is equivalent to - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); //float bob = getBob(mob, a); #ifdef SKIN_PREVIEW_BOB_ANIM @@ -383,11 +383,11 @@ void UIControl_PlayerSkinPreview::render(EntityRenderer *renderer, double x, dou double xa = sin(yr * PI / 180); double za = -cos(yr * PI / 180); - float flap = (float) yd * 10; + float flap = static_cast(yd) * 10; if (flap < -6) flap = -6; if (flap > 32) flap = 32; - float lean = (float) (xd * xa + zd * za) * 100; - float lean2 = (float) (xd * za - zd * xa) * 100; + float lean = static_cast(xd * xa + zd * za) * 100; + float lean2 = static_cast(xd * za - zd * xa) * 100; if (lean < 0) lean = 0; //float pow = 1;//mob->oBob + (bob - mob->oBob) * a; diff --git a/Minecraft.Client/Common/UI/UIControl_Progress.cpp b/Minecraft.Client/Common/UI/UIControl_Progress.cpp index 78e7c1d0c..20dc1ff7e 100644 --- a/Minecraft.Client/Common/UI/UIControl_Progress.cpp +++ b/Minecraft.Client/Common/UI/UIControl_Progress.cpp @@ -53,7 +53,7 @@ void UIControl_Progress::setProgress(int current) { m_current = current; - float percent = (float)((m_current-m_min))/(m_max-m_min); + float percent = static_cast((m_current - m_min))/(m_max-m_min); if(percent != m_lastPercent) { diff --git a/Minecraft.Client/Common/UI/UIControl_SaveList.cpp b/Minecraft.Client/Common/UI/UIControl_SaveList.cpp index f83454d73..5ae9c8f05 100644 --- a/Minecraft.Client/Common/UI/UIControl_SaveList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_SaveList.cpp @@ -52,7 +52,7 @@ void UIControl_SaveList::addItem(const string &label, const wstring &iconName, i IggyStringUTF8 stringVal; stringVal.string = (char*)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF8; value[0].string8 = stringVal; @@ -74,7 +74,7 @@ void UIControl_SaveList::addItem(const wstring &label, const wstring &iconName, IggyStringUTF16 stringVal; stringVal.string = (IggyUTF16*)label.c_str(); - stringVal.length = (S32)label.length(); + stringVal.length = static_cast(label.length()); value[0].type = IGGY_DATATYPE_string_UTF16; value[0].string16 = stringVal; diff --git a/Minecraft.Client/Common/UI/UIControl_Slider.cpp b/Minecraft.Client/Common/UI/UIControl_Slider.cpp index c21680029..2d56a29c0 100644 --- a/Minecraft.Client/Common/UI/UIControl_Slider.cpp +++ b/Minecraft.Client/Common/UI/UIControl_Slider.cpp @@ -92,12 +92,12 @@ void UIControl_Slider::SetSliderTouchPos(float fTouchPos) S32 UIControl_Slider::GetRealWidth() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealWidth , 0 , nullptr ); S32 iRealWidth = m_width; if(result.type == IGGY_DATATYPE_number) { - iRealWidth = (S32)result.number; + iRealWidth = static_cast(result.number); } return iRealWidth; } diff --git a/Minecraft.Client/Common/UI/UIControl_SpaceIndicatorBar.cpp b/Minecraft.Client/Common/UI/UIControl_SpaceIndicatorBar.cpp index 653b05926..75bbac298 100644 --- a/Minecraft.Client/Common/UI/UIControl_SpaceIndicatorBar.cpp +++ b/Minecraft.Client/Common/UI/UIControl_SpaceIndicatorBar.cpp @@ -63,7 +63,7 @@ void UIControl_SpaceIndicatorBar::reset() void UIControl_SpaceIndicatorBar::addSave(int64_t size) { - float startPercent = (float)((m_currentTotal-m_min))/(m_max-m_min); + float startPercent = static_cast((m_currentTotal - m_min))/(m_max-m_min); m_sizeAndOffsets.push_back( pair(size, startPercent) ); @@ -90,7 +90,7 @@ void UIControl_SpaceIndicatorBar::setSaveSize(int64_t size) { m_currentSave = size; - float percent = (float)((m_currentSave-m_min))/(m_max-m_min); + float percent = static_cast((m_currentSave - m_min))/(m_max-m_min); IggyDataValue result; IggyDataValue value[1]; @@ -101,7 +101,7 @@ void UIControl_SpaceIndicatorBar::setSaveSize(int64_t size) void UIControl_SpaceIndicatorBar::setTotalSize(int64_t size) { - float percent = (float)((m_currentTotal-m_min))/(m_max-m_min); + float percent = static_cast((m_currentTotal - m_min))/(m_max-m_min); IggyDataValue result; IggyDataValue value[1]; diff --git a/Minecraft.Client/Common/UI/UIControl_TexturePackList.cpp b/Minecraft.Client/Common/UI/UIControl_TexturePackList.cpp index 02336e004..7f721493a 100644 --- a/Minecraft.Client/Common/UI/UIControl_TexturePackList.cpp +++ b/Minecraft.Client/Common/UI/UIControl_TexturePackList.cpp @@ -83,7 +83,7 @@ void UIControl_TexturePackList::selectSlot(int id) void UIControl_TexturePackList::clearSlots() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_clearSlotsFunc ,0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath(), m_clearSlotsFunc ,0 , nullptr ); } void UIControl_TexturePackList::setEnabled(bool enable) @@ -125,7 +125,7 @@ bool UIControl_TexturePackList::CanTouchTrigger(S32 iX, S32 iY) S32 bCanTouchTrigger = false; if(result.type == IGGY_DATATYPE_boolean) { - bCanTouchTrigger = (bool)result.boolval; + bCanTouchTrigger = static_cast(result.boolval); } return bCanTouchTrigger; } @@ -133,12 +133,12 @@ bool UIControl_TexturePackList::CanTouchTrigger(S32 iX, S32 iY) S32 UIControl_TexturePackList::GetRealHeight() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( m_parentScene->getMovie() , &result, getIggyValuePath() , m_funcGetRealHeight, 0 , nullptr ); S32 iRealHeight = m_height; if(result.type == IGGY_DATATYPE_number) { - iRealHeight = (S32)result.number; + iRealHeight = static_cast(result.number); } return iRealHeight; } diff --git a/Minecraft.Client/Common/UI/UIController.cpp b/Minecraft.Client/Common/UI/UIController.cpp index 840ed389e..b12ea5e73 100644 --- a/Minecraft.Client/Common/UI/UIController.cpp +++ b/Minecraft.Client/Common/UI/UIController.cpp @@ -13,6 +13,7 @@ #include "..\..\EnderDragonRenderer.h" #include "..\..\MultiPlayerLocalPlayer.h" #include "UIFontData.h" +#include "UISplitScreenHelpers.h" #ifdef _WINDOWS64 #include "..\..\Windows64\KeyboardMouseInput.h" #endif @@ -57,18 +58,20 @@ bool UIController::ms_bReloadSkinCSInitialised = false; DWORD UIController::m_dwTrialTimerLimitSecs=DYNAMIC_CONFIG_DEFAULT_TRIAL_TIME; +// GetViewportRect and Fit16x9 are now in UISplitScreenHelpers.h + #ifdef _WINDOWS64 static UIControl_Slider *FindSliderById(UIScene *pScene, int sliderId) { vector *controls = pScene->GetControls(); - if (!controls) return NULL; + if (!controls) return nullptr; for (size_t i = 0; i < controls->size(); ++i) { UIControl *ctrl = (*controls)[i]; if (ctrl && ctrl->getControlType() == UIControl::eSlider && ctrl->getId() == sliderId) - return (UIControl_Slider *)ctrl; + return static_cast(ctrl); } - return NULL; + return nullptr; } #endif @@ -148,7 +151,7 @@ int64_t UIController::iggyAllocCount = 0; static unordered_map allocations; static void * RADLINK AllocateFunction ( void * alloc_callback_user_data , size_t size_requested , size_t * size_returned ) { - UIController *controller = (UIController *)alloc_callback_user_data; + UIController *controller = static_cast(alloc_callback_user_data); EnterCriticalSection(&controller->m_Allocatorlock); #ifdef EXCLUDE_IGGY_ALLOCATIONS_FROM_HEAP_INSPECTOR void *alloc = __real_malloc(size_requested); @@ -165,7 +168,7 @@ static void * RADLINK AllocateFunction ( void * alloc_callback_user_data , size_ static void RADLINK DeallocateFunction ( void * alloc_callback_user_data , void * ptr ) { - UIController *controller = (UIController *)alloc_callback_user_data; + UIController *controller = static_cast(alloc_callback_user_data); EnterCriticalSection(&controller->m_Allocatorlock); size_t size = allocations[ptr]; UIController::iggyAllocCount -= size; @@ -181,15 +184,15 @@ static void RADLINK DeallocateFunction ( void * alloc_callback_user_data , void UIController::UIController() { - m_uiDebugConsole = NULL; - m_reloadSkinThread = NULL; + m_uiDebugConsole = nullptr; + m_reloadSkinThread = nullptr; m_navigateToHomeOnReload = false; m_bCleanupOnReload = false; - m_mcTTFFont = NULL; - m_moj7 = NULL; - m_moj11 = NULL; + m_mcTTFFont = nullptr; + m_moj7 = nullptr; + m_moj11 = nullptr; // 4J-JEV: It's important that these remain the same, unless updateCurrentLanguage is going to be called. m_eCurrentFont = m_eTargetFont = eFont_NotLoaded; @@ -270,7 +273,7 @@ void UIController::SetSysUIShowing(bool bVal) void UIController::SetSystemUIShowing(LPVOID lpParam,bool bVal) { - UIController *pClass=(UIController *)lpParam; + UIController *pClass=static_cast(lpParam); pClass->SetSysUIShowing(bVal); } @@ -310,13 +313,13 @@ void UIController::postInit() for(unsigned int i = 0; i < eUIGroup_COUNT; ++i) { - m_groups[i] = new UIGroup((EUIGroup)i,i-1); + m_groups[i] = new UIGroup(static_cast(i),i-1); } #ifdef ENABLE_IGGY_EXPLORER iggy_explorer = IggyExpCreate("127.0.0.1", 9190, malloc(IGGYEXP_MIN_STORAGE), IGGYEXP_MIN_STORAGE); - if ( iggy_explorer == NULL ) + if ( iggy_explorer == nullptr ) { // not normally an error, just an error for this demo! app.DebugPrintf( "Couldn't connect to Iggy Explorer, did you run it first?" ); @@ -329,7 +332,7 @@ void UIController::postInit() #ifdef ENABLE_IGGY_PERFMON m_iggyPerfmonEnabled = false; - iggy_perfmon = IggyPerfmonCreate(perf_malloc, perf_free, NULL); + iggy_perfmon = IggyPerfmonCreate(perf_malloc, perf_free, nullptr); IggyInstallPerfmon(iggy_perfmon); #endif @@ -370,7 +373,7 @@ UITTFFont *UIController::createFont(EFont fontLanguage) #endif // 4J-JEV, Cyrillic characters have been added to this font now, (4/July/14) // XC_LANGUAGE_RUSSIAN and XC_LANGUAGE_GREEK: - default: return NULL; + default: return nullptr; } } @@ -397,17 +400,17 @@ void UIController::SetupFont() if (m_eCurrentFont != eFont_NotLoaded) app.DebugPrintf("[UIController] Font switch required for language transition to %i.\n", nextLanguage); else app.DebugPrintf("[UIController] Initialising font for language %i.\n", nextLanguage); - if (m_mcTTFFont != NULL) + if (m_mcTTFFont != nullptr) { delete m_mcTTFFont; - m_mcTTFFont = NULL; + m_mcTTFFont = nullptr; } if(m_eTargetFont == eFont_Bitmap) { // these may have been set up by a previous language being chosen - if (m_moj7 == NULL) m_moj7 = new UIBitmapFont(SFontData::Mojangles_7); - if (m_moj11 == NULL) m_moj11 = new UIBitmapFont(SFontData::Mojangles_11); + if (m_moj7 == nullptr) m_moj7 = new UIBitmapFont(SFontData::Mojangles_7); + if (m_moj11 == nullptr) m_moj11 = new UIBitmapFont(SFontData::Mojangles_11); // 4J-JEV: Ensure we redirect to them correctly, even if the objects were previously initialised. m_moj7->registerFont(); @@ -519,52 +522,9 @@ void UIController::tick() void UIController::loadSkins() { - wstring platformSkinPath = L""; - #ifdef __PS3__ - platformSkinPath = L"skinPS3.swf"; -#elif defined __PSVITA__ - platformSkinPath = L"skinVita.swf"; -#elif defined _WINDOWS64 - if(m_fScreenHeight>720.0f) - { - platformSkinPath = L"skinHDWin.swf"; - } - else - { - platformSkinPath = L"skinWin.swf"; - } -#elif defined _DURANGO - if(m_fScreenHeight>720.0f) - { - platformSkinPath = L"skinHDDurango.swf"; - } - else - { - platformSkinPath = L"skinDurango.swf"; - } -#elif defined __ORBIS__ - if(m_fScreenHeight>720.0f) - { - platformSkinPath = L"skinHDOrbis.swf"; - } - else - { - platformSkinPath = L"skinOrbis.swf"; - } + m_iggyLibraries[eLibrary_Platform] = loadSkin(L"skinPS3.swf", L"platformskin.swf"); -#endif - // Every platform has one of these, so nothing shared - if(m_fScreenHeight>720.0f) - { - m_iggyLibraries[eLibrary_Platform] = loadSkin(platformSkinPath, L"platformskinHD.swf"); - } - else - { - m_iggyLibraries[eLibrary_Platform] = loadSkin(platformSkinPath, L"platformskin.swf"); - } - -#if defined(__PS3__) || defined(__PSVITA__) m_iggyLibraries[eLibrary_GraphicsDefault] = loadSkin(L"skinGraphics.swf", L"skinGraphics.swf"); m_iggyLibraries[eLibrary_GraphicsHUD] = loadSkin(L"skinGraphicsHud.swf", L"skinGraphicsHud.swf"); m_iggyLibraries[eLibrary_GraphicsInGame] = loadSkin(L"skinGraphicsInGame.swf", L"skinGraphicsInGame.swf"); @@ -575,13 +535,28 @@ void UIController::loadSkins() m_iggyLibraries[eLibrary_HUD] = loadSkin(L"skinHud.swf", L"skinHud.swf"); m_iggyLibraries[eLibrary_Tooltips] = loadSkin(L"skinTooltips.swf", L"skinTooltips.swf"); m_iggyLibraries[eLibrary_Default] = loadSkin(L"skin.swf", L"skin.swf"); -#endif -#if ( defined(_WINDOWS64) || defined(_DURANGO) || defined(__ORBIS__) ) +#elif defined __PSVITA__ + m_iggyLibraries[eLibrary_Platform] = loadSkin(L"skinVita.swf", L"platformskin.swf"); -#if defined(_WINDOWS64) - // 4J Stu - Load the 720/480 skins so that we have something to fallback on during development -#ifndef _FINAL_BUILD + m_iggyLibraries[eLibrary_GraphicsDefault] = loadSkin(L"skinGraphics.swf", L"skinGraphics.swf"); + m_iggyLibraries[eLibrary_GraphicsHUD] = loadSkin(L"skinGraphicsHud.swf", L"skinGraphicsHud.swf"); + m_iggyLibraries[eLibrary_GraphicsInGame] = loadSkin(L"skinGraphicsInGame.swf", L"skinGraphicsInGame.swf"); + m_iggyLibraries[eLibrary_GraphicsTooltips] = loadSkin(L"skinGraphicsTooltips.swf", L"skinGraphicsTooltips.swf"); + m_iggyLibraries[eLibrary_GraphicsLabels] = loadSkin(L"skinGraphicsLabels.swf", L"skinGraphicsLabels.swf"); + m_iggyLibraries[eLibrary_Labels] = loadSkin(L"skinLabels.swf", L"skinLabels.swf"); + m_iggyLibraries[eLibrary_InGame] = loadSkin(L"skinInGame.swf", L"skinInGame.swf"); + m_iggyLibraries[eLibrary_HUD] = loadSkin(L"skinHud.swf", L"skinHud.swf"); + m_iggyLibraries[eLibrary_Tooltips] = loadSkin(L"skinTooltips.swf", L"skinTooltips.swf"); + m_iggyLibraries[eLibrary_Default] = loadSkin(L"skin.swf", L"skin.swf"); + +#elif defined _WINDOWS64 + // HD platform skin — required by skinHD*.swf (1080p scene SWFs) + m_iggyLibraries[eLibrary_Platform] = loadSkin(L"skinHDWin.swf", L"platformskinHD.swf"); + // Non-HD platform skin — required by skin*.swf (720p/480p scene SWFs) + m_iggyLibraries[eLibraryFallback_Platform] = loadSkin(L"skinWin.swf", L"platformskin.swf"); + + // Non-HD skin set (720p/480p scenes import these) m_iggyLibraries[eLibraryFallback_GraphicsDefault] = loadSkin(L"skinGraphics.swf", L"skinGraphics.swf"); m_iggyLibraries[eLibraryFallback_GraphicsHUD] = loadSkin(L"skinGraphicsHud.swf", L"skinGraphicsHud.swf"); m_iggyLibraries[eLibraryFallback_GraphicsInGame] = loadSkin(L"skinGraphicsInGame.swf", L"skinGraphicsInGame.swf"); @@ -592,8 +567,21 @@ void UIController::loadSkins() m_iggyLibraries[eLibraryFallback_HUD] = loadSkin(L"skinHud.swf", L"skinHud.swf"); m_iggyLibraries[eLibraryFallback_Tooltips] = loadSkin(L"skinTooltips.swf", L"skinTooltips.swf"); m_iggyLibraries[eLibraryFallback_Default] = loadSkin(L"skin.swf", L"skin.swf"); -#endif -#endif + + // HD skin set (1080p scenes import these) + m_iggyLibraries[eLibrary_GraphicsDefault] = loadSkin(L"skinHDGraphics.swf", L"skinHDGraphics.swf"); + m_iggyLibraries[eLibrary_GraphicsHUD] = loadSkin(L"skinHDGraphicsHud.swf", L"skinHDGraphicsHud.swf"); + m_iggyLibraries[eLibrary_GraphicsInGame] = loadSkin(L"skinHDGraphicsInGame.swf", L"skinHDGraphicsInGame.swf"); + m_iggyLibraries[eLibrary_GraphicsTooltips] = loadSkin(L"skinHDGraphicsTooltips.swf", L"skinHDGraphicsTooltips.swf"); + m_iggyLibraries[eLibrary_GraphicsLabels] = loadSkin(L"skinHDGraphicsLabels.swf", L"skinHDGraphicsLabels.swf"); + m_iggyLibraries[eLibrary_Labels] = loadSkin(L"skinHDLabels.swf", L"skinHDLabels.swf"); + m_iggyLibraries[eLibrary_InGame] = loadSkin(L"skinHDInGame.swf", L"skinHDInGame.swf"); + m_iggyLibraries[eLibrary_HUD] = loadSkin(L"skinHDHud.swf", L"skinHDHud.swf"); + m_iggyLibraries[eLibrary_Tooltips] = loadSkin(L"skinHDTooltips.swf", L"skinHDTooltips.swf"); + m_iggyLibraries[eLibrary_Default] = loadSkin(L"skinHD.swf", L"skinHD.swf"); + +#elif defined _DURANGO + m_iggyLibraries[eLibrary_Platform] = loadSkin(L"skinHDDurango.swf", L"platformskinHD.swf"); m_iggyLibraries[eLibrary_GraphicsDefault] = loadSkin(L"skinHDGraphics.swf", L"skinHDGraphics.swf"); m_iggyLibraries[eLibrary_GraphicsHUD] = loadSkin(L"skinHDGraphicsHud.swf", L"skinHDGraphicsHud.swf"); @@ -605,7 +593,21 @@ void UIController::loadSkins() m_iggyLibraries[eLibrary_HUD] = loadSkin(L"skinHDHud.swf", L"skinHDHud.swf"); m_iggyLibraries[eLibrary_Tooltips] = loadSkin(L"skinHDTooltips.swf", L"skinHDTooltips.swf"); m_iggyLibraries[eLibrary_Default] = loadSkin(L"skinHD.swf", L"skinHD.swf"); -#endif // HD platforms + +#elif defined __ORBIS__ + m_iggyLibraries[eLibrary_Platform] = loadSkin(L"skinHDOrbis.swf", L"platformskinHD.swf"); + + m_iggyLibraries[eLibrary_GraphicsDefault] = loadSkin(L"skinHDGraphics.swf", L"skinHDGraphics.swf"); + m_iggyLibraries[eLibrary_GraphicsHUD] = loadSkin(L"skinHDGraphicsHud.swf", L"skinHDGraphicsHud.swf"); + m_iggyLibraries[eLibrary_GraphicsInGame] = loadSkin(L"skinHDGraphicsInGame.swf", L"skinHDGraphicsInGame.swf"); + m_iggyLibraries[eLibrary_GraphicsTooltips] = loadSkin(L"skinHDGraphicsTooltips.swf", L"skinHDGraphicsTooltips.swf"); + m_iggyLibraries[eLibrary_GraphicsLabels] = loadSkin(L"skinHDGraphicsLabels.swf", L"skinHDGraphicsLabels.swf"); + m_iggyLibraries[eLibrary_Labels] = loadSkin(L"skinHDLabels.swf", L"skinHDLabels.swf"); + m_iggyLibraries[eLibrary_InGame] = loadSkin(L"skinHDInGame.swf", L"skinHDInGame.swf"); + m_iggyLibraries[eLibrary_HUD] = loadSkin(L"skinHDHud.swf", L"skinHDHud.swf"); + m_iggyLibraries[eLibrary_Tooltips] = loadSkin(L"skinHDTooltips.swf", L"skinHDTooltips.swf"); + m_iggyLibraries[eLibrary_Default] = loadSkin(L"skinHD.swf", L"skinHD.swf"); +#endif } IggyLibrary UIController::loadSkin(const wstring &skinPath, const wstring &skinName) @@ -615,7 +617,7 @@ IggyLibrary UIController::loadSkin(const wstring &skinPath, const wstring &skinN if(!skinPath.empty() && app.hasArchiveFile(skinPath)) { byteArray baFile = app.getArchiveFile(skinPath); - lib = IggyLibraryCreateFromMemoryUTF16( (IggyUTF16 *)skinName.c_str() , (void *)baFile.data, baFile.length, NULL ); + lib = IggyLibraryCreateFromMemoryUTF16( (IggyUTF16 *)skinName.c_str() , (void *)baFile.data, baFile.length, nullptr ); delete[] baFile.data; #ifdef _DEBUG @@ -623,12 +625,12 @@ IggyLibrary UIController::loadSkin(const wstring &skinPath, const wstring &skinN rrbool res; int iteration = 0; int64_t totalStatic = 0; - while(res = IggyDebugGetMemoryUseInfo ( NULL , - lib , - "" , - 0 , - iteration , - &memoryInfo )) + while(res = IggyDebugGetMemoryUseInfo (nullptr, + lib , + "" , + 0 , + iteration , + &memoryInfo )) { totalStatic += memoryInfo.static_allocation_bytes; app.DebugPrintf(app.USER_SR, "%ls - %.*s, static: %dB, dynamic: %dB\n", skinPath.c_str(), memoryInfo.subcategory_stringlen, memoryInfo.subcategory, memoryInfo.static_allocation_bytes, memoryInfo.dynamic_allocation_bytes); @@ -692,7 +694,7 @@ void UIController::StartReloadSkinThread() int UIController::reloadSkinThreadProc(void* lpParam) { EnterCriticalSection(&ms_reloadSkinCS); // MGH - added to prevent crash loading Iggy movies while the skins were being reloaded - UIController *controller = (UIController *)lpParam; + UIController *controller = static_cast(lpParam); // Load new skin controller->loadSkins(); @@ -727,7 +729,7 @@ bool UIController::IsExpectingOrReloadingSkin() void UIController::CleanUpSkinReload() { delete m_reloadSkinThread; - m_reloadSkinThread = NULL; + m_reloadSkinThread = nullptr; if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { @@ -787,18 +789,19 @@ void UIController::tickInput() #endif { #ifdef _WINDOWS64 - m_mouseClickConsumedByScene = false; - if (!g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsKBMActive()) - { - UIScene *pScene = NULL; - // Search by layer priority across all groups (layer-first). - // Tooltip layer is skipped because it holds non-interactive - // overlays (button hints, timer) that should never capture mouse. - // Old group-first order found those tooltips on eUIGroup_Fullscreen - // before reaching in-game menus on eUIGroup_Player1. - static const EUILayer mouseLayers[] = { + m_mouseClickConsumedByScene = false; + if (!g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsKBMActive()) + { + UIScene *pScene = nullptr; + + // Search by layer priority across all groups (layer-first). + // Tooltip layer is skipped because it holds non-interactive + // overlays (button hints, timer) that should never capture mouse. + // Old group-first order found those tooltips on eUIGroup_Fullscreen + // before reaching in-game menus on eUIGroup_Player1. + static const EUILayer mouseLayers[] = { #ifndef _CONTENT_PACKAGE - eUILayer_Debug, + eUILayer_Debug, #endif eUILayer_Error, eUILayer_Alert, @@ -806,17 +809,36 @@ void UIController::tickInput() eUILayer_Fullscreen, eUILayer_Scene, }; - for (int l = 0; l < _countof(mouseLayers) && !pScene; ++l) + // Only check the fullscreen group and the primary (KBM) player's group. + // Other splitscreen players use controllers — mouse must not affect them. + const int mouseGroups[] = { static_cast(eUIGroup_Fullscreen), ProfileManager.GetPrimaryPad() + 1 }; + for (int l = 0; l < _countof(mouseLayers) && !pScene; ++l) + { + for (int g = 0; g < _countof(mouseGroups) && !pScene; ++g) { - for (int grp = 0; grp < eUIGroup_COUNT && !pScene; ++grp) - { - pScene = m_groups[grp]->GetTopScene(mouseLayers[l]); - } + pScene = m_groups[mouseGroups[g]]->GetTopScene(mouseLayers[l]); } + } if (pScene && pScene->getMovie()) - { - int rawMouseX = g_KBMInput.GetMouseX(); - int rawMouseY = g_KBMInput.GetMouseY(); + { + int rawMouseX = g_KBMInput.GetMouseX(); + int rawMouseY = g_KBMInput.GetMouseY(); + F32 mouseX = static_cast(rawMouseX); + F32 mouseY = static_cast(rawMouseY); + + extern HWND g_hWnd; + if (g_hWnd) + { + RECT rc; + GetClientRect(g_hWnd, &rc); + int winW = rc.right - rc.left; + int winH = rc.bottom - rc.top; + if (winW > 0 && winH > 0) + { + mouseX = mouseX * (m_fScreenWidth / static_cast(winW)); + mouseY = mouseY * (m_fScreenHeight / static_cast(winH)); + } + } // Only update hover focus when the mouse has actually moved, // so that mouse-wheel scrolling can change list selection @@ -825,9 +847,14 @@ void UIController::tickInput() m_lastHoverMouseX = rawMouseX; m_lastHoverMouseY = rawMouseY; - // Convert mouse to scene/movie coordinates - F32 sceneMouseX = (F32)rawMouseX; - F32 sceneMouseY = (F32)rawMouseY; + // Convert mouse window-pixel coords to Flash/SWF authoring coords. + // In split-screen the scene is rendered at a tile-origin offset + // and at a smaller display size, so we must: + // 1. Map window pixels -> UIController screen space + // 2. Subtract the viewport tile origin + // 3. Scale from display dimensions to SWF authoring dimensions + F32 sceneMouseX = static_cast(rawMouseX); + F32 sceneMouseY = static_cast(rawMouseY); { extern HWND g_hWnd; RECT rc; @@ -837,8 +864,30 @@ void UIController::tickInput() int winH = rc.bottom - rc.top; if (winW > 0 && winH > 0) { - sceneMouseX = sceneMouseX * ((F32)pScene->getRenderWidth() / (F32)winW); - sceneMouseY = sceneMouseY * ((F32)pScene->getRenderHeight() / (F32)winH); + // Step 1: window pixels -> screen space + F32 screenX = sceneMouseX * (getScreenWidth() / static_cast(winW)); + F32 screenY = sceneMouseY * (getScreenHeight() / static_cast(winH)); + + // Step 2 & 3: account for split-screen viewport + C4JRender::eViewportType vp = pScene->GetParentLayer()->getViewport(); + S32 displayW = 0, displayH = 0; + getRenderDimensions(vp, displayW, displayH); + + F32 vpOriginX, vpOriginY, vpW, vpH; + GetViewportRect(getScreenWidth(), getScreenHeight(), vp, vpOriginX, vpOriginY, vpW, vpH); + // All viewports use Fit16x9 for menu scenes + S32 fitW, fitH, fitOffsetX, fitOffsetY; + Fit16x9(vpW, vpH, fitW, fitH, fitOffsetX, fitOffsetY); + S32 originX = static_cast(vpOriginX) + fitOffsetX; + S32 originY = static_cast(vpOriginY) + fitOffsetY; + displayW = fitW; + displayH = fitH; + + if (displayW > 0 && displayH > 0) + { + sceneMouseX = (screenX - originX) * (static_cast(pScene->getRenderWidth()) / static_cast(displayW)); + sceneMouseY = (screenY - originY) * (static_cast(pScene->getRenderHeight()) / static_cast(displayH)); + } } } } @@ -890,7 +939,7 @@ void UIController::tickInput() // TexturePackList origin is where the slot area starts, // not the top-left of the whole control — use GetRealHeight. if (type == UIControl::eTexturePackList) - ch = ((UIControl_TexturePackList *)ctrl)->GetRealHeight(); + ch = static_cast(ctrl)->GetRealHeight(); if (cw <= 0 || ch <= 0) continue; @@ -901,8 +950,8 @@ void UIController::tickInput() { // ButtonList manages focus internally via Flash — // pass mouse coords so it can highlight the right item. - ((UIControl_ButtonList *)ctrl)->SetTouchFocus( - (S32)sceneMouseX, (S32)sceneMouseY, false); + static_cast(ctrl)->SetTouchFocus( + static_cast(sceneMouseX), static_cast(sceneMouseY), false); hitControlId = -1; hitArea = INT_MAX; hitCtrl = NULL; @@ -911,10 +960,10 @@ void UIController::tickInput() if (type == UIControl::eTexturePackList) { // TexturePackList expects coords relative to its origin. - UIControl_TexturePackList *pList = (UIControl_TexturePackList *)ctrl; + UIControl_TexturePackList *pList = static_cast(ctrl); pScene->SetFocusToElement(ctrl->getId()); pList->SetTouchFocus( - (S32)(sceneMouseX - cx), (S32)(sceneMouseY - cy), false); + static_cast(sceneMouseX - cx), static_cast(sceneMouseY - cy), false); m_bMouseHoverHorizontalList = true; hitControlId = -1; hitArea = INT_MAX; @@ -950,7 +999,7 @@ void UIController::tickInput() // happens after both tickInput and scene tick, so no flicker. if (hitCtrl && hitCtrl->getControlType() == UIControl::eTextInput) { - ((UIControl_TextInput *)hitCtrl)->setCaretVisible(false); + static_cast(hitCtrl)->setCaretVisible(false); } } } @@ -1016,7 +1065,7 @@ void UIController::tickInput() if (pMainPanel && ctrl->getParentPanel() != pMainPanel) continue; - UIControl_Slider *pSlider = (UIControl_Slider *)ctrl; + UIControl_Slider *pSlider = static_cast(ctrl); pSlider->UpdateControl(); S32 cx = pSlider->getXPos() + panelOffsetX; S32 cy = pSlider->getYPos() + panelOffsetY; @@ -1045,7 +1094,7 @@ void UIController::tickInput() S32 sliderWidth = pSlider->GetRealWidth(); if (sliderWidth > 0) { - float fNewSliderPos = (sceneMouseX - (float)sliderX) / (float)sliderWidth; + float fNewSliderPos = (sceneMouseX - static_cast(sliderX)) / static_cast(sliderWidth); if (fNewSliderPos < 0.0f) fNewSliderPos = 0.0f; if (fNewSliderPos > 1.0f) fNewSliderPos = 1.0f; pSlider->SetSliderTouchPos(fNewSliderPos); @@ -1132,7 +1181,7 @@ void UIController::handleInput() if(ProfileManager.GetLockedProfile() >= 0 && !InputManager.IsPadLocked( ProfileManager.GetLockedProfile() ) && firstUnfocussedUnhandledPad >= 0) { - ProfileManager.RequestSignInUI(false, false, false, false, true, NULL, NULL, firstUnfocussedUnhandledPad ); + ProfileManager.RequestSignInUI(false, false, false, false, true, nullptr, nullptr, firstUnfocussedUnhandledPad ); } } #endif @@ -1159,8 +1208,8 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) if((m_bTouchscreenPressed==false) && pTouchData->reportNum==1) { // no active touch? clear active and highlighted touch UI elements - m_ActiveUIElement = NULL; - m_HighlightedUIElement = NULL; + m_ActiveUIElement = nullptr; + m_HighlightedUIElement = nullptr; // fullscreen first UIScene *pScene=m_groups[(int)eUIGroup_Fullscreen]->getCurrentScene(); @@ -1460,7 +1509,7 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) IggyMemoryUseInfo memoryInfo; rrbool res; int iteration = 0; - while(res = IggyDebugGetMemoryUseInfo ( NULL , + while(res = IggyDebugGetMemoryUseInfo ( nullptr , m_iggyLibraries[i] , "" , 0 , @@ -1491,7 +1540,7 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) bool handled = false; // Send the key to the fullscreen group first - m_groups[(int)eUIGroup_Fullscreen]->handleInput(iPad, key, repeat, pressed, released, handled); + m_groups[static_cast(eUIGroup_Fullscreen)]->handleInput(iPad, key, repeat, pressed, released, handled); if(!handled) { // If it's not been handled yet, then pass the event onto the players specific group @@ -1502,9 +1551,9 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) rrbool RADLINK UIController::ExternalFunctionCallback( void * user_callback_data , Iggy * player , IggyExternalFunctionCallUTF16 * call) { - UIScene *scene = (UIScene *)IggyPlayerGetUserdata(player); + UIScene *scene = static_cast(IggyPlayerGetUserdata(player)); - if(scene != NULL) + if(scene != nullptr) { scene->externalCallback(call); } @@ -1566,73 +1615,48 @@ void UIController::renderScenes() void UIController::getRenderDimensions(C4JRender::eViewportType viewport, S32 &width, S32 &height) { - switch( viewport ) + F32 originX, originY, viewW, viewH; + GetViewportRect(getScreenWidth(), getScreenHeight(), viewport, originX, originY, viewW, viewH); + + if(viewport == C4JRender::VIEWPORT_TYPE_FULLSCREEN) { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - width = (S32)(getScreenWidth()); - height = (S32)(getScreenHeight()); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - width = (S32)(getScreenWidth() / 2); - height = (S32)(getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - width = (S32)(getScreenWidth() / 2); - height = (S32)(getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - width = (S32)(getScreenWidth() / 2); - height = (S32)(getScreenHeight() / 2); - break; + S32 offsetX, offsetY; + Fit16x9(viewW, viewH, width, height, offsetX, offsetY); + } + else + { + // Split-screen: use raw viewport dims — the SWF tiling code handles non-16:9 + width = static_cast(viewW); + height = static_cast(viewH); } } void UIController::setupRenderPosition(C4JRender::eViewportType viewport) { - if(m_bCustomRenderPosition || m_currentRenderViewport != viewport) + m_currentRenderViewport = viewport; + m_bCustomRenderPosition = false; + + F32 vpOriginX, vpOriginY, vpW, vpH; + GetViewportRect(getScreenWidth(), getScreenHeight(), viewport, vpOriginX, vpOriginY, vpW, vpH); + + S32 xPos, yPos; + if(viewport == C4JRender::VIEWPORT_TYPE_FULLSCREEN) { - m_currentRenderViewport = viewport; - m_bCustomRenderPosition = false; - S32 xPos = 0; - S32 yPos = 0; - switch( viewport ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - xPos = (S32)(getScreenWidth() / 4); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - xPos = (S32)(getScreenWidth() / 4); - yPos = (S32)(getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - yPos = (S32)(getScreenHeight() / 4); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - xPos = (S32)(getScreenWidth() / 2); - yPos = (S32)(getScreenHeight() / 4); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(getScreenWidth() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(getScreenWidth() / 2); - yPos = (S32)(getScreenHeight() / 2); - break; - } - m_tileOriginX = xPos; - m_tileOriginY = yPos; - setTileOrigin(xPos, yPos); + S32 fitW, fitH, fitOffsetX, fitOffsetY; + Fit16x9(vpW, vpH, fitW, fitH, fitOffsetX, fitOffsetY); + xPos = static_cast(vpOriginX) + fitOffsetX; + yPos = static_cast(vpOriginY) + fitOffsetY; } + else + { + // Split-screen: position at viewport origin, no 16:9 fitting + xPos = static_cast(vpOriginX); + yPos = static_cast(vpOriginY); + } + + m_tileOriginX = xPos; + m_tileOriginY = yPos; + setTileOrigin(xPos, yPos); } void UIController::setupRenderPosition(S32 xOrigin, S32 yOrigin) @@ -1691,8 +1715,8 @@ void UIController::setupCustomDrawMatrices(UIScene *scene, CustomDrawData *custo Minecraft *pMinecraft=Minecraft::GetInstance(); // Clear just the region required for this control. - float sceneWidth = (float)scene->getRenderWidth(); - float sceneHeight = (float)scene->getRenderHeight(); + float sceneWidth = static_cast(scene->getRenderWidth()); + float sceneHeight = static_cast(scene->getRenderHeight()); LONG left, right, top, bottom; #ifdef __PS3__ @@ -1720,10 +1744,10 @@ void UIController::setupCustomDrawMatrices(UIScene *scene, CustomDrawData *custo if(!m_bScreenWidthSetup) { Minecraft *pMinecraft=Minecraft::GetInstance(); - if(pMinecraft != NULL) + if(pMinecraft != nullptr) { - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fScreenHeight=(float)pMinecraft->height_phys; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fScreenHeight=static_cast(pMinecraft->height_phys); m_bScreenWidthSetup = true; } } @@ -1767,9 +1791,9 @@ void UIController::endCustomDrawGameStateAndMatrices() void RADLINK UIController::CustomDrawCallback(void *user_callback_data, Iggy *player, IggyCustomDrawCallbackRegion *region) { - UIScene *scene = (UIScene *)IggyPlayerGetUserdata(player); + UIScene *scene = static_cast(IggyPlayerGetUserdata(player)); - if(scene != NULL) + if(scene != nullptr) { scene->customDraw(region); } @@ -1781,7 +1805,7 @@ void RADLINK UIController::CustomDrawCallback(void *user_callback_data, Iggy *pl //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. +//return - A platform-independent wrapped texture handle provided by GDraw, or nullptr (nullptr with throw an ActionScript 3 ArgumentError that the Flash developer can catch) Use by calling IggySetTextureSubstitutionCallbacks. // //Discussion // @@ -1796,7 +1820,7 @@ GDrawTexture * RADLINK UIController::TextureSubstitutionCreateCallback ( void * 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 ) + if( image.getData() != nullptr ) { image.preMultiplyAlpha(); Textures *t = Minecraft::GetInstance()->textures; @@ -1804,28 +1828,38 @@ GDrawTexture * RADLINK UIController::TextureSubstitutionCreateCallback ( void * // 4J Stu - All our flash controls that allow replacing textures use a special 64x64 symbol // Force this size here so that our images don't get scaled wildly - #if (defined __ORBIS__ || defined _DURANGO || defined _WINDOWS64 ) + #if (defined __ORBIS__ || defined _DURANGO ) *width = 96; *height = 96; #else *width = 64; *height = 64; - #endif + + #if defined _WINDOWS64 + // Only set the size to 96x96 for 1080p on Windows + UIScene *scene = uiController->GetTopScene(0); + if (scene->getSceneResolution() == UIScene::eSceneResolution_1080) + { + *width = 96; + *height = 96; + } + #endif + *destroy_callback_data = (void *)id; - app.DebugPrintf("Found substitution texture %ls (%d) - %dx%d\n", (wchar_t *)texture_name, id, image.getWidth(), image.getHeight()); + app.DebugPrintf("Found substitution texture %ls (%d) - %dx%d\n", static_cast(texture_name), id, image.getWidth(), image.getHeight()); return ui.getSubstitutionTexture(id); } else { - return NULL; + return nullptr; } } else { - app.DebugPrintf("Could not find substitution texture %ls\n", (wchar_t *)texture_name); - return NULL; + app.DebugPrintf("Could not find substitution texture %ls\n", static_cast(texture_name)); + return nullptr; } } @@ -1835,13 +1869,16 @@ void RADLINK UIController::TextureSubstitutionDestroyCallback ( void * user_call { // Orbis complains about casting a pointer to an int LONGLONG llVal=(LONGLONG)destroy_callback_data; - int id=(int)llVal; + int id=static_cast(llVal); app.DebugPrintf("Destroying iggy texture %d\n", id); ui.destroySubstitutionTexture(user_callback_data, handle); - Textures *t = Minecraft::GetInstance()->textures; - t->releaseTexture( id ); + Minecraft* mc = Minecraft::GetInstance(); + if (mc && mc->textures) + { + mc->textures->releaseTexture( id ); + } } void UIController::registerSubstitutionTexture(const wstring &textureName, PBYTE pbData, DWORD dwLength) @@ -1937,7 +1974,7 @@ bool UIController::NavigateToScene(int iPad, EUIScene scene, void *initData, EUI if( ( iPad != 255 ) && ( iPad >= 0 ) ) { menuDisplayedPad = iPad; - group = (EUIGroup)(iPad+1); + group = static_cast(iPad + 1); } else group = eUIGroup_Fullscreen; } @@ -1952,7 +1989,7 @@ bool UIController::NavigateToScene(int iPad, EUIScene scene, void *initData, EUI EnterCriticalSection(&m_navigationLock); SetMenuDisplayed(menuDisplayedPad,true); - bool success = m_groups[(int)group]->NavigateToScene(iPad, scene, initData, layer); + bool success = m_groups[static_cast(group)]->NavigateToScene(iPad, scene, initData, layer); if(success && group == eUIGroup_Fullscreen) setFullscreenMenuDisplayed(true); LeaveCriticalSection(&m_navigationLock); @@ -1967,18 +2004,18 @@ bool UIController::NavigateBack(int iPad, bool forceUsePad, EUIScene eScene, EUI bool navComplete = false; if( app.GetGameStarted() ) { - bool navComplete = m_groups[(int)eUIGroup_Fullscreen]->NavigateBack(iPad, eScene, eLayer); + bool navComplete = m_groups[static_cast(eUIGroup_Fullscreen)]->NavigateBack(iPad, eScene, eLayer); if(!navComplete && ( iPad != 255 ) && ( iPad >= 0 ) ) { - EUIGroup group = (EUIGroup)(iPad+1); - navComplete = m_groups[(int)group]->NavigateBack(iPad, eScene, eLayer); - if(!m_groups[(int)group]->GetMenuDisplayed())SetMenuDisplayed(iPad,false); + EUIGroup group = static_cast(iPad + 1); + navComplete = m_groups[static_cast(group)]->NavigateBack(iPad, eScene, eLayer); + if(!m_groups[static_cast(group)]->GetMenuDisplayed())SetMenuDisplayed(iPad,false); } // 4J-PB - autosave in fullscreen doesn't clear the menuDisplayed flag else { - if(!m_groups[(int)eUIGroup_Fullscreen]->GetMenuDisplayed()) + if(!m_groups[static_cast(eUIGroup_Fullscreen)]->GetMenuDisplayed()) { setFullscreenMenuDisplayed(false); for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) @@ -1990,8 +2027,8 @@ bool UIController::NavigateBack(int iPad, bool forceUsePad, EUIScene eScene, EUI } else { - navComplete = m_groups[(int)eUIGroup_Fullscreen]->NavigateBack(iPad, eScene, eLayer); - if(!m_groups[(int)eUIGroup_Fullscreen]->GetMenuDisplayed()) SetMenuDisplayed(XUSER_INDEX_ANY,false); + navComplete = m_groups[static_cast(eUIGroup_Fullscreen)]->NavigateBack(iPad, eScene, eLayer); + if(!m_groups[static_cast(eUIGroup_Fullscreen)]->GetMenuDisplayed()) SetMenuDisplayed(XUSER_INDEX_ANY,false); } return navComplete; } @@ -2012,11 +2049,11 @@ void UIController::NavigateToHomeMenu() TexturePack *pTexPack=Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=NULL; + DLCTexturePack *pDLCTexPack=nullptr; if(pTexPack->hasAudio()) { // get the dlc texture pack, and store it - pDLCTexPack=(DLCTexturePack *)pTexPack; + pDLCTexPack=static_cast(pTexPack); } // change to the default texture pack @@ -2033,11 +2070,11 @@ void UIController::NavigateToHomeMenu() eStream_CD_1); pMinecraft->soundEngine->playStreaming(L"", 0, 0, 0, 1, 1); - // if(pDLCTexPack->m_pStreamedWaveBank!=NULL) + // if(pDLCTexPack->m_pStreamedWaveBank!=nullptr) // { // pDLCTexPack->m_pStreamedWaveBank->Destroy(); // } - // if(pDLCTexPack->m_pSoundBank!=NULL) + // if(pDLCTexPack->m_pSoundBank!=nullptr) // { // pDLCTexPack->m_pSoundBank->Destroy(); // } @@ -2071,7 +2108,7 @@ UIScene *UIController::GetTopScene(int iPad, EUILayer layer, EUIGroup group) // If the game isn't running treat as user 0, otherwise map index directly from pad if( ( iPad != 255 ) && ( iPad >= 0 ) ) { - group = (EUIGroup)(iPad+1); + group = static_cast(iPad + 1); } else group = eUIGroup_Fullscreen; } @@ -2081,7 +2118,7 @@ UIScene *UIController::GetTopScene(int iPad, EUILayer layer, EUIGroup group) group = eUIGroup_Fullscreen; } } - return m_groups[(int)group]->GetTopScene(layer); + return m_groups[static_cast(group)]->GetTopScene(layer); } size_t UIController::RegisterForCallbackId(UIScene *scene) @@ -2108,7 +2145,7 @@ void UIController::UnregisterCallbackId(size_t id) UIScene *UIController::GetSceneFromCallbackId(size_t id) { - UIScene *scene = NULL; + UIScene *scene = nullptr; auto it = m_registeredCallbackScenes.find(id); if(it != m_registeredCallbackScenes.end() ) { @@ -2129,7 +2166,7 @@ void UIController::LeaveCallbackIdCriticalSection() void UIController::CloseAllPlayersScenes() { - m_groups[(int)eUIGroup_Fullscreen]->getTooltips()->SetTooltips(-1); + m_groups[static_cast(eUIGroup_Fullscreen)]->getTooltips()->SetTooltips(-1); for(unsigned int i = 0; i < eUIGroup_COUNT; ++i) { //m_bCloseAllScenes[i] = true; @@ -2152,7 +2189,7 @@ void UIController::CloseUIScenes(int iPad, bool forceIPad) if( app.GetGameStarted() || forceIPad ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2160,22 +2197,22 @@ void UIController::CloseUIScenes(int iPad, bool forceIPad) group = eUIGroup_Fullscreen; } - m_groups[(int)group]->closeAllScenes(); - m_groups[(int)group]->getTooltips()->SetTooltips(-1); + m_groups[static_cast(group)]->closeAllScenes(); + m_groups[static_cast(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); + if(m_groups[static_cast(group)]->getTutorialPopup()) m_groups[static_cast(group)]->getTutorialPopup()->SetTutorialDescription(&popupInfo); if(group==eUIGroup_Fullscreen) setFullscreenMenuDisplayed(false); - SetMenuDisplayed((group == eUIGroup_Fullscreen ? XUSER_INDEX_ANY : iPad), m_groups[(int)group]->GetMenuDisplayed()); + SetMenuDisplayed((group == eUIGroup_Fullscreen ? XUSER_INDEX_ANY : iPad), m_groups[static_cast(group)]->GetMenuDisplayed()); } void UIController::setFullscreenMenuDisplayed(bool displayed) { // Show/hide the tooltips for the fullscreen group - m_groups[(int)eUIGroup_Fullscreen]->showComponent(ProfileManager.GetPrimaryPad(),eUIComponent_Tooltips,eUILayer_Tooltips,displayed); + m_groups[static_cast(eUIGroup_Fullscreen)]->showComponent(ProfileManager.GetPrimaryPad(),eUIComponent_Tooltips,eUILayer_Tooltips,displayed); // Show/hide tooltips for the other layers for(unsigned int i = (eUIGroup_Fullscreen+1); i < eUIGroup_COUNT; ++i) @@ -2190,14 +2227,14 @@ bool UIController::IsPauseMenuDisplayed(int iPad) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - return m_groups[(int)group]->IsPauseMenuDisplayed(); + return m_groups[static_cast(group)]->IsPauseMenuDisplayed(); } bool UIController::IsContainerMenuDisplayed(int iPad) @@ -2206,14 +2243,14 @@ bool UIController::IsContainerMenuDisplayed(int iPad) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - return m_groups[(int)group]->IsContainerMenuDisplayed(); + return m_groups[static_cast(group)]->IsContainerMenuDisplayed(); } bool UIController::IsIgnorePlayerJoinMenuDisplayed(int iPad) @@ -2222,14 +2259,14 @@ bool UIController::IsIgnorePlayerJoinMenuDisplayed(int iPad) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - return m_groups[(int)group]->IsIgnorePlayerJoinMenuDisplayed(); + return m_groups[static_cast(group)]->IsIgnorePlayerJoinMenuDisplayed(); } bool UIController::IsIgnoreAutosaveMenuDisplayed(int iPad) @@ -2238,14 +2275,14 @@ bool UIController::IsIgnoreAutosaveMenuDisplayed(int iPad) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - return m_groups[(int)eUIGroup_Fullscreen]->IsIgnoreAutosaveMenuDisplayed() || (group != eUIGroup_Fullscreen && m_groups[(int)group]->IsIgnoreAutosaveMenuDisplayed()); + return m_groups[static_cast(eUIGroup_Fullscreen)]->IsIgnoreAutosaveMenuDisplayed() || (group != eUIGroup_Fullscreen && m_groups[static_cast(group)]->IsIgnoreAutosaveMenuDisplayed()); } void UIController::SetIgnoreAutosaveMenuDisplayed(int iPad, bool displayed) @@ -2259,14 +2296,14 @@ bool UIController::IsSceneInStack(int iPad, EUIScene eScene) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - return m_groups[(int)group]->IsSceneInStack(eScene); + return m_groups[static_cast(group)]->IsSceneInStack(eScene); } bool UIController::GetMenuDisplayed(int iPad) @@ -2347,14 +2384,14 @@ void UIController::SetTooltipText( unsigned int iPad, unsigned int tooltip, int if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->SetTooltipText(tooltip, iTextID); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->SetTooltipText(tooltip, iTextID); } void UIController::SetEnableTooltips( unsigned int iPad, BOOL bVal ) @@ -2363,14 +2400,14 @@ void UIController::SetEnableTooltips( unsigned int iPad, BOOL bVal ) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->SetEnableTooltips(bVal); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->SetEnableTooltips(bVal); } void UIController::ShowTooltip( unsigned int iPad, unsigned int tooltip, bool show ) @@ -2379,14 +2416,14 @@ void UIController::ShowTooltip( unsigned int iPad, unsigned int tooltip, bool sh if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->ShowTooltip(tooltip,show); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->ShowTooltip(tooltip,show); } void UIController::SetTooltips( unsigned int iPad, int iA, int iB, int iX, int iY, int iLT, int iRT, int iLB, int iRB, int iLS, int iRS, int iBack, bool forceUpdate) @@ -2408,14 +2445,14 @@ void UIController::SetTooltips( unsigned int iPad, int iA, int iB, int iX, int i if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->SetTooltips(iA, iB, iX, iY, iLT, iRT, iLB, iRB, iLS, iRS, iBack, forceUpdate); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->SetTooltips(iA, iB, iX, iY, iLT, iRT, iLB, iRB, iLS, iRS, iBack, forceUpdate); } void UIController::EnableTooltip( unsigned int iPad, unsigned int tooltip, bool enable ) @@ -2424,14 +2461,14 @@ void UIController::EnableTooltip( unsigned int iPad, unsigned int tooltip, bool if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->EnableTooltip(tooltip,enable); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->EnableTooltip(tooltip,enable); } void UIController::RefreshTooltips(unsigned int iPad) @@ -2450,7 +2487,7 @@ void UIController::AnimateKeyPress(int iPad, int iAction, bool bRepeat, bool bPr if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2458,7 +2495,7 @@ void UIController::AnimateKeyPress(int iPad, int iAction, bool bRepeat, bool bPr group = eUIGroup_Fullscreen; } bool handled = false; - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->handleInput(iPad, iAction, bRepeat, bPressed, bReleased, handled); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->handleInput(iPad, iAction, bRepeat, bPressed, bReleased, handled); } void UIController::OverrideSFX(int iPad, int iAction,bool bVal) @@ -2468,7 +2505,7 @@ void UIController::OverrideSFX(int iPad, int iAction,bool bVal) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2476,7 +2513,7 @@ void UIController::OverrideSFX(int iPad, int iAction,bool bVal) group = eUIGroup_Fullscreen; } bool handled = false; - if(m_groups[(int)group]->getTooltips()) m_groups[(int)group]->getTooltips()->overrideSFX(iPad, iAction,bVal); + if(m_groups[static_cast(group)]->getTooltips()) m_groups[static_cast(group)]->getTooltips()->overrideSFX(iPad, iAction,bVal); } void UIController::PlayUISFX(ESoundEffect eSound) @@ -2504,13 +2541,13 @@ void UIController::DisplayGamertag(unsigned int iPad, bool show) { show = false; } - EUIGroup group = (EUIGroup)(iPad+1); - if(m_groups[(int)group]->getHUD()) m_groups[(int)group]->getHUD()->ShowDisplayName(show); + EUIGroup group = static_cast(iPad + 1); + if(m_groups[static_cast(group)]->getHUD()) m_groups[static_cast(group)]->getHUD()->ShowDisplayName(show); // Update TutorialPopup in Splitscreen if no container is displayed (to make sure the Popup does not overlap with the Gamertag!) - if(app.GetLocalPlayerCount() > 1 && m_groups[(int)group]->getTutorialPopup() && !m_groups[(int)group]->IsContainerMenuDisplayed()) + if(app.GetLocalPlayerCount() > 1 && m_groups[static_cast(group)]->getTutorialPopup() && !m_groups[static_cast(group)]->IsContainerMenuDisplayed()) { - m_groups[(int)group]->getTutorialPopup()->UpdateTutorialPopup(); + m_groups[static_cast(group)]->getTutorialPopup()->UpdateTutorialPopup(); } } @@ -2521,7 +2558,7 @@ void UIController::SetSelectedItem(unsigned int iPad, const wstring &name) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2529,7 +2566,7 @@ void UIController::SetSelectedItem(unsigned int iPad, const wstring &name) group = eUIGroup_Fullscreen; } bool handled = false; - if(m_groups[(int)group]->getHUD()) m_groups[(int)group]->getHUD()->SetSelectedLabel(name); + if(m_groups[static_cast(group)]->getHUD()) m_groups[static_cast(group)]->getHUD()->SetSelectedLabel(name); } void UIController::UpdateSelectedItemPos(unsigned int iPad) @@ -2582,10 +2619,10 @@ void UIController::HandleInventoryUpdated(int iPad) EUIGroup group = eUIGroup_Fullscreen; if( app.GetGameStarted() && ( iPad != 255 ) && ( iPad >= 0 ) ) { - group = (EUIGroup)(iPad+1); + group = static_cast(iPad + 1); } - m_groups[group]->HandleMessage(eUIMessage_InventoryUpdated, NULL); + m_groups[group]->HandleMessage(eUIMessage_InventoryUpdated, nullptr); } void UIController::HandleGameTick() @@ -2604,14 +2641,14 @@ void UIController::SetTutorial(int iPad, Tutorial *tutorial) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTutorialPopup()) m_groups[(int)group]->getTutorialPopup()->SetTutorial(tutorial); + if(m_groups[static_cast(group)]->getTutorialPopup()) m_groups[static_cast(group)]->getTutorialPopup()->SetTutorial(tutorial); } void UIController::SetTutorialDescription(int iPad, TutorialPopupInfo *info) @@ -2620,7 +2657,7 @@ void UIController::SetTutorialDescription(int iPad, TutorialPopupInfo *info) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2628,11 +2665,11 @@ void UIController::SetTutorialDescription(int iPad, TutorialPopupInfo *info) group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTutorialPopup()) + if(m_groups[static_cast(group)]->getTutorialPopup()) { // tutorial popup needs to know if a container menu is being displayed - m_groups[(int)group]->getTutorialPopup()->SetContainerMenuVisible(m_groups[(int)group]->IsContainerMenuDisplayed()); - m_groups[(int)group]->getTutorialPopup()->SetTutorialDescription(info); + m_groups[static_cast(group)]->getTutorialPopup()->SetContainerMenuVisible(m_groups[static_cast(group)]->IsContainerMenuDisplayed()); + m_groups[static_cast(group)]->getTutorialPopup()->SetTutorialDescription(info); } } @@ -2640,9 +2677,9 @@ void UIController::SetTutorialDescription(int iPad, TutorialPopupInfo *info) void UIController::RemoveInteractSceneReference(int iPad, UIScene *scene) { EUIGroup group; - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; - if(m_groups[(int)group]->getTutorialPopup()) m_groups[(int)group]->getTutorialPopup()->RemoveInteractSceneReference(scene); + if(m_groups[static_cast(group)]->getTutorialPopup()) m_groups[static_cast(group)]->getTutorialPopup()->RemoveInteractSceneReference(scene); } #endif @@ -2652,14 +2689,14 @@ void UIController::SetTutorialVisible(int iPad, bool visible) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else { group = eUIGroup_Fullscreen; } - if(m_groups[(int)group]->getTutorialPopup()) m_groups[(int)group]->getTutorialPopup()->SetVisible(visible); + if(m_groups[static_cast(group)]->getTutorialPopup()) m_groups[static_cast(group)]->getTutorialPopup()->SetVisible(visible); } bool UIController::IsTutorialVisible(int iPad) @@ -2668,7 +2705,7 @@ bool UIController::IsTutorialVisible(int iPad) if( app.GetGameStarted() ) { // If the game isn't running treat as user 0, otherwise map index directly from pad - if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = (EUIGroup)(iPad+1); + if( ( iPad != 255 ) && ( iPad >= 0 ) ) group = static_cast(iPad + 1); else group = eUIGroup_Fullscreen; } else @@ -2676,7 +2713,7 @@ bool UIController::IsTutorialVisible(int iPad) group = eUIGroup_Fullscreen; } bool visible = false; - if(m_groups[(int)group]->getTutorialPopup()) visible = m_groups[(int)group]->getTutorialPopup()->IsVisible(); + if(m_groups[static_cast(group)]->getTutorialPopup()) visible = m_groups[static_cast(group)]->getTutorialPopup()->IsVisible(); return visible; } @@ -2686,7 +2723,7 @@ void UIController::UpdatePlayerBasePositions() for( BYTE idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(pMinecraft->localplayers[idx] != NULL) + if(pMinecraft->localplayers[idx] != nullptr) { if(pMinecraft->localplayers[idx]->m_iScreenSection==C4JRender::VIEWPORT_TYPE_FULLSCREEN) { @@ -2696,7 +2733,7 @@ void UIController::UpdatePlayerBasePositions() { DisplayGamertag(idx,true); } - m_groups[idx+1]->SetViewportType((C4JRender::eViewportType)pMinecraft->localplayers[idx]->m_iScreenSection); + m_groups[idx+1]->SetViewportType(static_cast(pMinecraft->localplayers[idx]->m_iScreenSection)); } else { @@ -2729,7 +2766,7 @@ void UIController::ShowOtherPlayersBaseScene(unsigned int iPad, bool show) void UIController::ShowTrialTimer(bool show) { - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showTrialTimer(show); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showTrialTimer(show); } void UIController::SetTrialTimerLimitSecs(unsigned int uiSeconds) @@ -2741,7 +2778,7 @@ void UIController::UpdateTrialTimer(unsigned int iPad) { WCHAR wcTime[20]; - DWORD dwTimeTicks=(DWORD)app.getTrialTimer(); + DWORD dwTimeTicks=static_cast(app.getTrialTimer()); if(dwTimeTicks>m_dwTrialTimerLimitSecs) { @@ -2760,11 +2797,11 @@ void UIController::UpdateTrialTimer(unsigned int iPad) int iMins=dwTimeTicks/60; int iSeconds=dwTimeTicks%60; swprintf( wcTime, 20, L"%d:%02d",iMins,iSeconds); - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->setTrialTimer(wcTime); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->setTrialTimer(wcTime); } else { - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->setTrialTimer(L""); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->setTrialTimer(L""); } // are we out of time? @@ -2774,7 +2811,7 @@ void UIController::UpdateTrialTimer(unsigned int iPad) // bring up the pause menu to stop the trial over message box being called again? if(!ui.GetMenuDisplayed( iPad ) ) { - ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); + ui.NavigateToScene(iPad, eUIScene_PauseMenu, nullptr, eUILayer_Scene); app.SetAction(iPad,eAppAction_TrialOver); } @@ -2783,7 +2820,7 @@ void UIController::UpdateTrialTimer(unsigned int iPad) void UIController::ReduceTrialTimerValue() { - DWORD dwTimeTicks=(int)app.getTrialTimer(); + DWORD dwTimeTicks=static_cast(app.getTrialTimer()); if(dwTimeTicks>m_dwTrialTimerLimitSecs) { @@ -2795,7 +2832,7 @@ void UIController::ReduceTrialTimerValue() void UIController::ShowAutosaveCountdownTimer(bool show) { - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showTrialTimer(show); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showTrialTimer(show); } void UIController::UpdateAutosaveCountdownTimer(unsigned int uiSeconds) @@ -2803,7 +2840,7 @@ void UIController::UpdateAutosaveCountdownTimer(unsigned int uiSeconds) #if !(defined(_XBOX_ONE) || defined(__ORBIS__)) 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); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->setTrialTimer(wcAutosaveCountdown); #endif } @@ -2820,12 +2857,12 @@ void UIController::ShowSavingMessage(unsigned int iPad, C4JStorage::ESavingMessa show = true; break; } - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showSaveIcon(show); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showSaveIcon(show); } void UIController::ShowPlayerDisplayname(bool show) { - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showPlayerDisplayName(show); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showPlayerDisplayName(show); } void UIController::SetWinUserIndex(unsigned int iPad) @@ -2844,12 +2881,12 @@ void UIController::ShowUIDebugConsole(bool show) if(show) { - m_uiDebugConsole = (UIComponent_DebugUIConsole *)m_groups[eUIGroup_Fullscreen]->addComponent(0, eUIComponent_DebugUIConsole, eUILayer_Debug); + m_uiDebugConsole = static_cast(m_groups[eUIGroup_Fullscreen]->addComponent(0, eUIComponent_DebugUIConsole, eUILayer_Debug)); } else { m_groups[eUIGroup_Fullscreen]->removeComponent(eUIComponent_DebugUIConsole, eUILayer_Debug); - m_uiDebugConsole = NULL; + m_uiDebugConsole = nullptr; } #endif } @@ -2860,12 +2897,12 @@ void UIController::ShowUIDebugMarketingGuide(bool show) if(show) { - m_uiDebugMarketingGuide = (UIComponent_DebugUIMarketingGuide *)m_groups[eUIGroup_Fullscreen]->addComponent(0, eUIComponent_DebugUIMarketingGuide, eUILayer_Debug); + m_uiDebugMarketingGuide = static_cast(m_groups[eUIGroup_Fullscreen]->addComponent(0, eUIComponent_DebugUIMarketingGuide, eUILayer_Debug)); } else { m_groups[eUIGroup_Fullscreen]->removeComponent(eUIComponent_DebugUIMarketingGuide, eUILayer_Debug); - m_uiDebugMarketingGuide = NULL; + m_uiDebugMarketingGuide = nullptr; } #endif } @@ -2883,13 +2920,13 @@ bool UIController::PressStartPlaying(unsigned int iPad) void UIController::ShowPressStart(unsigned int iPad) { m_iPressStartQuadrantsMask|=1<getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showPressStart(iPad, true); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showPressStart(iPad, true); } void UIController::HidePressStart() { ClearPressStart(); - if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->showPressStart(0, false); + if(m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()) m_groups[static_cast(eUIGroup_Fullscreen)]->getPressStartToPlay()->showPressStart(0, false); } void UIController::ClearPressStart() @@ -2952,7 +2989,7 @@ C4JStorage::EMessageResult UIController::RequestMessageBox(UINT uiTitle, UINT ui } } -C4JStorage::EMessageResult UIController::RequestUGCMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = NULL*/, LPVOID lpParam/* = NULL*/) +C4JStorage::EMessageResult UIController::RequestUGCMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = nullptr*/, LPVOID lpParam/* = nullptr*/) { // Default title / messages if (title == -1) @@ -2984,7 +3021,7 @@ C4JStorage::EMessageResult UIController::RequestUGCMessageBox(UINT title/* = -1 #endif } -C4JStorage::EMessageResult UIController::RequestContentRestrictedMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = NULL*/, LPVOID lpParam/* = NULL*/) +C4JStorage::EMessageResult UIController::RequestContentRestrictedMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = nullptr*/, LPVOID lpParam/* = nullptr*/) { // Default title / messages if (title == -1) @@ -3022,7 +3059,7 @@ C4JStorage::EMessageResult UIController::RequestContentRestrictedMessageBox(UINT void UIController::setFontCachingCalculationBuffer(int length) { /* 4J-JEV: As described in an email from Sean. - If your `optional_temp_buffer` is NULL, Iggy will allocate the temp + If your `optional_temp_buffer` is nullptr, Iggy will allocate the temp buffer on the stack during Iggy draw calls. The size of the buffer it will allocate is 16 bytes times `max_chars` in 32-bit, and 24 bytes times `max_chars` in 64-bit. If the stack of the thread making the @@ -3035,10 +3072,10 @@ void UIController::setFontCachingCalculationBuffer(int length) static const int CHAR_SIZE = 16; #endif - if (m_tempBuffer != NULL) delete [] m_tempBuffer; + if (m_tempBuffer != nullptr) delete [] m_tempBuffer; if (length<0) { - if (m_defaultBuffer == NULL) m_defaultBuffer = new char[CHAR_SIZE*5000]; + if (m_defaultBuffer == nullptr) m_defaultBuffer = new char[CHAR_SIZE*5000]; IggySetFontCachingCalculationBuffer(5000, m_defaultBuffer, CHAR_SIZE*5000); } else @@ -3048,16 +3085,16 @@ 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, nullptr otherwise UIScene *UIController::FindScene(EUIScene sceneType) { - UIScene *pScene = NULL; + UIScene *pScene = nullptr; for (int i = 0; i < eUIGroup_COUNT; i++) { pScene = m_groups[i]->FindScene(sceneType); #ifdef __PS3__ - if (pScene != NULL) return pScene; + if (pScene != nullptr) return pScene; #else if (pScene != nullptr) return pScene; #endif @@ -3223,7 +3260,7 @@ bool UIController::TouchBoxHit(UIScene *pUIScene,S32 x, S32 y) } //app.DebugPrintf("MISS at x = %i y = %i\n", (int)x, (int)y); - m_HighlightedUIElement = NULL; + m_HighlightedUIElement = nullptr; return false; } diff --git a/Minecraft.Client/Common/UI/UIController.h b/Minecraft.Client/Common/UI/UIController.h index 5b897b130..08a5ba088 100644 --- a/Minecraft.Client/Common/UI/UIController.h +++ b/Minecraft.Client/Common/UI/UIController.h @@ -101,9 +101,8 @@ private: eLibrary_Tooltips, eLibrary_Default, -#if ( defined(_WINDOWS64) ) - // 4J Stu - Load the 720/480 skins so that we have something to fallback on during development -#ifndef _FINAL_BUILD +#if defined(_WINDOWS64) + // Non-HD skin libraries needed by 720p/480p scene SWFs. eLibraryFallback_Platform, eLibraryFallback_GraphicsDefault, eLibraryFallback_GraphicsHUD, @@ -115,7 +114,6 @@ private: eLibraryFallback_HUD, eLibraryFallback_Tooltips, eLibraryFallback_Default, -#endif #endif eLibrary_Count, @@ -257,6 +255,7 @@ public: // RENDERING float getScreenWidth() { return m_fScreenWidth; } float getScreenHeight() { return m_fScreenHeight; } + void updateScreenSize(S32 w, S32 h) { m_fScreenWidth = (float)w; m_fScreenHeight = (float)h; app.DebugPrintf("[UI-INIT] updateScreenSize: %d x %d\n", w, h); } virtual void render() = 0; void getRenderDimensions(C4JRender::eViewportType viewport, S32 &width, S32 &height); @@ -293,7 +292,7 @@ protected: static GDrawTexture * RADLINK TextureSubstitutionCreateCallback( void * user_callback_data , IggyUTF16 * texture_name , S32 * width , S32 * height , void **destroy_callback_data ); static void RADLINK TextureSubstitutionDestroyCallback( void * user_callback_data , void * destroy_callback_data , GDrawTexture * handle ); - virtual GDrawTexture *getSubstitutionTexture(int textureId) { return NULL; } + virtual GDrawTexture *getSubstitutionTexture(int textureId) { return nullptr; } virtual void destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle) {} public: @@ -302,7 +301,7 @@ public: public: // NAVIGATION - bool NavigateToScene(int iPad, EUIScene scene, void *initData = NULL, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD); + bool NavigateToScene(int iPad, EUIScene scene, void *initData = nullptr, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD); bool NavigateBack(int iPad, bool forceUsePad = false, EUIScene eScene = eUIScene_COUNT, EUILayer eLayer = eUILayer_COUNT); void NavigateToHomeMenu(); UIScene *GetTopScene(int iPad, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD); @@ -382,14 +381,14 @@ public: virtual void HidePressStart(); void ClearPressStart(); - virtual C4JStorage::EMessageResult RequestAlertMessage(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=NULL,LPVOID lpParam=NULL, WCHAR *pwchFormatString=NULL); - virtual C4JStorage::EMessageResult RequestErrorMessage(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=NULL,LPVOID lpParam=NULL, WCHAR *pwchFormatString=NULL); + virtual C4JStorage::EMessageResult RequestAlertMessage(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=nullptr,LPVOID lpParam=nullptr, WCHAR *pwchFormatString=nullptr); + virtual C4JStorage::EMessageResult RequestErrorMessage(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=nullptr,LPVOID lpParam=nullptr, WCHAR *pwchFormatString=nullptr); private: virtual C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad,int( *Func)(LPVOID,int,const C4JStorage::EMessageResult),LPVOID lpParam, WCHAR *pwchFormatString,DWORD dwFocusButton, bool bIsError); public: - C4JStorage::EMessageResult RequestUGCMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = NULL, LPVOID lpParam = NULL); - C4JStorage::EMessageResult RequestContentRestrictedMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = NULL, LPVOID lpParam = NULL); + C4JStorage::EMessageResult RequestUGCMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = nullptr, LPVOID lpParam = nullptr); + C4JStorage::EMessageResult RequestContentRestrictedMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = nullptr, LPVOID lpParam = nullptr); virtual void SetWinUserIndex(unsigned int iPad); unsigned int GetWinUserIndex(); diff --git a/Minecraft.Client/Common/UI/UIFontData.cpp b/Minecraft.Client/Common/UI/UIFontData.cpp index c5ad46ef0..715d08ddc 100644 --- a/Minecraft.Client/Common/UI/UIFontData.cpp +++ b/Minecraft.Client/Common/UI/UIFontData.cpp @@ -145,9 +145,9 @@ CFontData::CFontData() { m_unicodeMap = unordered_map(); - m_sFontData = NULL; - m_kerningTable = NULL; - m_pbRawImage = NULL; + m_sFontData = nullptr; + m_kerningTable = nullptr; + m_pbRawImage = nullptr; } CFontData::CFontData(SFontData &sFontData, int *pbRawImage) diff --git a/Minecraft.Client/Common/UI/UIGroup.cpp b/Minecraft.Client/Common/UI/UIGroup.cpp index 79d3c38f7..baccc17f6 100644 --- a/Minecraft.Client/Common/UI/UIGroup.cpp +++ b/Minecraft.Client/Common/UI/UIGroup.cpp @@ -1,6 +1,8 @@ #include "stdafx.h" #include "UIGroup.h" +#include "UI.h" + UIGroup::UIGroup(EUIGroup group, int iPad) { m_group = group; @@ -23,22 +25,22 @@ UIGroup::UIGroup(EUIGroup group, int iPad) #endif } - m_tooltips = (UIComponent_Tooltips *)m_layers[(int)eUILayer_Tooltips]->addComponent(0, eUIComponent_Tooltips); + m_tooltips = (UIComponent_Tooltips *)m_layers[static_cast(eUILayer_Tooltips)]->addComponent(0, eUIComponent_Tooltips); - m_tutorialPopup = NULL; - m_hud = NULL; - m_pressStartToPlay = NULL; + m_tutorialPopup = nullptr; + m_hud = nullptr; + m_pressStartToPlay = nullptr; if(m_group != eUIGroup_Fullscreen) { - m_tutorialPopup = (UIComponent_TutorialPopup *)m_layers[(int)eUILayer_Popup]->addComponent(m_iPad, eUIComponent_TutorialPopup); + m_tutorialPopup = (UIComponent_TutorialPopup *)m_layers[static_cast(eUILayer_Popup)]->addComponent(m_iPad, eUIComponent_TutorialPopup); - m_hud = (UIScene_HUD *)m_layers[(int)eUILayer_HUD]->addComponent(m_iPad, eUIScene_HUD); + m_hud = (UIScene_HUD *)m_layers[static_cast(eUILayer_HUD)]->addComponent(m_iPad, eUIScene_HUD); //m_layers[(int)eUILayer_Chat]->addComponent(m_iPad, eUIComponent_Chat); } else { - m_pressStartToPlay = (UIComponent_PressStartToPlay *)m_layers[(int)eUILayer_Tooltips]->addComponent(0, eUIComponent_PressStartToPlay); + m_pressStartToPlay = (UIComponent_PressStartToPlay *)m_layers[static_cast(eUILayer_Tooltips)]->addComponent(0, eUIComponent_PressStartToPlay); } // 4J Stu - Pre-allocate this for cached rendering in scenes. It's horribly slow to do dynamically, but we should only need one @@ -65,7 +67,7 @@ void UIGroup::ReloadAll() if(highestRenderable < eUILayer_Fullscreen) highestRenderable = eUILayer_Fullscreen; for(; highestRenderable >= 0; --highestRenderable) { - if(highestRenderable < eUILayer_COUNT) m_layers[highestRenderable]->ReloadAll(highestRenderable != (int)eUILayer_Fullscreen); + if(highestRenderable < eUILayer_COUNT) m_layers[highestRenderable]->ReloadAll(highestRenderable != static_cast(eUILayer_Fullscreen)); } } @@ -127,7 +129,7 @@ void UIGroup::getRenderDimensions(S32 &width, S32 &height) // NAVIGATION bool UIGroup::NavigateToScene(int iPad, EUIScene scene, void *initData, EUILayer layer) { - bool succeeded = m_layers[(int)layer]->NavigateToScene(iPad, scene, initData); + bool succeeded = m_layers[static_cast(layer)]->NavigateToScene(iPad, scene, initData); updateStackStates(); return succeeded; } @@ -151,9 +153,9 @@ void UIGroup::closeAllScenes() Minecraft *pMinecraft = Minecraft::GetInstance(); if( m_iPad >= 0 ) { - if(pMinecraft != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(true); @@ -163,14 +165,14 @@ void UIGroup::closeAllScenes() for(unsigned int i = 0; i < eUILayer_COUNT; ++i) { // Ignore the error layer - if(i != (int)eUILayer_Error) m_layers[i]->closeAllScenes(); + if(i != static_cast(eUILayer_Error)) m_layers[i]->closeAllScenes(); } updateStackStates(); } UIScene *UIGroup::GetTopScene(EUILayer layer) { - return m_layers[(int)layer]->GetTopScene(); + return m_layers[static_cast(layer)]->GetTopScene(); } bool UIGroup::GetMenuDisplayed() @@ -214,10 +216,10 @@ UIScene *UIGroup::getCurrentScene() { pScene=m_layers[i]->getCurrentScene(); - if(pScene!=NULL) return pScene; + if(pScene!=nullptr) return pScene; } - return NULL; + return nullptr; } #endif @@ -412,16 +414,16 @@ int UIGroup::getCommandBufferList() return m_commandBufferList; } -// Returns the first scene of given type if it exists, NULL otherwise +// Returns the first scene of given type if it exists, nullptr otherwise UIScene *UIGroup::FindScene(EUIScene sceneType) { - UIScene *pScene = NULL; + UIScene *pScene = nullptr; for (int i = 0; i < eUILayer_COUNT; i++) { pScene = m_layers[i]->FindScene(sceneType); #ifdef __PS3__ - if (pScene != NULL) return pScene; + if (pScene != nullptr) return pScene; #else if (pScene != nullptr) return pScene; #endif diff --git a/Minecraft.Client/Common/UI/UILayer.cpp b/Minecraft.Client/Common/UI/UILayer.cpp index 2063778b6..e1c388f54 100644 --- a/Minecraft.Client/Common/UI/UILayer.cpp +++ b/Minecraft.Client/Common/UI/UILayer.cpp @@ -102,7 +102,7 @@ void UILayer::render(S32 width, S32 height, C4JRender::eViewportType viewport) bool UILayer::IsSceneInStack(EUIScene scene) { bool inStack = false; - for(int i = m_sceneStack.size() - 1;i >= 0; --i) + for(int i = static_cast(m_sceneStack.size()) - 1; i >= 0; --i) { if(m_sceneStack[i]->getSceneType() == scene) { @@ -118,7 +118,7 @@ bool UILayer::HasFocus(int iPad) bool hasFocus = false; if(m_hasFocus) { - for(int i = m_sceneStack.size() - 1;i >= 0; --i) + for(int i = (int)m_sceneStack.size() - 1; i >= 0; --i) { if(m_sceneStack[i]->stealsFocus() ) { @@ -146,7 +146,7 @@ bool UILayer::hidesLowerScenes() } if(!hidesScenes && !m_sceneStack.empty()) { - for(int i = m_sceneStack.size() - 1;i >= 0; --i) + for(int i = static_cast(m_sceneStack.size()) - 1; i >= 0; --i) { if(m_sceneStack[i]->hidesLowerScenes()) { @@ -197,7 +197,7 @@ bool UILayer::GetMenuDisplayed() bool UILayer::NavigateToScene(int iPad, EUIScene scene, void *initData) { - UIScene *newScene = NULL; + UIScene *newScene = nullptr; switch(scene) { // Debug @@ -424,7 +424,7 @@ bool UILayer::NavigateToScene(int iPad, EUIScene scene, void *initData) break; }; - if(newScene == NULL) + if(newScene == nullptr) { app.DebugPrintf("WARNING: Scene %d was not created. Add it to UILayer::NavigateToScene\n", scene); return false; @@ -451,7 +451,7 @@ bool UILayer::NavigateBack(int iPad, EUIScene eScene) bool navigated = false; if(eScene < eUIScene_COUNT) { - UIScene *scene = NULL; + UIScene *scene = nullptr; do { scene = m_sceneStack.back(); @@ -523,9 +523,9 @@ UIScene *UILayer::addComponent(int iPad, EUIScene scene, void *initData) return itComp; } } - return NULL; + return nullptr; } - UIScene *newScene = NULL; + UIScene *newScene = nullptr; switch(scene) { @@ -573,7 +573,7 @@ UIScene *UILayer::addComponent(int iPad, EUIScene scene, void *initData) break; }; - if(newScene == NULL) return NULL; + if(newScene == nullptr) return nullptr; m_components.push_back(newScene); @@ -661,12 +661,12 @@ void UILayer::closeAllScenes() } } -// Get top scene on stack (or NULL if stack is empty) +// Get top scene on stack (or nullptr if stack is empty) UIScene *UILayer::GetTopScene() { if(m_sceneStack.size() == 0) { - return NULL; + return nullptr; } else { @@ -789,7 +789,7 @@ UIScene *UILayer::getCurrentScene() } } - return NULL; + return nullptr; } #endif @@ -894,10 +894,10 @@ void UILayer::PrintTotalMemoryUsage(int64_t &totalStatic, int64_t &totalDynamic) totalDynamic += layerDynamic; } -// Returns the first scene of given type if it exists, NULL otherwise +// Returns the first scene of given type if it exists, nullptr otherwise UIScene *UILayer::FindScene(EUIScene sceneType) { - for (int i = 0; i < m_sceneStack.size(); i++) + for (size_t i = 0; i < m_sceneStack.size(); i++) { if (m_sceneStack[i]->getSceneType() == sceneType) { @@ -905,5 +905,5 @@ UIScene *UILayer::FindScene(EUIScene sceneType) } } - return NULL; + return nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UILayer.h b/Minecraft.Client/Common/UI/UILayer.h index ec6a1f8a8..7f1a0bf5c 100644 --- a/Minecraft.Client/Common/UI/UILayer.h +++ b/Minecraft.Client/Common/UI/UILayer.h @@ -61,7 +61,7 @@ public: // E.g. you can keep a component active while performing navigation with other scenes on this layer void showComponent(int iPad, EUIScene scene, bool show); bool isComponentVisible(EUIScene scene); - UIScene *addComponent(int iPad, EUIScene scene, void *initData = NULL); + UIScene *addComponent(int iPad, EUIScene scene, void *initData = nullptr); void removeComponent(EUIScene scene); // INPUT diff --git a/Minecraft.Client/Common/UI/UIScene.cpp b/Minecraft.Client/Common/UI/UIScene.cpp index d01585cb8..303897a7f 100644 --- a/Minecraft.Client/Common/UI/UIScene.cpp +++ b/Minecraft.Client/Common/UI/UIScene.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "UI.h" #include "UIScene.h" +#include "UISplitScreenHelpers.h" #include "..\..\Lighting.h" #include "..\..\LocalPlayer.h" @@ -11,8 +12,8 @@ UIScene::UIScene(int iPad, UILayer *parentLayer) { m_parentLayer = parentLayer; m_iPad = iPad; - swf = NULL; - m_pItemRenderer = NULL; + swf = nullptr; + m_pItemRenderer = nullptr; bHasFocus = false; m_hasTickedOnce = false; @@ -26,7 +27,7 @@ UIScene::UIScene(int iPad, UILayer *parentLayer) m_lastOpacity = 1.0f; m_bUpdateOpacity = false; - m_backScene = NULL; + m_backScene = nullptr; m_cacheSlotRenders = false; m_needsCacheRendered = true; @@ -49,14 +50,14 @@ UIScene::~UIScene() ui.UnregisterCallbackId(m_callbackUniqueId); } - if(m_pItemRenderer != NULL) delete m_pItemRenderer; + if(m_pItemRenderer != nullptr) delete m_pItemRenderer; } void UIScene::destroyMovie() { /* Destroy the Iggy player. */ IggyPlayerDestroy( swf ); - swf = NULL; + swf = nullptr; // Clear out the controls collection (doesn't delete the controls, and they get re-setup later) m_controls.clear(); @@ -115,7 +116,7 @@ bool UIScene::needsReloaded() bool UIScene::hasMovie() { - return swf != NULL; + return swf != nullptr; } F64 UIScene::getSafeZoneHalfHeight() @@ -171,15 +172,22 @@ void UIScene::updateSafeZone() { case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - safeBottom = getSafeZoneHalfHeight(); + // safeTop mirrors SPLIT_TOP for visual symmetry. safeBottom omitted. + safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + safeTop = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - safeRight = getSafeZoneHalfWidth(); + safeTop = getSafeZoneHalfHeight(); + break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: safeTop = getSafeZoneHalfHeight(); @@ -187,22 +195,22 @@ void UIScene::updateSafeZone() break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: safeTop = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); + break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - safeBottom = getSafeZoneHalfHeight(); + safeTop = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - safeBottom = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); + safeTop = getSafeZoneHalfHeight(); + break; case C4JRender::VIEWPORT_TYPE_FULLSCREEN: default: safeTop = getSafeZoneHalfHeight(); safeBottom = getSafeZoneHalfHeight(); safeLeft = getSafeZoneHalfWidth(); - safeRight = getSafeZoneHalfWidth(); + break; } setSafeZone(safeTop, safeBottom, safeLeft, safeRight); @@ -285,26 +293,16 @@ void UIScene::loadMovie() moviePath.append(L"Vita.swf"); m_loadedResolution = eSceneResolution_Vita; #elif defined _WINDOWS64 - if(ui.getScreenHeight() == 720) - { - moviePath.append(L"720.swf"); - m_loadedResolution = eSceneResolution_720; - } - else if(ui.getScreenHeight() == 480) - { - moviePath.append(L"480.swf"); - m_loadedResolution = eSceneResolution_480; - } - else if(ui.getScreenHeight() < 720) - { - moviePath.append(L"Vita.swf"); - m_loadedResolution = eSceneResolution_Vita; - } - else + if(ui.getScreenHeight() > 720.0f) { moviePath.append(L"1080.swf"); m_loadedResolution = eSceneResolution_1080; } + else + { + moviePath.append(L"720.swf"); + m_loadedResolution = eSceneResolution_720; + } #else moviePath.append(L"1080.swf"); m_loadedResolution = eSceneResolution_1080; @@ -330,10 +328,8 @@ void UIScene::loadMovie() byteArray baFile = ui.getMovieData(moviePath.c_str()); int64_t beforeLoad = ui.iggyAllocCount; - swf = IggyPlayerCreateFromMemory ( baFile.data , baFile.length, NULL); + swf = IggyPlayerCreateFromMemory ( baFile.data , baFile.length, nullptr); int64_t afterLoad = ui.iggyAllocCount; - IggyPlayerInitializeAndTickRS ( swf ); - int64_t afterTick = ui.iggyAllocCount; if(!swf) { @@ -343,17 +339,44 @@ void UIScene::loadMovie() #endif app.FatalLoadError(); } - app.DebugPrintf( app.USER_SR, "Loaded iggy movie %ls\n", moviePath.c_str() ); + + // Read movie dimensions from the SWF header (available immediately after + // CreateFromMemory, no init tick needed). IggyProperties *properties = IggyPlayerProperties ( swf ); m_movieHeight = properties->movie_height_in_pixels; m_movieWidth = properties->movie_width_in_pixels; - m_renderWidth = m_movieWidth; m_renderHeight = m_movieHeight; - S32 width, height; - m_parentLayer->getRenderDimensions(width, height); - IggyPlayerSetDisplaySize( swf, width, height ); + // Set display size BEFORE the init tick to match what render() will use. + // InitializeAndTickRS runs ActionScript that creates text fields. If the + // display size here differs from what render() passes to SetDisplaySize, + // Iggy can cache glyph rasterizations at one scale during init and then + // reuse them at a different scale during draw, producing mixed glyph sizes. +#ifdef _WINDOWS64 + { + S32 fitW, fitH, fitOffX, fitOffY; + Fit16x9(ui.getScreenWidth(), ui.getScreenHeight(), fitW, fitH, fitOffX, fitOffY); + IggyPlayerSetDisplaySize( swf, fitW, fitH ); + } +#else + IggyPlayerSetDisplaySize( swf, m_movieWidth, m_movieHeight ); +#endif + + IggyPlayerInitializeAndTickRS ( swf ); + int64_t afterTick = ui.iggyAllocCount; + +#ifdef _WINDOWS64 + // Flush Iggy's internal font caches so all glyphs get rasterized fresh + // at the current display scale on the first Draw. Without this, stale + // cache entries from a previous scene (loaded at a different display size) + // cause mixed glyph sizes. ResizeD3D already calls this, which is why + // fonts look correct after a resize but break when a scene reloads + // without one. + IggyFlushInstalledFonts(); +#endif + + app.DebugPrintf( app.USER_SR, "Loaded iggy movie %ls\n", moviePath.c_str() ); IggyPlayerSetUserdata(swf,this); @@ -365,7 +388,7 @@ void UIScene::loadMovie() int64_t totalStatic = 0; int64_t totalDynamic = 0; while(res = IggyDebugGetMemoryUseInfo ( swf , - NULL , + nullptr , 0 , 0 , iteration , @@ -389,21 +412,22 @@ void UIScene::loadMovie() void UIScene::getDebugMemoryUseRecursive(const wstring &moviePath, IggyMemoryUseInfo &memoryInfo) { - rrbool res; - IggyMemoryUseInfo internalMemoryInfo; - int internalIteration = 0; - while(res = IggyDebugGetMemoryUseInfo ( swf , - NULL , - memoryInfo.subcategory , - memoryInfo.subcategory_stringlen , - internalIteration , - &internalMemoryInfo )) - { - 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); - } + rrbool res; + IggyMemoryUseInfo internalMemoryInfo; + int internalIteration = 0; + while (res = IggyDebugGetMemoryUseInfo(swf, + 0, + memoryInfo.subcategory, + memoryInfo.subcategory_stringlen, + internalIteration, + &internalMemoryInfo)) + { + 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); + } } void UIScene::PrintTotalMemoryUsage(int64_t &totalStatic, int64_t &totalDynamic) @@ -416,7 +440,7 @@ void UIScene::PrintTotalMemoryUsage(int64_t &totalStatic, int64_t &totalDynamic) int64_t sceneStatic = 0; int64_t sceneDynamic = 0; while(res = IggyDebugGetMemoryUseInfo ( swf , - NULL , + 0 , "" , 0 , iteration , @@ -464,7 +488,7 @@ void UIScene::tick() UIControl* UIScene::GetMainPanel() { - return NULL; + return nullptr; } #ifdef _WINDOWS64 @@ -560,10 +584,13 @@ bool UIScene::handleMouseClick(F32 x, F32 y) { if (bestCtrl->getControlType() == UIControl::eCheckBox) { - UIControl_CheckBox *cb = (UIControl_CheckBox *)bestCtrl; - bool newState = !cb->IsChecked(); - cb->setChecked(newState); - handleCheckboxToggled((F64)bestId, newState); + UIControl_CheckBox *cb = static_cast(bestCtrl); + if (cb->IsEnabled()) + { + bool newState = !cb->IsChecked(); + cb->setChecked(newState); + handleCheckboxToggled((F64)bestId, newState); + } } else { @@ -666,28 +693,42 @@ void UIScene::removeControl( UIControl_Base *control, bool centreScene) void UIScene::slideLeft() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSlideLeft , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSlideLeft , 0 , nullptr ); } void UIScene::slideRight() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSlideRight , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSlideRight , 0 , nullptr ); } void UIScene::doHorizontalResizeCheck() { IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcHorizontalResizeCheck , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcHorizontalResizeCheck , 0 , nullptr ); } void UIScene::render(S32 width, S32 height, C4JRender::eViewportType viewport) { if(m_bIsReloading) return; if(!m_hasTickedOnce || !swf) return; - ui.setupRenderPosition(viewport); - IggyPlayerSetDisplaySize( swf, width, height ); - IggyPlayerDraw( swf ); + + if(viewport != C4JRender::VIEWPORT_TYPE_FULLSCREEN) + { + F32 originX, originY, viewW, viewH; + GetViewportRect(ui.getScreenWidth(), ui.getScreenHeight(), viewport, originX, originY, viewW, viewH); + S32 fitW, fitH, offsetX, offsetY; + Fit16x9(viewW, viewH, fitW, fitH, offsetX, offsetY); + ui.setupRenderPosition(static_cast(originX) + offsetX, static_cast(originY) + offsetY); + IggyPlayerSetDisplaySize( swf, fitW, fitH ); + IggyPlayerDraw( swf ); + } + else + { + ui.setupRenderPosition(viewport); + IggyPlayerSetDisplaySize( swf, width, height ); + IggyPlayerDraw( swf ); + } } void UIScene::setOpacity(float percent) @@ -721,7 +762,7 @@ void UIScene::customDraw(IggyCustomDrawCallbackRegion *region) void UIScene::customDrawSlotControl(IggyCustomDrawCallbackRegion *region, int iPad, shared_ptr item, float fAlpha, bool isFoil, bool bDecorations) { - if (item!= NULL) + if (item!= nullptr) { if(m_cacheSlotRenders) { @@ -849,7 +890,7 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt if (pop > 0) { glPushMatrix(); - float squeeze = 1 + pop / (float) Inventory::POP_TIME_DURATION; + float squeeze = 1 + pop / static_cast(Inventory::POP_TIME_DURATION); float sx = x; float sy = y; float sxoffs = 8 * scaleX; @@ -860,7 +901,7 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt } PIXBeginNamedEvent(0,"Render and decorate"); - if(m_pItemRenderer == NULL) m_pItemRenderer = new ItemRenderer(); + if(m_pItemRenderer == nullptr) m_pItemRenderer = new ItemRenderer(); RenderManager.StateSetBlendEnable(true); RenderManager.StateSetBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderManager.StateSetBlendFactor(0xffffffff); @@ -878,15 +919,15 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt { glPushMatrix(); glScalef(scaleX, scaleY, 1.0f); - int iX= (int)(0.5f+((float)x)/scaleX); - int iY= (int)(0.5f+((float)y)/scaleY); + int iX= static_cast(0.5f + ((float)x) / scaleX); + int iY= static_cast(0.5f + ((float)y) / scaleY); m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, item, iX, iY, fAlpha); glPopMatrix(); } else { - m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, item, (int)x, (int)y, fAlpha); + m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, item, static_cast(x), static_cast(y), fAlpha); } } @@ -897,9 +938,9 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt // 4J Stu - Not threadsafe //void UIScene::navigateForward(int iPad, EUIScene scene, void *initData) //{ -// if(m_parentLayer == NULL) +// if(m_parentLayer == nullptr) // { -// app.DebugPrintf("A scene is trying to navigate forwards, but it's parent layer is NULL!\n"); +// app.DebugPrintf("A scene is trying to navigate forwards, but it's parent layer is nullptr!\n"); //#ifndef _CONTENT_PACKAGE // __debugbreak(); //#endif @@ -917,9 +958,9 @@ void UIScene::navigateBack() ui.NavigateBack(m_iPad); - if(m_parentLayer == NULL) + if(m_parentLayer == nullptr) { -// app.DebugPrintf("A scene is trying to navigate back, but it's parent layer is NULL!\n"); +// app.DebugPrintf("A scene is trying to navigate back, but it's parent layer is nullptr!\n"); #ifndef _CONTENT_PACKAGE // __debugbreak(); #endif @@ -1042,7 +1083,7 @@ void UIScene::sendInputToMovie(int key, bool repeat, bool pressed, bool released IggyEvent keyEvent; // 4J Stu - Keyloc is always standard as we don't care about shift/alt - IggyMakeEventKey( &keyEvent, pressed?IGGY_KEYEVENT_Down:IGGY_KEYEVENT_Up, (IggyKeycode)iggyKeyCode, IGGY_KEYLOC_Standard ); + IggyMakeEventKey( &keyEvent, pressed?IGGY_KEYEVENT_Down:IGGY_KEYEVENT_Up, static_cast(iggyKeyCode), IGGY_KEYLOC_Standard ); IggyEventResult result; IggyPlayerDispatchEventRS ( swf , &keyEvent , &result ); @@ -1331,9 +1372,8 @@ bool UIScene::hasRegisteredSubstitutionTexture(const wstring &textureName) void UIScene::_handleFocusChange(F64 controlId, F64 childId) { - int newControl = (int)controlId; - int newChild = (int)childId; - + int newControl = static_cast(controlId); + int newChild = static_cast(childId); if (newControl != m_iFocusControl || newChild != m_iFocusChild) { m_iFocusControl = newControl; @@ -1346,8 +1386,8 @@ void UIScene::_handleFocusChange(F64 controlId, F64 childId) void UIScene::_handleInitFocus(F64 controlId, F64 childId) { - m_iFocusControl = (int)controlId; - m_iFocusChild = (int)childId; + m_iFocusControl = static_cast(controlId); + m_iFocusChild = static_cast(childId); //handleInitFocus(controlId, childId); handleFocusChange(controlId, childId); diff --git a/Minecraft.Client/Common/UI/UIScene.h b/Minecraft.Client/Common/UI/UIScene.h index e45ecdd11..ca089d39c 100644 --- a/Minecraft.Client/Common/UI/UIScene.h +++ b/Minecraft.Client/Common/UI/UIScene.h @@ -265,7 +265,7 @@ public: // NAVIGATION protected: - //void navigateForward(int iPad, EUIScene scene, void *initData = NULL); + //void navigateForward(int iPad, EUIScene scene, void *initData = nullptr); void navigateBack(); public: diff --git a/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.cpp b/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.cpp index 6b196c1b8..0c3b6096d 100644 --- a/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "UI.h" #include "UIScene_AbstractContainerMenu.h" +#include "UISplitScreenHelpers.h" #include "..\..\..\Minecraft.World\net.minecraft.world.inventory.h" #include "..\..\..\Minecraft.World\net.minecraft.world.item.h" @@ -49,15 +50,15 @@ void UIScene_AbstractContainerMenu::handleDestroy() #endif Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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) - if(pMinecraft->localplayers[m_iPad] != NULL && pMinecraft->localplayers[m_iPad]->containerMenu->containerId == m_menu->containerId) + if(pMinecraft->localplayers[m_iPad] != nullptr && pMinecraft->localplayers[m_iPad]->containerMenu->containerId == m_menu->containerId) { pMinecraft->localplayers[m_iPad]->closeContainer(); } @@ -149,8 +150,8 @@ void UIScene_AbstractContainerMenu::PlatformInitialize(int iPad, int startIndex) m_fPointerMaxX = m_fPanelMaxX + fPointerWidth; m_fPointerMaxY = m_fPanelMaxY + (fPointerHeight/2); -// m_hPointerText=NULL; -// m_hPointerTextBkg=NULL; +// m_hPointerText=nullptr; +// m_hPointerTextBkg=nullptr; // Put the pointer over first item in use row to start with. UIVec2D itemPos; @@ -187,14 +188,19 @@ void UIScene_AbstractContainerMenu::PlatformInitialize(int iPad, int startIndex) IggyEvent mouseEvent; S32 width, height; m_parentLayer->getRenderDimensions(width, height); - S32 x = m_pointerPos.x*((float)width/m_movieWidth); - S32 y = m_pointerPos.y*((float)height/m_movieHeight); + + C4JRender::eViewportType vp = m_parentLayer->getViewport(); + if(vp != C4JRender::VIEWPORT_TYPE_FULLSCREEN) + Fit16x9(width, height); + + S32 x = m_pointerPos.x*(static_cast(width)/m_movieWidth); + S32 y = m_pointerPos.y*(static_cast(height)/m_movieHeight); IggyMakeEventMouseMove( &mouseEvent, x, y); IggyEventResult result; IggyPlayerDispatchEventRS ( getMovie() , &mouseEvent , &result ); -#ifdef USE_POINTER_ACCEL +#ifdef USE_POINTER_ACCEL m_fPointerVelX = 0.0f; m_fPointerVelY = 0.0f; m_fPointerAccelX = 0.0f; @@ -212,8 +218,12 @@ void UIScene_AbstractContainerMenu::tick() S32 width, height; m_parentLayer->getRenderDimensions(width, height); - S32 x = (S32)(m_pointerPos.x * ((float)width / m_movieWidth)); - S32 y = (S32)(m_pointerPos.y * ((float)height / m_movieHeight)); + C4JRender::eViewportType vp = m_parentLayer->getViewport(); + if(vp != C4JRender::VIEWPORT_TYPE_FULLSCREEN) + Fit16x9(width, height); + + S32 x = static_cast(m_pointerPos.x * (static_cast(width) / m_movieWidth)); + S32 y = static_cast(m_pointerPos.y * (static_cast(height) / m_movieHeight)); IggyMakeEventMouseMove( &mouseEvent, x, y); @@ -251,10 +261,31 @@ void UIScene_AbstractContainerMenu::render(S32 width, S32 height, C4JRender::eVi m_needsCacheRendered = false; } +void UIScene_AbstractContainerMenu::getMouseToSWFScale(float &scaleX, float &scaleY) +{ + extern HWND g_hWnd; + RECT rc; + GetClientRect(g_hWnd, &rc); + int winW = rc.right - rc.left; + int winH = rc.bottom - rc.top; + if(winW <= 0 || winH <= 0) { scaleX = 1.0f; scaleY = 1.0f; return; } + + S32 renderW, renderH; + C4JRender::eViewportType vp = GetParentLayer()->getViewport(); + ui.getRenderDimensions(vp, renderW, renderH); + if(vp != C4JRender::VIEWPORT_TYPE_FULLSCREEN) + Fit16x9(renderW, renderH); + + float screenW = (float)ui.getScreenWidth(); + float screenH = (float)ui.getScreenHeight(); + scaleX = static_cast(m_movieWidth) * screenW / (static_cast(renderW) * static_cast(winW)); + scaleY = static_cast(m_movieHeight) * screenH / (static_cast(renderH) * static_cast(winH)); +} + void UIScene_AbstractContainerMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; shared_ptr item = nullptr; int slotId = -1; @@ -265,7 +296,7 @@ void UIScene_AbstractContainerMenu::customDraw(IggyCustomDrawCallbackRegion *reg } else { - swscanf((wchar_t*)region->name,L"slot_%d",&slotId); + swscanf(static_cast(region->name),L"slot_%d",&slotId); if (slotId == -1) { app.DebugPrintf("This is not the control we are looking for\n"); @@ -278,7 +309,7 @@ void UIScene_AbstractContainerMenu::customDraw(IggyCustomDrawCallbackRegion *reg } } - if(item != NULL) customDrawSlotControl(region,m_iPad,item,m_menu->isValidIngredient(item, slotId)?1.0f:0.5f,item->isFoil(),true); + if(item != nullptr) customDrawSlotControl(region,m_iPad,item,m_menu->isValidIngredient(item, slotId)?1.0f:0.5f,item->isFoil(),true); } void UIScene_AbstractContainerMenu::handleInput(int iPad, int key, bool repeat, bool pressed, bool released, bool &handled) @@ -337,7 +368,7 @@ Slot *UIScene_AbstractContainerMenu::getSlot(ESceneSection eSection, int iSlot) { Slot *slot = m_menu->getSlot( getSectionStartOffset(eSection) + iSlot ); if(slot) return slot; - else return NULL; + else return nullptr; } bool UIScene_AbstractContainerMenu::isSlotEmpty(ESceneSection eSection, int iSlot) diff --git a/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.h b/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.h index 605f5dbdf..f28a5830a 100644 --- a/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.h +++ b/Minecraft.Client/Common/UI/UIScene_AbstractContainerMenu.h @@ -38,6 +38,7 @@ public: int getPad() { return m_iPad; } int getMovieWidth() { return m_movieWidth; } int getMovieHeight() { return m_movieHeight; } + void getMouseToSWFScale(float &scaleX, float &scaleY); bool getIgnoreInput() { return m_bIgnoreInput; } void setIgnoreInput(bool bVal) { m_bIgnoreInput=bVal; } @@ -53,7 +54,7 @@ protected: virtual bool isSlotEmpty(ESceneSection eSection, int iSlot); virtual void adjustPointerForSafeZone(); - virtual UIControl *getSection(ESceneSection eSection) { return NULL; } + virtual UIControl *getSection(ESceneSection eSection) { return nullptr; } virtual int GetBaseSlotCount() { return 0; } public: diff --git a/Minecraft.Client/Common/UI/UIScene_AnvilMenu.cpp b/Minecraft.Client/Common/UI/UIScene_AnvilMenu.cpp index 4d43a638b..a3fb0d2d7 100644 --- a/Minecraft.Client/Common/UI/UIScene_AnvilMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_AnvilMenu.cpp @@ -16,13 +16,13 @@ UIScene_AnvilMenu::UIScene_AnvilMenu(int iPad, void *_initData, UILayer *parentL m_labelAnvil.init( app.GetString(IDS_REPAIR_AND_NAME) ); - AnvilScreenInput *initData = (AnvilScreenInput *)_initData; + AnvilScreenInput *initData = static_cast(_initData); m_inventory = initData->inventory; Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[iPad] != NULL ) + if( pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Anvil_Menu, this); } @@ -263,7 +263,7 @@ void UIScene_AnvilMenu::setSectionSelectedSlot(ESceneSection eSection, int x, in int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionAnvilItem1: @@ -291,7 +291,7 @@ void UIScene_AnvilMenu::setSectionSelectedSlot(ESceneSection eSection, int x, in UIControl *UIScene_AnvilMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionAnvilItem1: @@ -334,7 +334,7 @@ void UIScene_AnvilMenu::onDirectEditFinished(UIControl_TextInput *input, UIContr int UIScene_AnvilMenu::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) { - UIScene_AnvilMenu *pClass=(UIScene_AnvilMenu *)lpParam; + UIScene_AnvilMenu *pClass=static_cast(lpParam); pClass->setIgnoreInput(false); if (bRes) @@ -343,8 +343,8 @@ int UIScene_AnvilMenu::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) uint16_t pchText[128]; ZeroMemory(pchText, 128 * sizeof(uint16_t)); Win64_GetKeyboardText(pchText, 128); - pClass->setEditNameValue((wchar_t *)pchText); - pClass->m_itemName = (wchar_t *)pchText; + pClass->setEditNameValue(reinterpret_cast(pchText)); + pClass->m_itemName = reinterpret_cast(pchText); pClass->updateItemName(); #else uint16_t pchText[128]; @@ -395,7 +395,7 @@ void UIScene_AnvilMenu::handleEditNamePressed() break; } #else - InputManager.RequestKeyboard(app.GetString(IDS_TITLE_RENAME),m_textInputAnvil.getLabel(),(DWORD)m_iPad,30,&UIScene_AnvilMenu::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Default); + InputManager.RequestKeyboard(app.GetString(IDS_TITLE_RENAME),m_textInputAnvil.getLabel(),static_cast(m_iPad),30,&UIScene_AnvilMenu::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Default); #endif #endif } diff --git a/Minecraft.Client/Common/UI/UIScene_BeaconMenu.cpp b/Minecraft.Client/Common/UI/UIScene_BeaconMenu.cpp index e70397d68..64e123736 100644 --- a/Minecraft.Client/Common/UI/UIScene_BeaconMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_BeaconMenu.cpp @@ -21,12 +21,12 @@ UIScene_BeaconMenu::UIScene_BeaconMenu(int iPad, void *_initData, UILayer *paren m_buttonsPowers[eControl_Secondary1].setVisible(false); m_buttonsPowers[eControl_Secondary2].setVisible(false); - BeaconScreenInput *initData = (BeaconScreenInput *)_initData; + BeaconScreenInput *initData = static_cast(_initData); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Beacon_Menu, this); } @@ -254,7 +254,7 @@ void UIScene_BeaconMenu::setSectionSelectedSlot(ESceneSection eSection, int x, i int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionBeaconItem: @@ -276,7 +276,7 @@ void UIScene_BeaconMenu::setSectionSelectedSlot(ESceneSection eSection, int x, i UIControl *UIScene_BeaconMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionBeaconItem: @@ -324,11 +324,11 @@ UIControl *UIScene_BeaconMenu::getSection(ESceneSection eSection) void UIScene_BeaconMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; shared_ptr item = nullptr; int slotId = -1; - swscanf((wchar_t*)region->name,L"slot_%d",&slotId); + swscanf(static_cast(region->name),L"slot_%d",&slotId); if(slotId >= 0 && slotId >= m_menu->getSize() ) { @@ -336,22 +336,22 @@ void UIScene_BeaconMenu::customDraw(IggyCustomDrawCallbackRegion *region) switch(icon) { case 0: - item = shared_ptr(new ItemInstance(Item::emerald) ); + item = std::make_shared(Item::emerald); break; case 1: - item = shared_ptr(new ItemInstance(Item::diamond) ); + item = std::make_shared(Item::diamond); break; case 2: - item = shared_ptr(new ItemInstance(Item::goldIngot) ); + item = std::make_shared(Item::goldIngot); break; case 3: - item = shared_ptr(new ItemInstance(Item::ironIngot) ); + item = std::make_shared(Item::ironIngot); break; default: assert(false); break; }; - if(item != NULL) customDrawSlotControl(region,m_iPad,item,1.0f,item->isFoil(),true); + if(item != nullptr) customDrawSlotControl(region,m_iPad,item,1.0f,item->isFoil(),true); } else { diff --git a/Minecraft.Client/Common/UI/UIScene_BrewingStandMenu.cpp b/Minecraft.Client/Common/UI/UIScene_BrewingStandMenu.cpp index 8563054c6..129868fd0 100644 --- a/Minecraft.Client/Common/UI/UIScene_BrewingStandMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_BrewingStandMenu.cpp @@ -14,15 +14,15 @@ UIScene_BrewingStandMenu::UIScene_BrewingStandMenu(int iPad, void *_initData, UI m_progressBrewingArrow.init(L"",0,0,PotionBrewing::BREWING_TIME_SECONDS * SharedConstants::TICKS_PER_SECOND,0); m_progressBrewingBubbles.init(L"",0,0,30,0); - BrewingScreenInput *initData = (BrewingScreenInput *)_initData; + BrewingScreenInput *initData = static_cast(_initData); m_brewingStand = initData->brewingStand; m_labelBrewingStand.init( m_brewingStand->getName() ); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Brewing_Menu, this); } @@ -249,7 +249,7 @@ void UIScene_BrewingStandMenu::setSectionSelectedSlot(ESceneSection eSection, in int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionBrewingBottle1: @@ -280,7 +280,7 @@ void UIScene_BrewingStandMenu::setSectionSelectedSlot(ESceneSection eSection, in UIControl *UIScene_BrewingStandMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionBrewingBottle1: diff --git a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp index 968072a8e..e10a5a62a 100644 --- a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp +++ b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp @@ -15,7 +15,7 @@ UIScene_ConnectingProgress::UIScene_ConnectingProgress(int iPad, void *_initData m_progressBar.setVisible( false ); m_labelTip.setVisible( false ); - ConnectionProgressParams *param = (ConnectionProgressParams *)_initData; + ConnectionProgressParams *param = static_cast(_initData); if( param->stringId >= 0 ) { @@ -210,7 +210,7 @@ void UIScene_ConnectingProgress::handleInput(int iPad, int key, bool repeat, boo // 4J-PB - Removed the option to cancel join - it didn't work anyway // case ACTION_MENU_CANCEL: // { -// if(m_cancelFunc != NULL) +// if(m_cancelFunc != nullptr) // { // m_cancelFunc(m_cancelFuncParam); // } @@ -245,7 +245,7 @@ void UIScene_ConnectingProgress::handleInput(int iPad, int key, bool repeat, boo void UIScene_ConnectingProgress::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Confirm: if(m_showingButton) diff --git a/Minecraft.Client/Common/UI/UIScene_ContainerMenu.cpp b/Minecraft.Client/Common/UI/UIScene_ContainerMenu.cpp index 9e48a57b2..b26ae48e9 100644 --- a/Minecraft.Client/Common/UI/UIScene_ContainerMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_ContainerMenu.cpp @@ -13,7 +13,7 @@ UIScene_ContainerMenu::UIScene_ContainerMenu(int iPad, void *_initData, UILayer *parentLayer) : UIScene_AbstractContainerMenu(iPad, parentLayer) { - ContainerScreenInput *initData = (ContainerScreenInput *)_initData; + ContainerScreenInput *initData = static_cast(_initData); m_bLargeChest = (initData->container->getContainerSize() > 3*9)?true:false; // Setup all the Iggy references we need for this scene @@ -24,9 +24,9 @@ UIScene_ContainerMenu::UIScene_ContainerMenu(int iPad, void *_initData, UILayer ContainerMenu* menu = new ContainerMenu( initData->inventory, initData->container ); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[iPad] != NULL ) + if( pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Container_Menu, this); } @@ -181,7 +181,7 @@ void UIScene_ContainerMenu::setSectionSelectedSlot(ESceneSection eSection, int x int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionContainerChest: @@ -203,7 +203,7 @@ void UIScene_ContainerMenu::setSectionSelectedSlot(ESceneSection eSection, int x UIControl *UIScene_ContainerMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionContainerChest: diff --git a/Minecraft.Client/Common/UI/UIScene_ControlsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_ControlsMenu.cpp index 575672485..939efde11 100644 --- a/Minecraft.Client/Common/UI/UIScene_ControlsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_ControlsMenu.cpp @@ -13,7 +13,7 @@ UIScene_ControlsMenu::UIScene_ControlsMenu(int iPad, void *initData, UILayer *pa IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; #if defined(_XBOX) || defined(_WIN64) - value[0].number = (F64)0; + value[0].number = static_cast(0); #elif defined(_DURANGO) value[0].number = (F64)1; #elif defined(__PS3__) @@ -25,7 +25,7 @@ UIScene_ControlsMenu::UIScene_ControlsMenu(int iPad, void *initData, UILayer *pa #endif IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetPlatform , 1 , value ); - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { @@ -84,7 +84,7 @@ UIScene_ControlsMenu::UIScene_ControlsMenu(int iPad, void *initData, UILayer *pa IggyDataValue result; IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (F64)m_iCurrentNavigatedControlsLayout; + value[0].number = static_cast(m_iCurrentNavigatedControlsLayout); IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetControllerLayout , 1 , value ); } @@ -180,7 +180,7 @@ void UIScene_ControlsMenu::handleInput(int iPad, int key, bool repeat, bool pres void UIScene_ControlsMenu::handleCheckboxToggled(F64 controlId, bool selected) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_InvertLook: app.SetGameSettings(m_iPad,eGameSetting_ControlInvertLook,(unsigned char)( selected ) ); @@ -194,13 +194,13 @@ void UIScene_ControlsMenu::handleCheckboxToggled(F64 controlId, bool selected) void UIScene_ControlsMenu::handlePress(F64 controlId, F64 childId) { - int control = (int)controlId; + int control = static_cast(controlId); switch(control) { case eControl_Button0: case eControl_Button1: case eControl_Button2: - app.SetGameSettings(m_iPad,eGameSetting_ControlScheme,(unsigned char)control); + app.SetGameSettings(m_iPad,eGameSetting_ControlScheme,static_cast(control)); LPWSTR layoutString = new wchar_t[ 128 ]; swprintf( layoutString, 128, L"%ls : %ls", app.GetString( IDS_CURRENT_LAYOUT ),app.GetString(m_iSchemeTextA[control])); #ifdef __ORBIS__ @@ -216,7 +216,7 @@ void UIScene_ControlsMenu::handlePress(F64 controlId, F64 childId) void UIScene_ControlsMenu::handleFocusChange(F64 controlId, F64 childId) { - int control = (int)controlId; + int control = static_cast(controlId); switch(control) { case eControl_Button0: diff --git a/Minecraft.Client/Common/UI/UIScene_CraftingMenu.cpp b/Minecraft.Client/Common/UI/UIScene_CraftingMenu.cpp index 2d1b4302f..16b63c4c5 100644 --- a/Minecraft.Client/Common/UI/UIScene_CraftingMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_CraftingMenu.cpp @@ -22,7 +22,7 @@ UIScene_CraftingMenu::UIScene_CraftingMenu(int iPad, void *_initData, UILayer *p #endif m_bIgnoreKeyPresses = false; - CraftingPanelScreenInput* initData = (CraftingPanelScreenInput*)_initData; + CraftingPanelScreenInput* initData = static_cast(_initData); m_iContainerType=initData->iContainerType; m_pPlayer=initData->player; m_bSplitscreen=initData->bSplitscreen; @@ -117,9 +117,9 @@ UIScene_CraftingMenu::UIScene_CraftingMenu(int iPad, void *_initData, UILayer *p // Update the tutorial state Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); if(m_iContainerType==RECIPE_TYPE_2x2) { @@ -198,14 +198,14 @@ void UIScene_CraftingMenu::handleDestroy() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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]->containerMenu->containerId == m_menu->containerId) + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr && Minecraft::GetInstance()->localplayers[m_iPad]->containerMenu->containerId == m_menu->containerId) { Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); } @@ -525,14 +525,14 @@ void UIScene_CraftingMenu::handleReload() void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; shared_ptr item = nullptr; int slotId = -1; float alpha = 1.0f; bool decorations = true; bool inventoryItem = false; - swscanf((wchar_t*)region->name,L"slot_%d",&slotId); + swscanf(static_cast(region->name),L"slot_%d",&slotId); if (slotId == -1) { app.DebugPrintf("This is not the control we are looking for\n"); @@ -560,7 +560,7 @@ void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) if(m_vSlotsInfo[iIndex].show) { item = m_vSlotsInfo[iIndex].item; - alpha = ((float)m_vSlotsInfo[iIndex].alpha)/31.0f; + alpha = static_cast(m_vSlotsInfo[iIndex].alpha)/31.0f; } } else if(slotId >= CRAFTING_H_SLOT_START && slotId < (CRAFTING_H_SLOT_START + m_iCraftablesMaxHSlotC) ) @@ -596,7 +596,7 @@ void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) if(m_hSlotsInfo[iIndex].show) { item = m_hSlotsInfo[iIndex].item; - alpha = ((float)m_hSlotsInfo[iIndex].alpha)/31.0f; + alpha = static_cast(m_hSlotsInfo[iIndex].alpha)/31.0f; } } else if(slotId >= CRAFTING_INGREDIENTS_LAYOUT_START && slotId < (CRAFTING_INGREDIENTS_LAYOUT_START + m_iIngredientsMaxSlotC) ) @@ -605,7 +605,7 @@ void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) if(m_ingredientsSlotsInfo[iIndex].show) { item = m_ingredientsSlotsInfo[iIndex].item; - alpha = ((float)m_ingredientsSlotsInfo[iIndex].alpha)/31.0f; + alpha = static_cast(m_ingredientsSlotsInfo[iIndex].alpha)/31.0f; } } else if(slotId >= CRAFTING_INGREDIENTS_DESCRIPTION_START && slotId < (CRAFTING_INGREDIENTS_DESCRIPTION_START + 4) ) @@ -614,7 +614,7 @@ void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) if(m_ingredientsInfo[iIndex].show) { item = m_ingredientsInfo[iIndex].item; - alpha = ((float)m_ingredientsInfo[iIndex].alpha)/31.0f; + alpha = static_cast(m_ingredientsInfo[iIndex].alpha)/31.0f; } } else if(slotId == CRAFTING_OUTPUT_SLOT_START ) @@ -622,11 +622,11 @@ void UIScene_CraftingMenu::customDraw(IggyCustomDrawCallbackRegion *region) if(m_craftingOutputSlotInfo.show) { item = m_craftingOutputSlotInfo.item; - alpha = ((float)m_craftingOutputSlotInfo.alpha)/31.0f; + alpha = static_cast(m_craftingOutputSlotInfo.alpha)/31.0f; } } - if(item != NULL) + if(item != nullptr) { if(!inventoryItem) { @@ -742,7 +742,7 @@ void UIScene_CraftingMenu::setCraftingOutputSlotItem(int iPad, shared_ptrgetId(); - m_pDLCPack = NULL; + m_pDLCPack = nullptr; m_bRebuildTouchBoxes = false; m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); @@ -96,7 +96,7 @@ UIScene_CreateWorldMenu::UIScene_CreateWorldMenu(int iPad, void *initData, UILay // #ifdef __PS3__ // if(ProfileManager.IsSignedInLive( m_iPad )) // { - // ProfileManager.GetChatAndContentRestrictions(m_iPad,true,&bChatRestricted,&bContentRestricted,NULL); + // ProfileManager.GetChatAndContentRestrictions(m_iPad,true,&bChatRestricted,&bContentRestricted,nullptr); // } // #endif @@ -184,7 +184,7 @@ UIScene_CreateWorldMenu::UIScene_CreateWorldMenu(int iPad, void *initData, UILay #if TO_BE_IMPLEMENTED // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -289,7 +289,6 @@ void UIScene_CreateWorldMenu::tick() { UIScene::tick(); - if(m_iSetTexturePackDescription >= 0 ) { UpdateTexturePackDescription( m_iSetTexturePackDescription ); @@ -432,7 +431,7 @@ void UIScene_CreateWorldMenu::handlePress(F64 controlId, F64 childId) //CD - Added for audio ui.PlayUISFX(eSFX_Press); - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_EditWorldName: { @@ -482,7 +481,7 @@ void UIScene_CreateWorldMenu::handlePress(F64 controlId, F64 childId) break; case eControl_TexturePackList: { - UpdateCurrentTexturePack((int)childId); + UpdateCurrentTexturePack(static_cast(childId)); } break; case eControl_NewWorld: @@ -528,7 +527,7 @@ void UIScene_CreateWorldMenu::StartSharedLaunchFlow() // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack==nullptr) { #if TO_BE_IMPLEMENTED // They've selected a texture pack they don't have yet @@ -578,7 +577,7 @@ void UIScene_CreateWorldMenu::StartSharedLaunchFlow() { // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)pTexturePack; + DLCTexturePack *pDLCTexPack=static_cast(pTexturePack); m_pDLCPack=pDLCTexPack->getDLCInfoParentPack(); // do we have a license? @@ -606,7 +605,7 @@ void UIScene_CreateWorldMenu::StartSharedLaunchFlow() DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_pDLCPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -649,8 +648,8 @@ void UIScene_CreateWorldMenu::StartSharedLaunchFlow() void UIScene_CreateWorldMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_Difficulty: m_sliderDifficulty.handleSliderMove(value); @@ -725,7 +724,7 @@ void UIScene_CreateWorldMenu::handleTimerComplete(int id) if(m_iConfigA[i]!=-1) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; //app.DebugPrintf("Retrieving iConfig %d from TPD\n",m_iConfigA[i]); app.GetTPD(m_iConfigA[i],&pbData,&dwBytes); @@ -734,7 +733,7 @@ void UIScene_CreateWorldMenu::handleTimerComplete(int id) if(dwBytes > 0 && pbData) { DWORD dwImageBytes=0; - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; app.GetFileFromTPD(eTPDFileType_Icon,pbData,dwBytes,&pbImageData,&dwImageBytes ); ListInfo.fEnabled = TRUE; @@ -764,7 +763,7 @@ void UIScene_CreateWorldMenu::handleGainFocus(bool navBack) int UIScene_CreateWorldMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,bool bRes) { - UIScene_CreateWorldMenu *pClass=(UIScene_CreateWorldMenu *)lpParam; + UIScene_CreateWorldMenu *pClass=static_cast(lpParam); pClass->m_bIgnoreInput=false; // 4J HEG - No reason to set value if keyboard was cancelled if (bRes) @@ -891,7 +890,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return; } @@ -911,7 +910,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // UINT uiIDA[2]; // uiIDA[0]=IDS_PLAY_OFFLINE; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; -// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),NULL,0,false); +// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),nullptr,0,false); return; } } @@ -951,7 +950,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() #if defined(__PS3__) || defined(__PSVITA__) if(isOnlineGame && isSignedInLive) { - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,nullptr,&bContentRestricted,nullptr); } #endif @@ -980,7 +979,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return; } @@ -998,7 +997,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // UINT uiIDA[2]; // uiIDA[0]=IDS_PLAY_OFFLINE; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; -// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),NULL,0,false); +// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),nullptr,0,false); } #endif @@ -1040,7 +1039,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return; } @@ -1062,7 +1061,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() // UINT uiIDA[2]; // uiIDA[0]=IDS_PLAY_OFFLINE; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; -// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),NULL,0,false); +// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_CreateWorldMenu::PSPlusReturned,this, app.GetStringTable(),nullptr,0,false); } #endif @@ -1072,7 +1071,7 @@ void UIScene_CreateWorldMenu::checkStateAndStartGame() if(isOnlineGame) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); @@ -1136,7 +1135,7 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD if (wSeed.length() != 0) { int64_t value = 0; - unsigned int len = (unsigned int)wSeed.length(); + unsigned int len = static_cast(wSeed.length()); //Check if the input string contains a numerical value bool isNumber = true; @@ -1174,7 +1173,7 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; param->texturePackId = pClass->m_MoreOptionsParams.dwTexturePack; Minecraft *pMinecraft = Minecraft::GetInstance(); @@ -1210,8 +1209,8 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD app.SetGameHostOption(eGameHostOption_WasntSaveOwner, false); #ifdef _LARGE_WORLDS app.SetGameHostOption(eGameHostOption_WorldSize, pClass->m_MoreOptionsParams.worldSize+1 ); // 0 is GAME_HOST_OPTION_WORLDSIZE_UNKNOWN - pClass->m_MoreOptionsParams.currentWorldSize = (EGameHostOptionWorldSize)(pClass->m_MoreOptionsParams.worldSize+1); - pClass->m_MoreOptionsParams.newWorldSize = (EGameHostOptionWorldSize)(pClass->m_MoreOptionsParams.worldSize+1); + pClass->m_MoreOptionsParams.currentWorldSize = static_cast(pClass->m_MoreOptionsParams.worldSize + 1); + pClass->m_MoreOptionsParams.newWorldSize = static_cast(pClass->m_MoreOptionsParams.worldSize + 1); #endif g_NetworkManager.HostGame(dwLocalUsersMask,isClientSide,isPrivate,MINECRAFT_NET_MAX_PLAYERS,0); @@ -1253,7 +1252,7 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave time app.SetAutosaveTimerTime(); @@ -1271,7 +1270,7 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD int UIScene_CreateWorldMenu::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - UIScene_CreateWorldMenu* pClass = (UIScene_CreateWorldMenu*)pParam; + UIScene_CreateWorldMenu* pClass = static_cast(pParam); if(bContinue==true) { @@ -1379,7 +1378,7 @@ int UIScene_CreateWorldMenu::StartGame_SignInReturned(void *pParam,bool bContinu int UIScene_CreateWorldMenu::ConfirmCreateReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_CreateWorldMenu* pClass = (UIScene_CreateWorldMenu*)pParam; + UIScene_CreateWorldMenu* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -1432,7 +1431,7 @@ int UIScene_CreateWorldMenu::ConfirmCreateReturned(void *pParam,int iPad,C4JStor if(isOnlineGame) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); diff --git a/Minecraft.Client/Common/UI/UIScene_CreativeMenu.cpp b/Minecraft.Client/Common/UI/UIScene_CreativeMenu.cpp index 0895cdffe..ba2cd8452 100644 --- a/Minecraft.Client/Common/UI/UIScene_CreativeMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_CreativeMenu.cpp @@ -19,9 +19,9 @@ UIScene_CreativeMenu::UIScene_CreativeMenu(int iPad, void *_initData, UILayer *p // Setup all the Iggy references we need for this scene initialiseMovie(); - InventoryScreenInput *initData = (InventoryScreenInput *)_initData; + InventoryScreenInput *initData = static_cast(_initData); - shared_ptr creativeContainer = shared_ptr(new SimpleContainer( 0, L"", false, TabSpec::MAX_SIZE )); + shared_ptr creativeContainer = std::make_shared(0, L"", false, TabSpec::MAX_SIZE); itemPickerMenu = new ItemPickerMenu(creativeContainer, initData->player->inventory); Initialize( initData->iPad, itemPickerMenu, false, -1, eSectionInventoryCreativeUsing, eSectionInventoryCreativeMax, initData->bNavigateBack); @@ -42,9 +42,9 @@ UIScene_CreativeMenu::UIScene_CreativeMenu(int iPad, void *_initData, UILayer *p } Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Creative_Inventory_Menu, this); } @@ -144,7 +144,7 @@ void UIScene_CreativeMenu::handleOtherClicked(int iPad, ESceneSection eSection, case eSectionInventoryCreativeTab_6: case eSectionInventoryCreativeTab_7: { - ECreativeInventoryTabs tab = (ECreativeInventoryTabs)((int)eCreativeInventoryTab_BuildingBlocks + (int)eSection - (int)eSectionInventoryCreativeTab_0); + ECreativeInventoryTabs tab = static_cast((int)eCreativeInventoryTab_BuildingBlocks + (int)eSection - (int)eSectionInventoryCreativeTab_0); if(tab != m_curTab) { switchTab(tab); @@ -193,8 +193,8 @@ void UIScene_CreativeMenu::handleInput(int iPad, int key, bool repeat, bool pres // Fall through intentional case VK_PAD_RSHOULDER: { - ECreativeInventoryTabs tab = (ECreativeInventoryTabs)(m_curTab + dir); - if (tab < 0) tab = (ECreativeInventoryTabs)(eCreativeInventoryTab_COUNT - 1); + ECreativeInventoryTabs tab = static_cast(m_curTab + dir); + if (tab < 0) tab = static_cast(eCreativeInventoryTab_COUNT - 1); if (tab >= eCreativeInventoryTab_COUNT) tab = eCreativeInventoryTab_BuildingBlocks; switchTab(tab); ui.PlayUISFX(eSFX_Focus); @@ -220,7 +220,7 @@ void UIScene_CreativeMenu::updateTabHighlightAndText(ECreativeInventoryTabs tab) IggyDataValue value[1]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (F64)tab; + value[0].number = static_cast(tab); IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ) , m_funcSetActiveTab , 1 , value ); @@ -400,7 +400,7 @@ void UIScene_CreativeMenu::setSectionSelectedSlot(ESceneSection eSection, int x, int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionInventoryCreativeSelector: @@ -419,7 +419,7 @@ void UIScene_CreativeMenu::setSectionSelectedSlot(ESceneSection eSection, int x, UIControl *UIScene_CreativeMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionInventoryCreativeSelector: @@ -468,10 +468,10 @@ void UIScene_CreativeMenu::updateScrollCurrentPage(int currentPage, int pageCoun IggyDataValue value[2]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (F64)pageCount; + value[0].number = static_cast(pageCount); value[1].type = IGGY_DATATYPE_number; - value[1].number = (F64)currentPage - 1; + value[1].number = static_cast(currentPage) - 1; IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ) , m_funcSetScrollBar , 2 , value ); } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIScene_Credits.cpp b/Minecraft.Client/Common/UI/UIScene_Credits.cpp index 75ddf92ff..9900169ce 100644 --- a/Minecraft.Client/Common/UI/UIScene_Credits.cpp +++ b/Minecraft.Client/Common/UI/UIScene_Credits.cpp @@ -593,11 +593,11 @@ void UIScene_Credits::tick() } // Set up the new text element. - if(pDef->m_Text!=NULL) // 4J-PB - think the RAD logo ones aren't set up yet and are coming is as null + if(pDef->m_Text!=nullptr) // 4J-PB - think the RAD logo ones aren't set up yet and are coming is as null { if ( pDef->m_iStringID[0] == CREDIT_ICON ) { - addImage((ECreditIcons)pDef->m_iStringID[1]); + addImage(static_cast(pDef->m_iStringID[1])); } else // using additional translated string. { @@ -670,7 +670,7 @@ void UIScene_Credits::setNextLabel(const wstring &label, ECreditTextTypes size) value[0].string16 = stringVal; value[1].type = IGGY_DATATYPE_number; - value[1].number = (int)size; + value[1].number = static_cast(size); value[2].type = IGGY_DATATYPE_boolean; value[2].boolval = (m_iCurrDefIndex == (m_iNumTextDefs - 1)); @@ -684,7 +684,7 @@ void UIScene_Credits::addImage(ECreditIcons icon) IggyDataValue value[2]; value[0].type = IGGY_DATATYPE_number; - value[0].number = (int)icon; + value[0].number = static_cast(icon); value[1].type = IGGY_DATATYPE_boolean; value[1].boolval = (m_iCurrDefIndex == (m_iNumTextDefs - 1)); diff --git a/Minecraft.Client/Common/UI/UIScene_DLCMainMenu.cpp b/Minecraft.Client/Common/UI/UIScene_DLCMainMenu.cpp index 77ffdffd9..6d705765e 100644 --- a/Minecraft.Client/Common/UI/UIScene_DLCMainMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DLCMainMenu.cpp @@ -121,11 +121,11 @@ void UIScene_DLCMainMenu::handleInput(int iPad, int key, bool repeat, bool press void UIScene_DLCMainMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_OffersList: { - int iIndex = (int)childId; + int iIndex = static_cast(childId); DLCOffersParam *param = new DLCOffersParam(); param->iPad = m_iPad; @@ -134,7 +134,7 @@ void UIScene_DLCMainMenu::handlePress(F64 controlId, F64 childId) // Xbox One will have requested the marketplace content - there is only that type #ifndef _XBOX_ONE - app.AddDLCRequest((eDLCMarketplaceType)iIndex, true); + app.AddDLCRequest(static_cast(iIndex), true); #endif killTimer(PLAYER_ONLINE_TIMER_ID); ui.NavigateToScene(m_iPad, eUIScene_DLCOffersMenu, param); @@ -166,7 +166,7 @@ void UIScene_DLCMainMenu::handleTimerComplete(int id) int UIScene_DLCMainMenu::ExitDLCMainMenu(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_DLCMainMenu* pClass = (UIScene_DLCMainMenu*)pParam; + UIScene_DLCMainMenu* pClass = static_cast(pParam); #if defined __ORBIS__ || defined __PSVITA__ app.GetCommerce()->HidePsStoreIcon(); diff --git a/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp b/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp index c109ed62b..5e644803b 100644 --- a/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp @@ -16,12 +16,12 @@ UIScene_DLCOffersMenu::UIScene_DLCOffersMenu(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { m_bProductInfoShown=false; - DLCOffersParam *param=(DLCOffersParam *)initData; + DLCOffersParam *param=static_cast(initData); m_iProductInfoIndex=param->iType; m_iCurrentDLC=0; m_iTotalDLC=0; #if defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) - m_pvProductInfo=NULL; + m_pvProductInfo=nullptr; #endif m_bAddAllDLCButtons=true; @@ -51,7 +51,7 @@ UIScene_DLCOffersMenu::UIScene_DLCOffersMenu(int iPad, void *initData, UILayer * } #ifdef _DURANGO - m_pNoImageFor_DLC = NULL; + m_pNoImageFor_DLC = nullptr; // If we don't yet have this DLC, we need to display a timer m_bDLCRequiredIsRetrieved=false; m_bIgnorePress=true; @@ -103,7 +103,7 @@ void UIScene_DLCOffersMenu::handleTimerComplete(int id) int UIScene_DLCOffersMenu::ExitDLCOffersMenu(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_DLCOffersMenu* pClass = (UIScene_DLCOffersMenu*)pParam; + UIScene_DLCOffersMenu* pClass = static_cast(pParam); #if defined __ORBIS__ || defined __PSVITA__ app.GetCommerce()->HidePsStoreIcon(); @@ -217,7 +217,7 @@ void UIScene_DLCOffersMenu::handleInput(int iPad, int key, bool repeat, bool pre void UIScene_DLCOffersMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_OffersList: { @@ -261,13 +261,13 @@ void UIScene_DLCOffersMenu::handlePress(F64 controlId, F64 childId) #endif // __PS3__ #elif defined _XBOX_ONE int iIndex = (int)childId; - StorageManager.InstallOffer(1,StorageManager.GetOffer(iIndex).wszProductID,NULL,NULL); + StorageManager.InstallOffer(1,StorageManager.GetOffer(iIndex).wszProductID,nullptr,nullptr); #else - int iIndex = (int)childId; + int iIndex = static_cast(childId); ULONGLONG ullIndexA[1]; ullIndexA[0]=StorageManager.GetOffer(iIndex).qwOfferID; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); #endif } break; @@ -343,10 +343,10 @@ void UIScene_DLCOffersMenu::tick() { m_bAddAllDLCButtons=false; // add the categories to the list box - if(m_pvProductInfo==NULL) + if(m_pvProductInfo==nullptr) { m_pvProductInfo=app.GetProductList(m_iProductInfoIndex); - if(m_pvProductInfo==NULL) + if(m_pvProductInfo==nullptr) { m_iTotalDLC=0; // need to display text to say no downloadable content available yet @@ -690,7 +690,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // Check that this is in the list of known DLC DLC_INFO *pDLC=app.GetDLCInfoForFullOfferID(xOffer.wszProductID); - if(pDLC!=NULL) + if(pDLC!=nullptr) { OrderA[uiDLCCount].uiContentIndex=i; OrderA[uiDLCCount++].uiSortIndex=pDLC->uiSortIndex; @@ -710,7 +710,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // Check that this is in the list of known DLC DLC_INFO *pDLC=app.GetDLCInfoForFullOfferID(xOffer.wszProductID); - if(pDLC==NULL) + if(pDLC==nullptr) { // skip this one app.DebugPrintf("Unknown offer - %ls\n",xOffer.wszOfferName); @@ -736,7 +736,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // find the DLC in the installed packages XCONTENT_DATA *pContentData=StorageManager.GetInstalledDLC(xOffer.wszProductID); - if(pContentData!=NULL) + if(pContentData!=nullptr) { m_buttonListOffers.addItem(wstrTemp,!pContentData->bTrialLicense,OrderA[i].uiContentIndex); } @@ -809,7 +809,7 @@ bool UIScene_DLCOffersMenu::UpdateDisplay(MARKETPLACE_CONTENTOFFER_INFO& xOffer) DLC_INFO *dlc = app.GetDLCInfoForFullOfferID(xOffer.wszOfferName); #endif - if (dlc != NULL) + if (dlc != nullptr) { WCHAR *cString = dlc->wchBanner; @@ -844,7 +844,7 @@ bool UIScene_DLCOffersMenu::UpdateDisplay(MARKETPLACE_CONTENTOFFER_INFO& xOffer) { if(hasRegisteredSubstitutionTexture(cString)==false) { - BYTE *pData=NULL; + BYTE *pData=nullptr; DWORD dwSize=0; app.GetMemFileDetails(cString,&pData,&dwSize); // set the image diff --git a/Minecraft.Client/Common/UI/UIScene_DeathMenu.cpp b/Minecraft.Client/Common/UI/UIScene_DeathMenu.cpp index 8f0f4c110..a4dbe8a82 100644 --- a/Minecraft.Client/Common/UI/UIScene_DeathMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DeathMenu.cpp @@ -18,9 +18,9 @@ UIScene_DeathMenu::UIScene_DeathMenu(int iPad, void *initData, UILayer *parentLa m_bIgnoreInput = false; Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[iPad]); // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(false); @@ -30,9 +30,9 @@ UIScene_DeathMenu::UIScene_DeathMenu(int iPad, void *initData, UILayer *parentLa UIScene_DeathMenu::~UIScene_DeathMenu() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(true); @@ -81,7 +81,7 @@ void UIScene_DeathMenu::handleInput(int iPad, int key, bool repeat, bool pressed void UIScene_DeathMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Respawn: m_bIgnoreInput = true; @@ -104,9 +104,9 @@ void UIScene_DeathMenu::handlePress(F64 controlId, F64 childId) { UINT uiIDA[3]; int playTime = -1; - if( pMinecraft->localplayers[m_iPad] != NULL ) + if( pMinecraft->localplayers[m_iPad] != nullptr ) { - playTime = (int)pMinecraft->localplayers[m_iPad]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[m_iPad]->getSessionTimer()); } TelemetryManager->RecordLevelExit(m_iPad, eSen_LevelExitStatus_Failed); diff --git a/Minecraft.Client/Common/UI/UIScene_DebugCreateSchematic.cpp b/Minecraft.Client/Common/UI/UIScene_DebugCreateSchematic.cpp index d3da08709..d698b51f5 100644 --- a/Minecraft.Client/Common/UI/UIScene_DebugCreateSchematic.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DebugCreateSchematic.cpp @@ -132,82 +132,96 @@ void UIScene_DebugCreateSchematic::handleInput(int iPad, int key, bool repeat, b void UIScene_DebugCreateSchematic::handlePress(F64 controlId, F64 childId) { #ifdef _WINDOWS64 - if (isDirectEditBlocking()) return; + if (isDirectEditBlocking()) + return; #endif - switch((int)controlId) - { - case eControl_Create: - { - // We want the start to be even - if(m_data->startX > 0 && m_data->startX%2 != 0) - m_data->startX-=1; - else if(m_data->startX < 0 && m_data->startX%2 !=0) - m_data->startX-=1; - if(m_data->startY < 0) m_data->startY = 0; - else if(m_data->startY > 0 && m_data->startY%2 != 0) - m_data->startY-=1; - if(m_data->startZ > 0 && m_data->startZ%2 != 0) - m_data->startZ-=1; - else if(m_data->startZ < 0 && m_data->startZ%2 !=0) - m_data->startZ-=1; - // We want the end to be odd to have a total size that is even - if(m_data->endX > 0 && m_data->endX%2 == 0) - m_data->endX+=1; - else if(m_data->endX < 0 && m_data->endX%2 ==0) - m_data->endX+=1; - if(m_data->endY > Level::maxBuildHeight) - m_data->endY = Level::maxBuildHeight; - else if(m_data->endY > 0 && m_data->endY%2 == 0) - m_data->endY+=1; - else if(m_data->endY < 0 && m_data->endY%2 ==0) - m_data->endY+=1; - if(m_data->endZ > 0 && m_data->endZ%2 == 0) - m_data->endZ+=1; - else if(m_data->endZ < 0 && m_data->endZ%2 ==0) - m_data->endZ+=1; + switch (static_cast(controlId)) + { + case eControl_Create: + { + // We want the start to be even + if (m_data->startX > 0 && m_data->startX % 2 != 0) + m_data->startX -= 1; + else if (m_data->startX < 0 && m_data->startX % 2 != 0) + m_data->startX -= 1; - app.SetXuiServerAction(ProfileManager.GetPrimaryPad(), eXuiServerAction_ExportSchematic, (void *)m_data); + if (m_data->startY < 0) + m_data->startY = 0; + else if (m_data->startY > 0 && m_data->startY % 2 != 0) + m_data->startY -= 1; - navigateBack(); - } - break; - case eControl_Name: - case eControl_StartX: - case eControl_StartY: - case eControl_StartZ: - case eControl_EndX: - case eControl_EndY: - case eControl_EndZ: - { - m_keyboardCallbackControl = (eControls)((int)controlId); + if (m_data->startZ > 0 && m_data->startZ % 2 != 0) + m_data->startZ -= 1; + else if (m_data->startZ < 0 && m_data->startZ % 2 != 0) + m_data->startZ -= 1; + + // We want the end to be odd to have a total size that is even + if (m_data->endX > 0 && m_data->endX % 2 == 0) + m_data->endX += 1; + else if (m_data->endX < 0 && m_data->endX % 2 == 0) + m_data->endX += 1; + + if (m_data->endY > Level::maxBuildHeight) + m_data->endY = Level::maxBuildHeight; + else if (m_data->endY > 0 && m_data->endY % 2 == 0) + m_data->endY += 1; + else if (m_data->endY < 0 && m_data->endY % 2 == 0) + m_data->endY += 1; + + if (m_data->endZ > 0 && m_data->endZ % 2 == 0) + m_data->endZ += 1; + else if (m_data->endZ < 0 && m_data->endZ % 2 == 0) + m_data->endZ += 1; + + app.SetXuiServerAction(ProfileManager.GetPrimaryPad(), eXuiServerAction_ExportSchematic, static_cast(m_data)); + navigateBack(); + } + break; + + case eControl_Name: + case eControl_StartX: + case eControl_StartY: + case eControl_StartZ: + case eControl_EndX: + case eControl_EndY: + case eControl_EndZ: + { + m_keyboardCallbackControl = static_cast(static_cast(controlId)); #ifdef _WINDOWS64 - if (g_KBMInput.IsKBMActive()) - { - UIControl_TextInput* input = getTextInputForControl(m_keyboardCallbackControl); - if (input) input->beginDirectEdit(25); - } - else - { - UIKeyboardInitData kbData; - kbData.title = L"Enter something"; - kbData.defaultText = L""; - kbData.maxChars = 25; - kbData.callback = &UIScene_DebugCreateSchematic::KeyboardCompleteCallback; - kbData.lpParam = this; - ui.NavigateToScene(m_iPad, eUIScene_Keyboard, &kbData, eUILayer_Fullscreen, eUIGroup_Fullscreen); - } + if (g_KBMInput.IsKBMActive()) + { + UIControl_TextInput* input = getTextInputForControl(m_keyboardCallbackControl); + if (input) input->beginDirectEdit(25); + } + else + { + UIKeyboardInitData kbData; + kbData.title = L"Enter something"; + kbData.defaultText = L""; + kbData.maxChars = 25; + kbData.callback = &UIScene_DebugCreateSchematic::KeyboardCompleteCallback; + kbData.lpParam = this; + ui.NavigateToScene(m_iPad, eUIScene_Keyboard, &kbData, eUILayer_Fullscreen, eUIGroup_Fullscreen); + } #else - InputManager.RequestKeyboard(L"Enter something",L"",(DWORD)0,25,&UIScene_DebugCreateSchematic::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Default); + InputManager.RequestKeyboard( + L"Enter something", + L"", + static_cast(0), + 25, + &UIScene_DebugCreateSchematic::KeyboardCompleteCallback, + this, + C_4JInput::EKeyboardMode_Default); #endif - } - break; - }; + } + break; + } } void UIScene_DebugCreateSchematic::handleCheckboxToggled(F64 controlId, bool selected) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_SaveMobs: m_data->bSaveMobs = selected; @@ -223,7 +237,7 @@ void UIScene_DebugCreateSchematic::handleCheckboxToggled(F64 controlId, bool sel int UIScene_DebugCreateSchematic::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) { - UIScene_DebugCreateSchematic *pClass=(UIScene_DebugCreateSchematic *)lpParam; + UIScene_DebugCreateSchematic *pClass=static_cast(lpParam); #ifdef _WINDOWS64 uint16_t pchText[128]; diff --git a/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp b/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp index fafcea027..c997fb311 100644 --- a/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp @@ -21,16 +21,16 @@ UIScene_DebugOverlay::UIScene_DebugOverlay(int iPad, void *initData, UILayer *pa // Setup all the Iggy references we need for this scene initialiseMovie(); - Minecraft *pMinecraft = Minecraft::GetInstance(); - WCHAR TempString[256]; - int fovSliderVal = app.GetGameSettings(m_iPad, eGameSetting_FOV); - int fovDeg = 70 + fovSliderVal * 40 / 100; - swprintf( (WCHAR *)TempString, 256, L"Set fov (%d)", fovDeg); - m_sliderFov.init(TempString,eControl_FOV,0,100,fovSliderVal); + const Minecraft *pMinecraft = Minecraft::GetInstance(); + WCHAR tempString[256]; + const int fovSliderVal = app.GetGameSettings(m_iPad, eGameSetting_FOV); + const int fovDeg = 70 + fovSliderVal * 40 / 100; + swprintf( tempString, 256, L"Set fov (%d)", fovDeg); + m_sliderFov.init(tempString,eControl_FOV,0,100,fovSliderVal); - float currentTime = pMinecraft->level->getLevelData()->getGameTime() % 24000; - swprintf( (WCHAR *)TempString, 256, L"Set time (unsafe) (%d)", (int)currentTime); - m_sliderTime.init(TempString,eControl_Time,0,240,currentTime/100); + const float currentTime = pMinecraft->level->getLevelData()->getGameTime() % 24000; + swprintf( tempString, 256, L"Set time (unsafe) (%d)", static_cast(currentTime)); + m_sliderTime.init(tempString,eControl_Time,0,240,currentTime/100); m_buttonRain.init(L"Toggle Rain",eControl_Rain); m_buttonThunder.init(L"Toggle Thunder",eControl_Thunder); @@ -46,7 +46,7 @@ UIScene_DebugOverlay::UIScene_DebugOverlay(int iPad, void *initData, UILayer *pa std::vector> sortedItems; for (size_t i = 0; i < Item::items.length; ++i) { - if (Item::items[i] != NULL) + if (Item::items[i] != nullptr) { sortedItems.emplace_back(std::wstring(app.GetString(Item::items[i]->getDescriptionId())), i); } @@ -138,19 +138,19 @@ wstring UIScene_DebugOverlay::getMoviePath() void UIScene_DebugOverlay::customDraw(IggyCustomDrawCallbackRegion *region) { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + const Minecraft *pMinecraft = Minecraft::GetInstance(); + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; int itemId = -1; - swscanf((wchar_t*)region->name,L"item_%d",&itemId); - if (itemId == -1 || itemId > Item::ITEM_NUM_COUNT || Item::items[itemId] == NULL) + swscanf(static_cast(region->name),L"item_%d",&itemId); + if (itemId == -1 || itemId > Item::ITEM_NUM_COUNT || Item::items[itemId] == nullptr) { app.DebugPrintf("This is not the control we are looking for\n"); } else { - shared_ptr item = shared_ptr( new ItemInstance(itemId,1,0) ); - if(item != NULL) customDrawSlotControl(region,m_iPad,item,1.0f,false,false); + const auto item = std::make_shared(itemId, 1, 0); + if(item != nullptr) customDrawSlotControl(region,m_iPad,item,1.0f,false,false); } } @@ -183,7 +183,7 @@ void UIScene_DebugOverlay::handleInput(int iPad, int key, bool repeat, bool pres void UIScene_DebugOverlay::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Items: { @@ -213,14 +213,14 @@ void UIScene_DebugOverlay::handlePress(F64 controlId, F64 childId) case eControl_Schematic: { #ifndef _CONTENT_PACKAGE - ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugCreateSchematic,NULL,eUILayer_Debug); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugCreateSchematic,nullptr,eUILayer_Debug); #endif } break; case eControl_SetCamera: { #ifndef _CONTENT_PACKAGE - ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugSetCamera,NULL,eUILayer_Debug); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugSetCamera,nullptr,eUILayer_Debug); #endif } break; @@ -254,7 +254,7 @@ void UIScene_DebugOverlay::handlePress(F64 controlId, F64 childId) void UIScene_DebugOverlay::handleSliderMove(F64 sliderId, F64 currentValue) { - switch((int)sliderId) + switch(static_cast(sliderId)) { case eControl_Time: { @@ -266,25 +266,25 @@ void UIScene_DebugOverlay::handleSliderMove(F64 sliderId, F64 currentValue) MinecraftServer::SetTime(currentValue * 100); pMinecraft->level->getLevelData()->setGameTime(currentValue * 100); - WCHAR TempString[256]; + WCHAR tempString[256]; float currentTime = currentValue * 100; - swprintf( (WCHAR *)TempString, 256, L"Set time (unsafe) (%d)", (int)currentTime); - m_sliderTime.setLabel(TempString); + swprintf( tempString, 256, L"Set time (unsafe) (%d)", static_cast(currentTime)); + m_sliderTime.setLabel(tempString); } break; case eControl_FOV: { Minecraft *pMinecraft = Minecraft::GetInstance(); - int v = (int)currentValue; + int v = static_cast(currentValue); if (v < 0) v = 0; if (v > 100) v = 100; int fovDeg = 70 + v * 40 / 100; - pMinecraft->gameRenderer->SetFovVal((float)fovDeg); + pMinecraft->gameRenderer->SetFovVal(static_cast(fovDeg)); app.SetGameSettings(m_iPad, eGameSetting_FOV, v); - WCHAR TempString[256]; - swprintf( (WCHAR *)TempString, 256, L"Set fov (%d)", fovDeg); - m_sliderFov.setLabel(TempString); + WCHAR tempString[256]; + swprintf( tempString, 256, L"Set fov (%d)", fovDeg); + m_sliderFov.setLabel(tempString); } break; }; diff --git a/Minecraft.Client/Common/UI/UIScene_DebugSetCamera.cpp b/Minecraft.Client/Common/UI/UIScene_DebugSetCamera.cpp index 62ee60b13..51eab5aa0 100644 --- a/Minecraft.Client/Common/UI/UIScene_DebugSetCamera.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DebugSetCamera.cpp @@ -17,7 +17,7 @@ UIScene_DebugSetCamera::UIScene_DebugSetCamera(int iPad, void *initData, UILayer currentPosition->player = playerNo; Minecraft *pMinecraft = Minecraft::GetInstance(); - if (pMinecraft != NULL) + if (pMinecraft != nullptr) { Vec3 *vec = pMinecraft->localplayers[playerNo]->getPos(1.0); @@ -143,7 +143,7 @@ void UIScene_DebugSetCamera::handlePress(F64 controlId, F64 childId) #ifdef _WINDOWS64 if (isDirectEditBlocking()) return; #endif - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Teleport: app.SetXuiServerAction( ProfileManager.GetPrimaryPad(), @@ -155,7 +155,7 @@ void UIScene_DebugSetCamera::handlePress(F64 controlId, F64 childId) case eControl_CamZ: case eControl_YRot: case eControl_Elevation: - m_keyboardCallbackControl = (eControls)((int)controlId); + m_keyboardCallbackControl = static_cast(static_cast(controlId)); #ifdef _WINDOWS64 if (g_KBMInput.IsKBMActive()) { @@ -173,6 +173,7 @@ void UIScene_DebugSetCamera::handlePress(F64 controlId, F64 childId) ui.NavigateToScene(m_iPad, eUIScene_Keyboard, &kbData, eUILayer_Fullscreen, eUIGroup_Fullscreen); } #else +>>>>>>> origin/main InputManager.RequestKeyboard(L"Enter something",L"",(DWORD)0,25,&UIScene_DebugSetCamera::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Default); #endif break; @@ -181,7 +182,7 @@ void UIScene_DebugSetCamera::handlePress(F64 controlId, F64 childId) void UIScene_DebugSetCamera::handleCheckboxToggled(F64 controlId, bool selected) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_LockPlayer: app.SetFreezePlayers(selected); @@ -191,18 +192,19 @@ void UIScene_DebugSetCamera::handleCheckboxToggled(F64 controlId, bool selected) int UIScene_DebugSetCamera::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) { - UIScene_DebugSetCamera *pClass=(UIScene_DebugSetCamera *)lpParam; + UIScene_DebugSetCamera *pClass=static_cast(lpParam); uint16_t pchText[2048]; ZeroMemory(pchText, 2048 * sizeof(uint16_t)); #ifdef _WINDOWS64 Win64_GetKeyboardText(pchText, 2048); #else +>>>>>>> origin/main InputManager.GetText(pchText); #endif if(pchText[0]!=0) { - wstring value = (wchar_t *)pchText; + wstring value = reinterpret_cast(pchText); double val = 0; if(!value.empty()) val = _fromString( value ); switch(pClass->m_keyboardCallbackControl) diff --git a/Minecraft.Client/Common/UI/UIScene_DispenserMenu.cpp b/Minecraft.Client/Common/UI/UIScene_DispenserMenu.cpp index 97cf842a9..2e47dda43 100644 --- a/Minecraft.Client/Common/UI/UIScene_DispenserMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DispenserMenu.cpp @@ -10,14 +10,14 @@ UIScene_DispenserMenu::UIScene_DispenserMenu(int iPad, void *_initData, UILayer // Setup all the Iggy references we need for this scene initialiseMovie(); - TrapScreenInput *initData = (TrapScreenInput *)_initData; + TrapScreenInput *initData = static_cast(_initData); m_labelDispenser.init(initData->trap->getName()); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Trap_Menu, this); } @@ -156,7 +156,7 @@ void UIScene_DispenserMenu::setSectionSelectedSlot(ESceneSection eSection, int x int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionTrapTrap: @@ -177,7 +177,7 @@ void UIScene_DispenserMenu::setSectionSelectedSlot(ESceneSection eSection, int x UIControl *UIScene_DispenserMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionTrapTrap: diff --git a/Minecraft.Client/Common/UI/UIScene_EULA.cpp b/Minecraft.Client/Common/UI/UIScene_EULA.cpp index 3177344df..411956212 100644 --- a/Minecraft.Client/Common/UI/UIScene_EULA.cpp +++ b/Minecraft.Client/Common/UI/UIScene_EULA.cpp @@ -48,8 +48,8 @@ UIScene_EULA::UIScene_EULA(int iPad, void *initData, UILayer *parentLayer) : UIS #endif vector paragraphs; - int lastIndex = 0; - for ( int index = EULA.find(L"\r\n", lastIndex, 2); + size_t lastIndex = 0; + for ( size_t index = EULA.find(L"\r\n", lastIndex, 2); index != wstring::npos; index = EULA.find(L"\r\n", lastIndex, 2) ) @@ -132,7 +132,7 @@ void UIScene_EULA::handleInput(int iPad, int key, bool repeat, bool pressed, boo void UIScene_EULA::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Confirm: //CD - Added for audio diff --git a/Minecraft.Client/Common/UI/UIScene_EnchantingMenu.cpp b/Minecraft.Client/Common/UI/UIScene_EnchantingMenu.cpp index 27459ccc1..f90c4b12b 100644 --- a/Minecraft.Client/Common/UI/UIScene_EnchantingMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_EnchantingMenu.cpp @@ -14,14 +14,14 @@ UIScene_EnchantingMenu::UIScene_EnchantingMenu(int iPad, void *_initData, UILaye m_enchantButton[1].init(1); m_enchantButton[2].init(2); - EnchantingScreenInput *initData = (EnchantingScreenInput *)_initData; + EnchantingScreenInput *initData = static_cast(_initData); m_labelEnchant.init( initData->name.empty() ? app.GetString(IDS_ENCHANT) : initData->name ); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Enchanting_Menu, this); } @@ -194,7 +194,7 @@ void UIScene_EnchantingMenu::setSectionSelectedSlot(ESceneSection eSection, int int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionEnchantSlot: @@ -216,7 +216,7 @@ void UIScene_EnchantingMenu::setSectionSelectedSlot(ESceneSection eSection, int UIControl *UIScene_EnchantingMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionEnchantSlot: @@ -247,7 +247,7 @@ UIControl *UIScene_EnchantingMenu::getSection(ESceneSection eSection) void UIScene_EnchantingMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; if(wcscmp((wchar_t *)region->name,L"EnchantmentBook")==0) @@ -264,7 +264,7 @@ void UIScene_EnchantingMenu::customDraw(IggyCustomDrawCallbackRegion *region) else { int slotId = -1; - swscanf((wchar_t*)region->name,L"slot_Button%d",&slotId); + swscanf(static_cast(region->name),L"slot_Button%d",&slotId); if(slotId >= 0) { // Setup GDraw, normal game render states and matrices diff --git a/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp b/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp index 2f43cada2..5b10e8cfe 100644 --- a/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp +++ b/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp @@ -50,7 +50,7 @@ UIScene_EndPoem::UIScene_EndPoem(int iPad, void *initData, UILayer *parentLayer) Minecraft *pMinecraft = Minecraft::GetInstance(); wstring playerName = L""; - if(pMinecraft->localplayers[ui.GetWinUserIndex()] != NULL) + if(pMinecraft->localplayers[ui.GetWinUserIndex()] != nullptr) { playerName = escapeXML( pMinecraft->localplayers[ui.GetWinUserIndex()]->getDisplayName() ); } @@ -159,14 +159,14 @@ void UIScene_EndPoem::handleInput(int iPad, int key, bool repeat, bool pressed, Minecraft *pMinecraft = Minecraft::GetInstance(); for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { - if(pMinecraft->localplayers[i] != NULL) + if(pMinecraft->localplayers[i] != nullptr) { app.SetAction(i,eAppAction_Respawn); } } // This just allows it to be shown - if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); + if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); updateTooltips(); navigateBack(); @@ -191,7 +191,7 @@ void UIScene_EndPoem::handleDestroy() void UIScene_EndPoem::handleRequestMoreData(F64 startIndex, bool up) { - m_requestedLabel = (int)startIndex; + m_requestedLabel = static_cast(startIndex); } void UIScene_EndPoem::updateNoise() @@ -221,13 +221,13 @@ void UIScene_EndPoem::updateNoise() { if (ui.UsingBitmapFont()) { - randomChar = SharedConstants::acceptableLetters[random->nextInt((int)SharedConstants::acceptableLetters.length())]; + randomChar = SharedConstants::acceptableLetters[random->nextInt(static_cast(SharedConstants::acceptableLetters.length()))]; } else { // 4J-JEV: It'd be nice to avoid null characters when using asian languages. static wstring acceptableLetters = L"!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_'|}~"; - randomChar = acceptableLetters[ random->nextInt((int)acceptableLetters.length()) ]; + randomChar = acceptableLetters[ random->nextInt(static_cast(acceptableLetters.length())) ]; } wstring randomCharStr = L""; diff --git a/Minecraft.Client/Common/UI/UIScene_FireworksMenu.cpp b/Minecraft.Client/Common/UI/UIScene_FireworksMenu.cpp index 1d24f989b..b33e086a7 100644 --- a/Minecraft.Client/Common/UI/UIScene_FireworksMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_FireworksMenu.cpp @@ -11,14 +11,14 @@ UIScene_FireworksMenu::UIScene_FireworksMenu(int iPad, void *_initData, UILayer // Setup all the Iggy references we need for this scene initialiseMovie(); - FireworksScreenInput *initData = (FireworksScreenInput *)_initData; + FireworksScreenInput *initData = static_cast(_initData); m_labelFireworks.init(app.GetString(IDS_HOW_TO_PLAY_MENU_FIREWORKS)); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Fireworks_Menu, this); } @@ -174,7 +174,7 @@ void UIScene_FireworksMenu::setSectionSelectedSlot(ESceneSection eSection, int x int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionFireworksIngredients: @@ -198,7 +198,7 @@ void UIScene_FireworksMenu::setSectionSelectedSlot(ESceneSection eSection, int x UIControl *UIScene_FireworksMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionFireworksIngredients: diff --git a/Minecraft.Client/Common/UI/UIScene_FullscreenProgress.cpp b/Minecraft.Client/Common/UI/UIScene_FullscreenProgress.cpp index fb17bda44..6a4ea0966 100644 --- a/Minecraft.Client/Common/UI/UIScene_FullscreenProgress.cpp +++ b/Minecraft.Client/Common/UI/UIScene_FullscreenProgress.cpp @@ -4,7 +4,6 @@ #include "..\..\Minecraft.h" #include "..\..\ProgressRenderer.h" - UIScene_FullscreenProgress::UIScene_FullscreenProgress(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { // Setup all the Iggy references we need for this scene @@ -27,7 +26,7 @@ UIScene_FullscreenProgress::UIScene_FullscreenProgress(int iPad, void *initData, m_buttonConfirm.init( app.GetString( IDS_CONFIRM_OK ), eControl_Confirm ); m_buttonConfirm.setVisible(false); - LoadingInputParams *params = (LoadingInputParams *)initData; + LoadingInputParams *params = static_cast(initData); m_CompletionData = params->completionData; m_iPad=params->completionData->iPad; @@ -102,7 +101,7 @@ void UIScene_FullscreenProgress::handleDestroy() DWORD exitcode = *((DWORD *)&code); // If we're active, have a cancel func, and haven't already cancelled, call cancel func - if( exitcode == STILL_ACTIVE && m_cancelFunc != NULL && !m_bWasCancelled) + if( exitcode == STILL_ACTIVE && m_cancelFunc != nullptr && !m_bWasCancelled) { m_bWasCancelled = true; m_cancelFunc(m_cancelFuncParam); @@ -224,7 +223,7 @@ void UIScene_FullscreenProgress::tick() // This just allows it to be shown Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); + if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); ui.UpdatePlayerBasePositions(); navigateBack(); } @@ -279,26 +278,27 @@ void UIScene_FullscreenProgress::handleInput(int iPad, int key, bool repeat, boo #ifdef __ORBIS__ case ACTION_MENU_TOUCHPAD_PRESS: #endif - if(pressed) + if(pressed && m_threadCompleted) { sendInputToMovie(key, repeat, pressed, released); } break; case ACTION_MENU_B: case ACTION_MENU_CANCEL: - if( pressed && m_cancelFunc != NULL && !m_bWasCancelled ) + if( pressed && m_cancelFunc != nullptr && !m_bWasCancelled ) { m_bWasCancelled = true; m_cancelFunc( m_cancelFuncParam ); } break; } + handled = true; } } void UIScene_FullscreenProgress::handlePress(F64 controlId, F64 childId) { - if(m_threadCompleted && (int)controlId == eControl_Confirm) + if(m_threadCompleted && static_cast(controlId) == eControl_Confirm) { // This assumes all buttons can only be pressed with the A button ui.AnimateKeyPress(m_iPad, ACTION_MENU_A, false, true, false); diff --git a/Minecraft.Client/Common/UI/UIScene_FurnaceMenu.cpp b/Minecraft.Client/Common/UI/UIScene_FurnaceMenu.cpp index 392221a6f..9dcbe45b4 100644 --- a/Minecraft.Client/Common/UI/UIScene_FurnaceMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_FurnaceMenu.cpp @@ -10,7 +10,7 @@ UIScene_FurnaceMenu::UIScene_FurnaceMenu(int iPad, void *_initData, UILayer *par // Setup all the Iggy references we need for this scene initialiseMovie(); - FurnaceScreenInput *initData = (FurnaceScreenInput *)_initData; + FurnaceScreenInput *initData = static_cast(_initData); m_furnace = initData->furnace; m_labelFurnace.init(m_furnace->getName()); @@ -21,9 +21,9 @@ UIScene_FurnaceMenu::UIScene_FurnaceMenu(int iPad, void *_initData, UILayer *par m_progressFurnaceArrow.init(L"",0,0,24,0); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Furnace_Menu, this); } @@ -202,7 +202,7 @@ void UIScene_FurnaceMenu::setSectionSelectedSlot(ESceneSection eSection, int x, int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionFurnaceResult: @@ -230,7 +230,7 @@ void UIScene_FurnaceMenu::setSectionSelectedSlot(ESceneSection eSection, int x, UIControl *UIScene_FurnaceMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionFurnaceResult: diff --git a/Minecraft.Client/Common/UI/UIScene_HUD.cpp b/Minecraft.Client/Common/UI/UIScene_HUD.cpp index 5f401c39d..213caa8dc 100644 --- a/Minecraft.Client/Common/UI/UIScene_HUD.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HUD.cpp @@ -1,877 +1,886 @@ -#include "stdafx.h" -#include "UI.h" -#include "UIScene_HUD.h" -#include "BossMobGuiInfo.h" -#include "..\..\Minecraft.h" -#include "..\..\MultiplayerLocalPlayer.h" -#include "..\..\..\Minecraft.World\net.minecraft.world.entity.boss.enderdragon.h" -#include "..\..\EnderDragonRenderer.h" -#include "..\..\..\Minecraft.World\net.minecraft.world.inventory.h" -#include "..\..\..\Minecraft.World\StringHelpers.h" - -UIScene_HUD::UIScene_HUD(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) -{ - m_bSplitscreen = false; - - // Setup all the Iggy references we need for this scene - initialiseMovie(); - - SetDragonLabel( app.GetString( IDS_BOSS_ENDERDRAGON_HEALTH ) ); - SetSelectedLabel(L""); - - for(unsigned int i = 0; i < CHAT_LINES_COUNT; ++i) - { - m_labelChatText[i].init(L""); - } - m_labelJukebox.init(L""); - - addTimer(0, 100); -} - -wstring UIScene_HUD::getMoviePath() -{ - switch( m_parentLayer->getViewport() ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - m_bSplitscreen = true; - return L"HUDSplit"; - break; - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - default: - m_bSplitscreen = false; - return L"HUD"; - break; - } -} - -void UIScene_HUD::updateSafeZone() -{ - // Distance from edge - F64 safeTop = 0.0; - F64 safeBottom = 0.0; - F64 safeLeft = 0.0; - F64 safeRight = 0.0; - - switch( m_parentLayer->getViewport() ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - safeTop = getSafeZoneHalfHeight(); - safeLeft = getSafeZoneHalfWidth(); - safeRight = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - safeBottom = getSafeZoneHalfHeight(); - safeLeft = getSafeZoneHalfWidth(); - safeRight = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - safeLeft = getSafeZoneHalfWidth(); - safeTop = getSafeZoneHalfHeight(); - safeBottom = getSafeZoneHalfHeight(); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - safeRight = getSafeZoneHalfWidth(); - safeTop = getSafeZoneHalfHeight(); - safeBottom = getSafeZoneHalfHeight(); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - safeTop = getSafeZoneHalfHeight(); - safeLeft = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - safeTop = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - safeBottom = getSafeZoneHalfHeight(); - safeLeft = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - safeBottom = getSafeZoneHalfHeight(); - safeRight = getSafeZoneHalfWidth(); - break; - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - default: - safeTop = getSafeZoneHalfHeight(); - safeBottom = getSafeZoneHalfHeight(); - safeLeft = getSafeZoneHalfWidth(); - safeRight = getSafeZoneHalfWidth(); - break; - } - setSafeZone(safeTop, safeBottom, safeLeft, safeRight); -} - -void UIScene_HUD::tick() -{ - UIScene::tick(); - if(getMovie() && app.GetGameStarted()) - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) - { - return; - } - - // Is boss present? - bool noBoss = BossMobGuiInfo::name.empty() || BossMobGuiInfo::displayTicks <= 0; - if (noBoss) - { - if (m_showDragonHealth) - { - // No boss and health is visible - if(m_ticksWithNoBoss <= 20) - { - ++m_ticksWithNoBoss; - } - else - { - ShowDragonHealth(false); - } - } - } - else - { - BossMobGuiInfo::displayTicks--; - - m_ticksWithNoBoss = 0; - SetDragonHealth(BossMobGuiInfo::healthProgress); - - if (!m_showDragonHealth) - { - SetDragonLabel(BossMobGuiInfo::name); - ShowDragonHealth(true); - } - } - } -} - -void UIScene_HUD::customDraw(IggyCustomDrawCallbackRegion *region) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; - - int slot = -1; - swscanf((wchar_t*)region->name,L"slot_%d",&slot); - if (slot == -1) - { - app.DebugPrintf("This is not the control we are looking for\n"); - } - else - { - Slot *invSlot = pMinecraft->localplayers[m_iPad]->inventoryMenu->getSlot(InventoryMenu::USE_ROW_SLOT_START + slot); - shared_ptr item = invSlot->getItem(); - if(item != NULL) - { - unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); - float fVal; - - if(ucAlpha<80) - { - // check if we have the timer running for the opacity - unsigned int uiOpacityTimer=app.GetOpacityTimer(m_iPad); - if(uiOpacityTimer!=0) - { - if(uiOpacityTimer<10) - { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); - } - else - { - fVal=0.01f*80.0f; - } - } - else - { - fVal=0.01f*(float)ucAlpha; - } - } - else - { - fVal=0.01f*(float)ucAlpha; - } - customDrawSlotControl(region,m_iPad,item,fVal,item->isFoil(),true); - } - } -} - -void UIScene_HUD::handleReload() -{ - m_lastActiveSlot = -1; - m_iGuiScale = -1; - m_bToolTipsVisible = true; - m_lastExpProgress = 0.0f; - m_lastExpLevel = 0; - m_iCurrentHealth = 0; - m_lastMaxHealth = 20; - m_lastHealthBlink = false; - m_lastHealthPoison = false; - m_iCurrentFood = -1; - m_lastFoodPoison = false; - m_lastAir = 10; - m_currentExtraAir = 0; - m_lastArmour = 0; - m_showHealth = true; - m_showHorseHealth = true; - m_showFood = true; - m_showAir = false; // get's initialised invisible anyways, by setting it to false we ensure it will remain visible when switching in and out of split screen! - m_showArmour = true; - m_showExpBar = true; - m_bRegenEffectEnabled = false; - m_iFoodSaturation = 0; - m_lastDragonHealth = 0.0f; - m_showDragonHealth = false; - m_ticksWithNoBoss = 0; - m_uiSelectedItemOpacityCountDown = 0; - m_displayName = L""; - m_lastShowDisplayName = true; - m_bRidingHorse = true; - m_horseHealth = 1; - m_lastHealthWither = true; - m_iCurrentHealthAbsorb = -1; - m_horseJumpProgress = 1.0f; - m_iHeartOffsetIndex = -1; - m_bHealthAbsorbActive = false; - m_iHorseMaxHealth = -1; - - m_labelDisplayName.setVisible(m_lastShowDisplayName); - - SetDragonLabel(BossMobGuiInfo::name); - SetSelectedLabel(L""); - - for(unsigned int i = 0; i < CHAT_LINES_COUNT; ++i) - { - m_labelChatText[i].init(L""); - } - m_labelJukebox.init(L""); - - int iGuiScale; - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localplayers[m_iPad]->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN) - { - iGuiScale=app.GetGameSettings(m_iPad,eGameSetting_UISize); - } - else - { - iGuiScale=app.GetGameSettings(m_iPad,eGameSetting_UISizeSplitscreen); - } - SetHudSize(iGuiScale); - - SetDisplayName(ProfileManager.GetDisplayName(m_iPad)); - - repositionHud(); - - SetTooltipsEnabled(((ui.GetMenuDisplayed(ProfileManager.GetPrimaryPad())) || (app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Tooltips) != 0))); -} - -int UIScene_HUD::getPad() -{ - return m_iPad; -} - -void UIScene_HUD::SetOpacity(float opacity) -{ - setOpacity(opacity); -} - -void UIScene_HUD::SetVisible(bool visible) -{ - setVisible(visible); -} - -void UIScene_HUD::SetHudSize(int scale) -{ - if(scale != m_iGuiScale) - { - m_iGuiScale = scale; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = scale; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcLoadHud , 1 , value ); - } -} - -void UIScene_HUD::SetExpBarProgress(float progress, int xpNeededForNextLevel) -{ - if(progress != m_lastExpProgress) - { - m_lastExpProgress = progress; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = progress; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetExpBarProgress , 1 , value ); - } -} - -void UIScene_HUD::SetExpLevel(int level) -{ - if(level != m_lastExpLevel) - { - m_lastExpLevel = level; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = level; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetPlayerLevel , 1 , value ); - } -} - -void UIScene_HUD::SetActiveSlot(int slot) -{ - if(slot != m_lastActiveSlot) - { - m_lastActiveSlot = slot; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = slot; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetActiveSlot , 1 , value ); - } -} - -void UIScene_HUD::SetHealth(int iHealth, int iLastHealth, bool bBlink, bool bPoison, bool bWither) -{ - int maxHealth = max(iHealth, iLastHealth); - if(maxHealth != m_lastMaxHealth || bBlink != m_lastHealthBlink || bPoison != m_lastHealthPoison || bWither != m_lastHealthWither) - { - m_lastMaxHealth = maxHealth; - m_lastHealthBlink = bBlink; - m_lastHealthPoison = bPoison; - m_lastHealthWither = bWither; - - IggyDataValue result; - IggyDataValue value[4]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = maxHealth; - value[1].type = IGGY_DATATYPE_boolean; - value[1].boolval = bBlink; - value[2].type = IGGY_DATATYPE_boolean; - value[2].boolval = bPoison; - value[3].type = IGGY_DATATYPE_boolean; - value[3].boolval = bWither; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHealth , 4 , value ); - } -} - -void UIScene_HUD::SetFood(int iFood, int iLastFood, bool bPoison) -{ - // Ignore iLastFood as food doesn't flash - int maxFood = iFood; //, iLastFood); - if(maxFood != m_iCurrentFood || bPoison != m_lastFoodPoison) - { - m_iCurrentFood = maxFood; - m_lastFoodPoison = bPoison; - - IggyDataValue result; - IggyDataValue value[2]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = maxFood; - value[1].type = IGGY_DATATYPE_boolean; - value[1].boolval = bPoison; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetFood , 2 , value ); - } -} - -void UIScene_HUD::SetAir(int iAir, int extra) -{ - if(iAir != m_lastAir) - { - app.DebugPrintf("SetAir to %d\n", iAir); - m_lastAir = iAir; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = iAir; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetAir , 1 , value ); - } -} - -void UIScene_HUD::SetArmour(int iArmour) -{ - if(iArmour != m_lastArmour) - { - app.DebugPrintf("SetArmour to %d\n", iArmour); - m_lastArmour = iArmour; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = iArmour; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetArmour , 1 , value ); - } -} - -void UIScene_HUD::ShowHealth(bool show) -{ - if(show != m_showHealth) - { - app.DebugPrintf("ShowHealth to %s\n", show?"TRUE":"FALSE"); - m_showHealth = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowHealth , 1 , value ); - } -} - -void UIScene_HUD::ShowHorseHealth(bool show) -{ - if(show != m_showHorseHealth) - { - app.DebugPrintf("ShowHorseHealth to %s\n", show?"TRUE":"FALSE"); - m_showHorseHealth = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowHorseHealth , 1 , value ); - } -} - -void UIScene_HUD::ShowFood(bool show) -{ - if(show != m_showFood) - { - app.DebugPrintf("ShowFood to %s\n", show?"TRUE":"FALSE"); - m_showFood = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowFood , 1 , value ); - } -} - -void UIScene_HUD::ShowAir(bool show) -{ - if(show != m_showAir) - { - app.DebugPrintf("ShowAir to %s\n", show?"TRUE":"FALSE"); - m_showAir = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowAir , 1 , value ); - } -} - -void UIScene_HUD::ShowArmour(bool show) -{ - if(show != m_showArmour) - { - app.DebugPrintf("ShowArmour to %s\n", show?"TRUE":"FALSE"); - m_showArmour = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowArmour , 1 , value ); - } -} - -void UIScene_HUD::ShowExpBar(bool show) -{ - if(show != m_showExpBar) - { - app.DebugPrintf("ShowExpBar to %s\n", show?"TRUE":"FALSE"); - m_showExpBar = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowExpbar , 1 , value ); - } -} - -void UIScene_HUD::SetRegenerationEffect(bool bEnabled) -{ - if(bEnabled != m_bRegenEffectEnabled) - { - app.DebugPrintf("SetRegenerationEffect to %s\n", bEnabled?"TRUE":"FALSE"); - m_bRegenEffectEnabled = bEnabled; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = bEnabled; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetRegenerationEffect , 1 , value ); - } -} - -void UIScene_HUD::SetFoodSaturationLevel(int iSaturation) -{ - if(iSaturation != m_iFoodSaturation) - { - app.DebugPrintf("Set saturation to %d\n", iSaturation); - m_iFoodSaturation = iSaturation; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = iSaturation; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetFoodSaturationLevel , 1 , value ); - } -} - -void UIScene_HUD::SetDragonHealth(float health) -{ - if(health != m_lastDragonHealth) - { - app.DebugPrintf("Set dragon health to %f\n", health); - m_lastDragonHealth = health; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = health; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDragonHealth , 1 , value ); - } -} - -void UIScene_HUD::SetDragonLabel(const wstring &label) -{ - IggyDataValue result; - IggyDataValue value[1]; - IggyStringUTF16 stringVal; - stringVal.string = (IggyUTF16*)label.c_str(); - stringVal.length = label.length(); - value[0].type = IGGY_DATATYPE_string_UTF16; - value[0].string16 = stringVal; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDragonLabel , 1 , value ); -} - -void UIScene_HUD::ShowDragonHealth(bool show) -{ - if(show != m_showDragonHealth) - { - app.DebugPrintf("ShowDragonHealth to %s\n", show?"TRUE":"FALSE"); - m_showDragonHealth = show; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = show; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowDragonHealth , 1 , value ); - } -} - -void UIScene_HUD::SetSelectedLabel(const wstring &label) -{ - // 4J Stu - Timing here is kept the same as on Xbox360, even though we do it differently now and do the fade out in Flash rather than directly setting opacity - if(!label.empty()) m_uiSelectedItemOpacityCountDown = SharedConstants::TICKS_PER_SECOND * 3; - - IggyDataValue result; - IggyDataValue value[1]; - IggyStringUTF16 stringVal; - stringVal.string = (IggyUTF16*)label.c_str(); - stringVal.length = label.length(); - value[0].type = IGGY_DATATYPE_string_UTF16; - value[0].string16 = stringVal; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetSelectedLabel , 1 , value ); -} - -void UIScene_HUD::HideSelectedLabel() -{ - IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcHideSelectedLabel , 0 , NULL ); -} - - -void UIScene_HUD::SetRidingHorse(bool ridingHorse, bool bIsJumpable, int maxHorseHealth) -{ - if(m_bRidingHorse != ridingHorse || maxHorseHealth != m_iHorseMaxHealth) - { - app.DebugPrintf("SetRidingHorse to %s\n", ridingHorse?"TRUE":"FALSE"); - m_bRidingHorse = ridingHorse; - m_bIsJumpable = bIsJumpable; - m_iHorseMaxHealth = maxHorseHealth; - - IggyDataValue result; - IggyDataValue value[3]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = ridingHorse; - value[1].type = IGGY_DATATYPE_boolean; - value[1].boolval = bIsJumpable; - value[2].type = IGGY_DATATYPE_number; - value[2].number = maxHorseHealth; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetRidingHorse , 3 , value ); - } -} - -void UIScene_HUD::SetHorseHealth(int health, bool blink /*= false*/) -{ - if(m_bRidingHorse && m_horseHealth != health) - { - app.DebugPrintf("SetHorseHealth to %d\n", health); - m_horseHealth = health; - - IggyDataValue result; - IggyDataValue value[2]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = health; - value[1].type = IGGY_DATATYPE_boolean; - value[1].boolval = blink; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHorseHealth , 2 , value ); - } -} - -void UIScene_HUD::SetHorseJumpBarProgress(float progress) -{ - if(m_bRidingHorse && m_horseJumpProgress != progress) - { - app.DebugPrintf("SetHorseJumpBarProgress to %f\n", progress); - m_horseJumpProgress = progress; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = progress; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHorseJumpBarProgress , 1 , value ); - } -} - -void UIScene_HUD::SetHealthAbsorb(int healthAbsorb) -{ - if(m_iCurrentHealthAbsorb != healthAbsorb) - { - app.DebugPrintf("SetHealthAbsorb to %d\n", healthAbsorb); - m_iCurrentHealthAbsorb = healthAbsorb; - - IggyDataValue result; - IggyDataValue value[2]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = healthAbsorb > 0; - value[1].type = IGGY_DATATYPE_number; - value[1].number = healthAbsorb; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHealthAbsorb , 2 , value ); - } -} - -void UIScene_HUD::render(S32 width, S32 height, C4JRender::eViewportType viewport) -{ - if(m_bSplitscreen) - { - S32 xPos = 0; - S32 yPos = 0; - switch( viewport ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - yPos = (S32)(ui.getScreenHeight() / 2); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xPos = (S32)(ui.getScreenWidth() / 2); - yPos = (S32)(ui.getScreenHeight() / 2); - break; - } - ui.setupRenderPosition(xPos, yPos); - - S32 tileXStart = 0; - S32 tileYStart = 0; - S32 tileWidth = width; - S32 tileHeight = height; - - switch( viewport ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - tileHeight = (S32)(ui.getScreenHeight()); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - tileWidth = (S32)(ui.getScreenWidth()); - tileYStart = (S32)(m_movieHeight / 2); - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - tileYStart = (S32)(m_movieHeight / 2); - break; - } - - IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); - - m_renderWidth = tileWidth; - m_renderHeight = tileHeight; - - IggyPlayerDrawTilesStart ( getMovie() ); - IggyPlayerDrawTile ( getMovie() , - tileXStart , - tileYStart , - tileXStart + tileWidth , - tileYStart + tileHeight , - 0 ); - IggyPlayerDrawTilesEnd ( getMovie() ); - } - else - { - UIScene::render(width, height, viewport); - } -} - -void UIScene_HUD::handleTimerComplete(int id) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - - bool anyVisible = false; - if(pMinecraft->localplayers[m_iPad]!= NULL) - { - Gui *pGui = pMinecraft->gui; - //DWORD messagesToDisplay = min( CHAT_LINES_COUNT, pGui->getMessagesCount(m_iPad) ); - for( unsigned int i = 0; i < CHAT_LINES_COUNT; ++i ) - { - float opacity = pGui->getOpacity(m_iPad, i); - if( opacity > 0 ) - { -#if 0 // def _WINDOWS64 // Use Iggy chat until Gui::render has visual parity - // Chat drawn by Gui::render with color codes. Hides Iggy chat to avoid double chats. - m_controlLabelBackground[i].setOpacity(0); - m_labelChatText[i].setOpacity(0); - m_labelChatText[i].setLabel(L""); -#else - m_controlLabelBackground[i].setOpacity(opacity); - m_labelChatText[i].setOpacity(opacity); - m_labelChatText[i].setLabel( pGui->getMessagesCount(m_iPad) ? pGui->getMessage(m_iPad,i) : L"" ); -#endif - anyVisible = true; - } - else - { - m_controlLabelBackground[i].setOpacity(0); - m_labelChatText[i].setOpacity(0); - m_labelChatText[i].setLabel(L""); - } - } - if(pGui->getJukeboxOpacity(m_iPad) > 0) anyVisible = true; - m_labelJukebox.setOpacity( pGui->getJukeboxOpacity(m_iPad) ); - m_labelJukebox.setLabel( pGui->getJukeboxMessage(m_iPad) ); - } - else - { - for( unsigned int i = 0; i < CHAT_LINES_COUNT; ++i ) - { - m_controlLabelBackground[i].setOpacity(0); - m_labelChatText[i].setOpacity(0); - m_labelChatText[i].setLabel(L""); - } - m_labelJukebox.setOpacity( 0 ); - } - - //setVisible(anyVisible); -} - -void UIScene_HUD::repositionHud() -{ - if(!m_bSplitscreen) return; - - S32 width = 0; - S32 height = 0; - m_parentLayer->getRenderDimensions( width, height ); - - switch( m_parentLayer->getViewport() ) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - height = (S32)(ui.getScreenHeight()); - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - width = (S32)(ui.getScreenWidth()); - break; - } - - app.DebugPrintf(app.USER_SR, "Reposition HUD with dims %d, %d\n", width, height ); - - IggyDataValue result; - IggyDataValue value[2]; - value[0].type = IGGY_DATATYPE_number; - value[0].number = width; - value[1].type = IGGY_DATATYPE_number; - value[1].number = height; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcRepositionHud , 2 , value ); -} - -void UIScene_HUD::ShowDisplayName(bool show) -{ - m_lastShowDisplayName = show; - m_labelDisplayName.setVisible(show); -} - -void UIScene_HUD::SetDisplayName(const wstring &displayName) -{ - if(displayName.compare(m_displayName) != 0) - { - m_displayName = displayName; - - IggyDataValue result; - IggyDataValue value[1]; - IggyStringUTF16 stringVal; - stringVal.string = (IggyUTF16*)displayName.c_str(); - stringVal.length = displayName.length(); - value[0].type = IGGY_DATATYPE_string_UTF16; - value[0].string16 = stringVal; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDisplayName , 1 , value ); - - m_labelDisplayName.setVisible(m_lastShowDisplayName); - } -} - -void UIScene_HUD::SetTooltipsEnabled(bool bEnabled) -{ - if(m_bToolTipsVisible != bEnabled) - { - m_bToolTipsVisible = bEnabled; - - IggyDataValue result; - IggyDataValue value[1]; - value[0].type = IGGY_DATATYPE_boolean; - value[0].boolval = bEnabled; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetTooltipsEnabled , 1 , value ); - } -} - -void UIScene_HUD::handleGameTick() -{ - if(getMovie() && app.GetGameStarted()) - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) - { - m_parentLayer->showComponent(m_iPad, eUIScene_HUD,false); - return; - } - m_parentLayer->showComponent(m_iPad, eUIScene_HUD,true); - - updateFrameTick(); - } +#include "stdafx.h" +#include "UI.h" +#include "UIScene_HUD.h" +#include "UISplitScreenHelpers.h" +#include "BossMobGuiInfo.h" +#include "..\..\Minecraft.h" +#include "..\..\MultiplayerLocalPlayer.h" +#include "..\..\..\Minecraft.World\net.minecraft.world.entity.boss.enderdragon.h" +#include "..\..\EnderDragonRenderer.h" +#include "..\..\..\Minecraft.World\net.minecraft.world.inventory.h" +#include "..\..\..\Minecraft.World\StringHelpers.h" + +UIScene_HUD::UIScene_HUD(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) +{ + m_bSplitscreen = false; + + // Setup all the Iggy references we need for this scene + initialiseMovie(); + + SetDragonLabel( app.GetString( IDS_BOSS_ENDERDRAGON_HEALTH ) ); + SetSelectedLabel(L""); + + for(unsigned int i = 0; i < CHAT_LINES_COUNT; ++i) + { + m_labelChatText[i].init(L""); + } + m_labelJukebox.init(L""); + + addTimer(0, 100); +} + +wstring UIScene_HUD::getMoviePath() +{ + switch( m_parentLayer->getViewport() ) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + m_bSplitscreen = true; + return L"HUDSplit"; + break; + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + default: + m_bSplitscreen = false; + return L"HUD"; + break; + } +} + +void UIScene_HUD::updateSafeZone() +{ + // Distance from edge + F64 safeTop = 0.0; + F64 safeBottom = 0.0; + F64 safeLeft = 0.0; + F64 safeRight = 0.0; + + switch( m_parentLayer->getViewport() ) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + // safeTop mirrors SPLIT_TOP so both players have the same vertical inset + // from their viewport's top edge (split divider), keeping GUI symmetrical. + // safeBottom is intentionally omitted: it would shift m_Hud.y upward in + // ActionScript, placing the hotbar too high relative to SPLIT_TOP. + safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + safeTop = getSafeZoneHalfHeight(); + safeBottom = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + safeTop = getSafeZoneHalfHeight(); + safeBottom = getSafeZoneHalfHeight(); + + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + safeTop = getSafeZoneHalfHeight(); + + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + safeTop = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + safeTop = getSafeZoneHalfHeight(); + + break; + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + default: + safeTop = getSafeZoneHalfHeight(); + safeBottom = getSafeZoneHalfHeight(); + safeLeft = getSafeZoneHalfWidth(); + + break; + } + setSafeZone(safeTop, safeBottom, safeLeft, safeRight); +} + +void UIScene_HUD::tick() +{ + UIScene::tick(); + if(getMovie() && app.GetGameStarted()) + { + Minecraft *pMinecraft = Minecraft::GetInstance(); + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) + { + return; + } + + // Is boss present? + bool noBoss = BossMobGuiInfo::name.empty() || BossMobGuiInfo::displayTicks <= 0; + if (noBoss) + { + if (m_showDragonHealth) + { + // No boss and health is visible + if(m_ticksWithNoBoss <= 20) + { + ++m_ticksWithNoBoss; + } + else + { + ShowDragonHealth(false); + } + } + } + else + { + BossMobGuiInfo::displayTicks--; + + m_ticksWithNoBoss = 0; + SetDragonHealth(BossMobGuiInfo::healthProgress); + + if (!m_showDragonHealth) + { + SetDragonLabel(BossMobGuiInfo::name); + ShowDragonHealth(true); + } + } + } +} + +void UIScene_HUD::customDraw(IggyCustomDrawCallbackRegion *region) +{ + Minecraft *pMinecraft = Minecraft::GetInstance(); + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; + + int slot = -1; + swscanf(static_cast(region->name),L"slot_%d",&slot); + if (slot == -1) + { + app.DebugPrintf("This is not the control we are looking for\n"); + } + else + { + Slot *invSlot = pMinecraft->localplayers[m_iPad]->inventoryMenu->getSlot(InventoryMenu::USE_ROW_SLOT_START + slot); + shared_ptr item = invSlot->getItem(); + if(item != nullptr) + { + unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); + float fVal; + + if(ucAlpha<80) + { + // check if we have the timer running for the opacity + unsigned int uiOpacityTimer=app.GetOpacityTimer(m_iPad); + if(uiOpacityTimer!=0) + { + if(uiOpacityTimer<10) + { + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); + } + else + { + fVal=0.01f*80.0f; + } + } + else + { + fVal=0.01f*static_cast(ucAlpha); + } + } + else + { + fVal=0.01f*static_cast(ucAlpha); + } + customDrawSlotControl(region,m_iPad,item,fVal,item->isFoil(),true); + } + } +} + +void UIScene_HUD::handleReload() +{ + m_lastActiveSlot = -1; + m_iGuiScale = -1; + m_bToolTipsVisible = true; + m_lastExpProgress = 0.0f; + m_lastExpLevel = 0; + m_iCurrentHealth = 0; + m_lastMaxHealth = 20; + m_lastHealthBlink = false; + m_lastHealthPoison = false; + m_iCurrentFood = -1; + m_lastFoodPoison = false; + m_lastAir = 10; + m_currentExtraAir = 0; + m_lastArmour = 0; + m_showHealth = true; + m_showHorseHealth = true; + m_showFood = true; + m_showAir = false; // get's initialised invisible anyways, by setting it to false we ensure it will remain visible when switching in and out of split screen! + m_showArmour = true; + m_showExpBar = true; + m_bRegenEffectEnabled = false; + m_iFoodSaturation = 0; + m_lastDragonHealth = 0.0f; + m_showDragonHealth = false; + m_ticksWithNoBoss = 0; + m_uiSelectedItemOpacityCountDown = 0; + m_displayName = L""; + m_lastShowDisplayName = true; + m_bRidingHorse = true; + m_horseHealth = 1; + m_lastHealthWither = true; + m_iCurrentHealthAbsorb = -1; + m_horseJumpProgress = 1.0f; + m_iHeartOffsetIndex = -1; + m_bHealthAbsorbActive = false; + m_iHorseMaxHealth = -1; + + m_labelDisplayName.setVisible(m_lastShowDisplayName); + + SetDragonLabel(BossMobGuiInfo::name); + SetSelectedLabel(L""); + + for(unsigned int i = 0; i < CHAT_LINES_COUNT; ++i) + { + m_labelChatText[i].init(L""); + } + m_labelJukebox.init(L""); + + int iGuiScale; + Minecraft *pMinecraft = Minecraft::GetInstance(); + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localplayers[m_iPad]->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN) + { + iGuiScale=app.GetGameSettings(m_iPad,eGameSetting_UISize); + } + else + { + iGuiScale=app.GetGameSettings(m_iPad,eGameSetting_UISizeSplitscreen); + } + SetHudSize(iGuiScale); + + SetDisplayName(ProfileManager.GetDisplayName(m_iPad)); + + SetTooltipsEnabled(((ui.GetMenuDisplayed(ProfileManager.GetPrimaryPad())) || (app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Tooltips) != 0))); +} + +int UIScene_HUD::getPad() +{ + return m_iPad; +} + +void UIScene_HUD::SetOpacity(float opacity) +{ + setOpacity(opacity); +} + +void UIScene_HUD::SetVisible(bool visible) +{ + setVisible(visible); +} + +void UIScene_HUD::SetHudSize(int scale) +{ + if(scale != m_iGuiScale) + { + m_iGuiScale = scale; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = scale; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcLoadHud , 1 , value ); + } +} + +void UIScene_HUD::SetExpBarProgress(float progress, int xpNeededForNextLevel) +{ + if(progress != m_lastExpProgress) + { + m_lastExpProgress = progress; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = progress; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetExpBarProgress , 1 , value ); + } +} + +void UIScene_HUD::SetExpLevel(int level) +{ + if(level != m_lastExpLevel) + { + m_lastExpLevel = level; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = level; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetPlayerLevel , 1 , value ); + } +} + +void UIScene_HUD::SetActiveSlot(int slot) +{ + if(slot != m_lastActiveSlot) + { + m_lastActiveSlot = slot; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = slot; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetActiveSlot , 1 , value ); + } +} + +void UIScene_HUD::SetHealth(int iHealth, int iLastHealth, bool bBlink, bool bPoison, bool bWither) +{ + int maxHealth = max(iHealth, iLastHealth); + if(maxHealth != m_lastMaxHealth || bBlink != m_lastHealthBlink || bPoison != m_lastHealthPoison || bWither != m_lastHealthWither) + { + m_lastMaxHealth = maxHealth; + m_lastHealthBlink = bBlink; + m_lastHealthPoison = bPoison; + m_lastHealthWither = bWither; + + IggyDataValue result; + IggyDataValue value[4]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = maxHealth; + value[1].type = IGGY_DATATYPE_boolean; + value[1].boolval = bBlink; + value[2].type = IGGY_DATATYPE_boolean; + value[2].boolval = bPoison; + value[3].type = IGGY_DATATYPE_boolean; + value[3].boolval = bWither; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHealth , 4 , value ); + } +} + +void UIScene_HUD::SetFood(int iFood, int iLastFood, bool bPoison) +{ + // Ignore iLastFood as food doesn't flash + int maxFood = iFood; //, iLastFood); + if(maxFood != m_iCurrentFood || bPoison != m_lastFoodPoison) + { + m_iCurrentFood = maxFood; + m_lastFoodPoison = bPoison; + + IggyDataValue result; + IggyDataValue value[2]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = maxFood; + value[1].type = IGGY_DATATYPE_boolean; + value[1].boolval = bPoison; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetFood , 2 , value ); + } +} + +void UIScene_HUD::SetAir(int iAir, int extra) +{ + if(iAir != m_lastAir) + { + app.DebugPrintf("SetAir to %d\n", iAir); + m_lastAir = iAir; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = iAir; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetAir , 1 , value ); + } +} + +void UIScene_HUD::SetArmour(int iArmour) +{ + if(iArmour != m_lastArmour) + { + app.DebugPrintf("SetArmour to %d\n", iArmour); + m_lastArmour = iArmour; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = iArmour; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetArmour , 1 , value ); + } +} + +void UIScene_HUD::ShowHealth(bool show) +{ + if(show != m_showHealth) + { + app.DebugPrintf("ShowHealth to %s\n", show?"TRUE":"FALSE"); + m_showHealth = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowHealth , 1 , value ); + } +} + +void UIScene_HUD::ShowHorseHealth(bool show) +{ + if(show != m_showHorseHealth) + { + app.DebugPrintf("ShowHorseHealth to %s\n", show?"TRUE":"FALSE"); + m_showHorseHealth = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowHorseHealth , 1 , value ); + } +} + +void UIScene_HUD::ShowFood(bool show) +{ + if(show != m_showFood) + { + app.DebugPrintf("ShowFood to %s\n", show?"TRUE":"FALSE"); + m_showFood = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowFood , 1 , value ); + } +} + +void UIScene_HUD::ShowAir(bool show) +{ + if(show != m_showAir) + { + app.DebugPrintf("ShowAir to %s\n", show?"TRUE":"FALSE"); + m_showAir = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowAir , 1 , value ); + } +} + +void UIScene_HUD::ShowArmour(bool show) +{ + if(show != m_showArmour) + { + app.DebugPrintf("ShowArmour to %s\n", show?"TRUE":"FALSE"); + m_showArmour = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowArmour , 1 , value ); + } +} + +void UIScene_HUD::ShowExpBar(bool show) +{ + if(show != m_showExpBar) + { + app.DebugPrintf("ShowExpBar to %s\n", show?"TRUE":"FALSE"); + m_showExpBar = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowExpbar , 1 , value ); + } +} + +void UIScene_HUD::SetRegenerationEffect(bool bEnabled) +{ + if(bEnabled != m_bRegenEffectEnabled) + { + app.DebugPrintf("SetRegenerationEffect to %s\n", bEnabled?"TRUE":"FALSE"); + m_bRegenEffectEnabled = bEnabled; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = bEnabled; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetRegenerationEffect , 1 , value ); + } +} + +void UIScene_HUD::SetFoodSaturationLevel(int iSaturation) +{ + if(iSaturation != m_iFoodSaturation) + { + app.DebugPrintf("Set saturation to %d\n", iSaturation); + m_iFoodSaturation = iSaturation; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = iSaturation; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetFoodSaturationLevel , 1 , value ); + } +} + +void UIScene_HUD::SetDragonHealth(float health) +{ + if(health != m_lastDragonHealth) + { + app.DebugPrintf("Set dragon health to %f\n", health); + m_lastDragonHealth = health; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = health; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDragonHealth , 1 , value ); + } +} + +void UIScene_HUD::SetDragonLabel(const wstring &label) +{ + IggyDataValue result; + IggyDataValue value[1]; + IggyStringUTF16 stringVal; + stringVal.string = (IggyUTF16*)label.c_str(); + stringVal.length = label.length(); + value[0].type = IGGY_DATATYPE_string_UTF16; + value[0].string16 = stringVal; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDragonLabel , 1 , value ); +} + +void UIScene_HUD::ShowDragonHealth(bool show) +{ + if(show != m_showDragonHealth) + { + app.DebugPrintf("ShowDragonHealth to %s\n", show?"TRUE":"FALSE"); + m_showDragonHealth = show; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = show; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcShowDragonHealth , 1 , value ); + } +} + +void UIScene_HUD::SetSelectedLabel(const wstring &label) +{ + // 4J Stu - Timing here is kept the same as on Xbox360, even though we do it differently now and do the fade out in Flash rather than directly setting opacity + if(!label.empty()) m_uiSelectedItemOpacityCountDown = SharedConstants::TICKS_PER_SECOND * 3; + + IggyDataValue result; + IggyDataValue value[1]; + IggyStringUTF16 stringVal; + stringVal.string = (IggyUTF16*)label.c_str(); + stringVal.length = label.length(); + value[0].type = IGGY_DATATYPE_string_UTF16; + value[0].string16 = stringVal; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetSelectedLabel , 1 , value ); +} + +void UIScene_HUD::HideSelectedLabel() +{ + IggyDataValue result; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcHideSelectedLabel , 0 , nullptr ); +} + + +void UIScene_HUD::SetRidingHorse(bool ridingHorse, bool bIsJumpable, int maxHorseHealth) +{ + if(m_bRidingHorse != ridingHorse || maxHorseHealth != m_iHorseMaxHealth) + { + app.DebugPrintf("SetRidingHorse to %s\n", ridingHorse?"TRUE":"FALSE"); + m_bRidingHorse = ridingHorse; + m_bIsJumpable = bIsJumpable; + m_iHorseMaxHealth = maxHorseHealth; + + IggyDataValue result; + IggyDataValue value[3]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = ridingHorse; + value[1].type = IGGY_DATATYPE_boolean; + value[1].boolval = bIsJumpable; + value[2].type = IGGY_DATATYPE_number; + value[2].number = maxHorseHealth; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetRidingHorse , 3 , value ); + } +} + +void UIScene_HUD::SetHorseHealth(int health, bool blink /*= false*/) +{ + if(m_bRidingHorse && m_horseHealth != health) + { + app.DebugPrintf("SetHorseHealth to %d\n", health); + m_horseHealth = health; + + IggyDataValue result; + IggyDataValue value[2]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = health; + value[1].type = IGGY_DATATYPE_boolean; + value[1].boolval = blink; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHorseHealth , 2 , value ); + } +} + +void UIScene_HUD::SetHorseJumpBarProgress(float progress) +{ + if(m_bRidingHorse && m_horseJumpProgress != progress) + { + app.DebugPrintf("SetHorseJumpBarProgress to %f\n", progress); + m_horseJumpProgress = progress; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = progress; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHorseJumpBarProgress , 1 , value ); + } +} + +void UIScene_HUD::SetHealthAbsorb(int healthAbsorb) +{ + if(m_iCurrentHealthAbsorb != healthAbsorb) + { + app.DebugPrintf("SetHealthAbsorb to %d\n", healthAbsorb); + m_iCurrentHealthAbsorb = healthAbsorb; + + IggyDataValue result; + IggyDataValue value[2]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = healthAbsorb > 0; + value[1].type = IGGY_DATATYPE_number; + value[1].number = healthAbsorb; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetHealthAbsorb , 2 , value ); + } +} + +void UIScene_HUD::render(S32 width, S32 height, C4JRender::eViewportType viewport) +{ + if(m_bSplitscreen) + { + S32 xPos = 0; + S32 yPos = 0; + switch( viewport ) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + yPos = static_cast(ui.getScreenHeight() / 2); + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + xPos = static_cast(ui.getScreenWidth() / 2); + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + xPos = static_cast(ui.getScreenWidth() / 2); + yPos = static_cast(ui.getScreenHeight() / 2); + break; + } + ui.setupRenderPosition(xPos, yPos); + + S32 tileXStart = 0; + S32 tileYStart = 0; + S32 tileWidth = width; + S32 tileHeight = height; + + bool needsYTile = false; + switch( viewport ) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + tileHeight = static_cast(ui.getScreenHeight()); + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP:case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + tileWidth = static_cast(ui.getScreenWidth()); + needsYTile = true; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + needsYTile = true; + break; + } + + F32 scale; + ComputeTileScale(tileWidth, tileHeight, m_movieWidth, m_movieHeight, needsYTile, scale, tileYStart); + + // For vertical split, if the window is shorter than the SWF movie, + // scale the movie down to fit the full height instead of cropping. + // ComputeTileScale clamps scale >= 1.0 (needed for quadrant mode), + // but in vertical split the tile covers the full screen height and + // cropping the bottom pushes RepositionHud's ActionScript to shift + // elements down. Scaling down keeps visibleH == movieHeight in SWF + // space, so ActionScript sees the full height and applies no offset. + if(!needsYTile && m_movieHeight > 0) + { + F32 scaleH = (F32)tileHeight / (F32)m_movieHeight; + if(scaleH < scale) + scale = scaleH; + } + + IggyPlayerSetDisplaySize( getMovie(), (S32)(m_movieWidth * scale), (S32)(m_movieHeight * scale) ); + + repositionHud(tileWidth, tileHeight, scale, needsYTile); + + m_renderWidth = tileWidth; + m_renderHeight = tileHeight; + + IggyPlayerDrawTilesStart ( getMovie() ); + IggyPlayerDrawTile ( getMovie() , + tileXStart , + tileYStart , + tileXStart + tileWidth , + tileYStart + tileHeight , + 0 ); + IggyPlayerDrawTilesEnd ( getMovie() ); + } + else + { + UIScene::render(width, height, viewport); + } +} + +void UIScene_HUD::handleTimerComplete(int id) +{ + Minecraft *pMinecraft = Minecraft::GetInstance(); + + bool anyVisible = false; + if(pMinecraft->localplayers[m_iPad]!= nullptr) + { + Gui *pGui = pMinecraft->gui; + //DWORD messagesToDisplay = min( CHAT_LINES_COUNT, pGui->getMessagesCount(m_iPad) ); + for( unsigned int i = 0; i < CHAT_LINES_COUNT; ++i ) + { + float opacity = pGui->getOpacity(m_iPad, i); + if( opacity > 0 ) + { +#if 0 // def _WINDOWS64 // Use Iggy chat until Gui::render has visual parity + // Chat drawn by Gui::render with color codes. Hides Iggy chat to avoid double chats. + m_controlLabelBackground[i].setOpacity(0); + m_labelChatText[i].setOpacity(0); + m_labelChatText[i].setLabel(L""); +#else + m_controlLabelBackground[i].setOpacity(opacity); + m_labelChatText[i].setOpacity(opacity); + m_labelChatText[i].setLabel( pGui->getMessagesCount(m_iPad) ? pGui->getMessage(m_iPad,i) : L"" ); +#endif + anyVisible = true; + } + else + { + m_controlLabelBackground[i].setOpacity(0); + m_labelChatText[i].setOpacity(0); + m_labelChatText[i].setLabel(L""); + } + } + if(pGui->getJukeboxOpacity(m_iPad) > 0) anyVisible = true; + m_labelJukebox.setOpacity( pGui->getJukeboxOpacity(m_iPad) ); + m_labelJukebox.setLabel( pGui->getJukeboxMessage(m_iPad) ); + } + else + { + for( unsigned int i = 0; i < CHAT_LINES_COUNT; ++i ) + { + m_controlLabelBackground[i].setOpacity(0); + m_labelChatText[i].setOpacity(0); + m_labelChatText[i].setLabel(L""); + } + m_labelJukebox.setOpacity( 0 ); + } + + //setVisible(anyVisible); +} + +void UIScene_HUD::repositionHud(S32 tileWidth, S32 tileHeight, F32 scale, bool needsYTile) +{ + if(!m_bSplitscreen) return; + + // Pass the visible tile area in SWF coordinates so ActionScript + // positions elements (crosshair, hotbar, etc.) centered in the + // actually visible region, not the raw viewport. + S32 visibleW = static_cast(tileWidth / scale); + S32 visibleH = static_cast(tileHeight / scale); + + app.DebugPrintf(app.USER_SR, "Reposition HUD: tile %dx%d, scale %.3f, visible SWF %dx%d\n", tileWidth, tileHeight, scale, visibleW, visibleH ); + + IggyDataValue result; + IggyDataValue value[2]; + value[0].type = IGGY_DATATYPE_number; + value[0].number = visibleW; + value[1].type = IGGY_DATATYPE_number; + value[1].number = visibleH; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcRepositionHud , 2 , value ); +} + +void UIScene_HUD::ShowDisplayName(bool show) +{ + m_lastShowDisplayName = show; + m_labelDisplayName.setVisible(show); +} + +void UIScene_HUD::SetDisplayName(const wstring &displayName) +{ + if(displayName.compare(m_displayName) != 0) + { + m_displayName = displayName; + + IggyDataValue result; + IggyDataValue value[1]; + IggyStringUTF16 stringVal; + stringVal.string = (IggyUTF16*)displayName.c_str(); + stringVal.length = displayName.length(); + value[0].type = IGGY_DATATYPE_string_UTF16; + value[0].string16 = stringVal; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetDisplayName , 1 , value ); + + m_labelDisplayName.setVisible(m_lastShowDisplayName); + } +} + +void UIScene_HUD::SetTooltipsEnabled(bool bEnabled) +{ + if(m_bToolTipsVisible != bEnabled) + { + m_bToolTipsVisible = bEnabled; + + IggyDataValue result; + IggyDataValue value[1]; + value[0].type = IGGY_DATATYPE_boolean; + value[0].boolval = bEnabled; + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetTooltipsEnabled , 1 , value ); + } +} + +void UIScene_HUD::handleGameTick() +{ + if(getMovie() && app.GetGameStarted()) + { + Minecraft *pMinecraft = Minecraft::GetInstance(); + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) + { + m_parentLayer->showComponent(m_iPad, eUIScene_HUD,false); + return; + } + m_parentLayer->showComponent(m_iPad, eUIScene_HUD,true); + + updateFrameTick(); + } } \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIScene_HUD.h b/Minecraft.Client/Common/UI/UIScene_HUD.h index 9d58ba4ba..04468c8ec 100644 --- a/Minecraft.Client/Common/UI/UIScene_HUD.h +++ b/Minecraft.Client/Common/UI/UIScene_HUD.h @@ -176,5 +176,5 @@ protected: #endif private: - void repositionHud(); + void repositionHud(S32 tileWidth, S32 tileHeight, F32 scale, bool needsYTile); }; diff --git a/Minecraft.Client/Common/UI/UIScene_HelpAndOptionsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_HelpAndOptionsMenu.cpp index 292b77aff..ab79b9400 100644 --- a/Minecraft.Client/Common/UI/UIScene_HelpAndOptionsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HelpAndOptionsMenu.cpp @@ -8,7 +8,7 @@ UIScene_HelpAndOptionsMenu::UIScene_HelpAndOptionsMenu(int iPad, void *initData, // Setup all the Iggy references we need for this scene initialiseMovie(); - m_bNotInGame=(Minecraft::GetInstance()->level==NULL); + m_bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_buttons[BUTTON_HAO_CHANGESKIN].init(IDS_CHANGE_SKIN,BUTTON_HAO_CHANGESKIN); m_buttons[BUTTON_HAO_HOWTOPLAY].init(IDS_HOW_TO_PLAY,BUTTON_HAO_HOWTOPLAY); @@ -41,7 +41,7 @@ UIScene_HelpAndOptionsMenu::UIScene_HelpAndOptionsMenu(int iPad, void *initData, // 4J-PB - do not need a storage device to see this menu - just need one when you choose to re-install them - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // any content to be re-installed? if(m_iPad==ProfileManager.GetPrimaryPad() && bNotInGame) @@ -103,7 +103,7 @@ void UIScene_HelpAndOptionsMenu::updateTooltips() void UIScene_HelpAndOptionsMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -128,7 +128,7 @@ void UIScene_HelpAndOptionsMenu::handleReload() #endif // 4J-PB - do not need a storage device to see this menu - just need one when you choose to re-install them - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // any content to be re-installed? if(m_iPad==ProfileManager.GetPrimaryPad() && bNotInGame) @@ -207,7 +207,7 @@ void UIScene_HelpAndOptionsMenu::handleInput(int iPad, int key, bool repeat, boo void UIScene_HelpAndOptionsMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case BUTTON_HAO_CHANGESKIN: ui.NavigateToScene(m_iPad, eUIScene_SkinSelectMenu); diff --git a/Minecraft.Client/Common/UI/UIScene_HopperMenu.cpp b/Minecraft.Client/Common/UI/UIScene_HopperMenu.cpp index f0f6db18a..8c657c973 100644 --- a/Minecraft.Client/Common/UI/UIScene_HopperMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HopperMenu.cpp @@ -10,14 +10,14 @@ UIScene_HopperMenu::UIScene_HopperMenu(int iPad, void *_initData, UILayer *paren // Setup all the Iggy references we need for this scene initialiseMovie(); - HopperScreenInput *initData = (HopperScreenInput *)_initData; + HopperScreenInput *initData = static_cast(_initData); m_labelDispenser.init(initData->hopper->getName()); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Hopper_Menu, this); } @@ -156,7 +156,7 @@ void UIScene_HopperMenu::setSectionSelectedSlot(ESceneSection eSection, int x, i int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionHopperContents: @@ -177,7 +177,7 @@ void UIScene_HopperMenu::setSectionSelectedSlot(ESceneSection eSection, int x, i UIControl *UIScene_HopperMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionHopperContents: diff --git a/Minecraft.Client/Common/UI/UIScene_HorseInventoryMenu.cpp b/Minecraft.Client/Common/UI/UIScene_HorseInventoryMenu.cpp index ab98e30f9..c062df4ed 100644 --- a/Minecraft.Client/Common/UI/UIScene_HorseInventoryMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HorseInventoryMenu.cpp @@ -11,16 +11,16 @@ UIScene_HorseInventoryMenu::UIScene_HorseInventoryMenu(int iPad, void *_initData // Setup all the Iggy references we need for this scene initialiseMovie(); - HorseScreenInput *initData = (HorseScreenInput *)_initData; + HorseScreenInput *initData = static_cast(_initData); m_labelHorse.init( initData->container->getName() ); m_inventory = initData->inventory; m_horse = initData->horse; Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[iPad] != NULL ) + if( pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Horse_Menu, this); } @@ -240,7 +240,7 @@ void UIScene_HorseInventoryMenu::setSectionSelectedSlot(ESceneSection eSection, int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionHorseArmor: @@ -268,7 +268,7 @@ void UIScene_HorseInventoryMenu::setSectionSelectedSlot(ESceneSection eSection, UIControl *UIScene_HorseInventoryMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionHorseArmor: @@ -296,7 +296,7 @@ UIControl *UIScene_HorseInventoryMenu::getSection(ESceneSection eSection) void UIScene_HorseInventoryMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; if(wcscmp((wchar_t *)region->name,L"horse")==0) { diff --git a/Minecraft.Client/Common/UI/UIScene_HowToPlay.cpp b/Minecraft.Client/Common/UI/UIScene_HowToPlay.cpp index e33e24fe7..bc7218027 100644 --- a/Minecraft.Client/Common/UI/UIScene_HowToPlay.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HowToPlay.cpp @@ -136,7 +136,7 @@ UIScene_HowToPlay::UIScene_HowToPlay(int iPad, void *initData, UILayer *parentLa // Extract pad and required page from init data. We just put the data into the pointer rather than using it as an address. size_t uiInitData = ( size_t )( initData ); - EHowToPlayPage eStartPage = ( EHowToPlayPage )( ( uiInitData >> 16 ) & 0xFFF ); // Ignores MSB which is set to 1! + EHowToPlayPage eStartPage = static_cast((uiInitData >> 16) & 0xFFF); // Ignores MSB which is set to 1! TelemetryManager->RecordMenuShown(m_iPad, eUIScene_HowToPlay, (ETelemetry_HowToPlay_SubMenuId)eStartPage); @@ -216,10 +216,10 @@ void UIScene_HowToPlay::handleInput(int iPad, int key, bool repeat, bool pressed if(pressed) { // Next page - int iNextPage = ( int )( m_eCurrPage ) + 1; + int iNextPage = static_cast(m_eCurrPage) + 1; if ( iNextPage != eHowToPlay_NumPages ) { - StartPage( ( EHowToPlayPage )( iNextPage ) ); + StartPage( static_cast(iNextPage) ); ui.PlayUISFX(eSFX_Press); } handled = true; @@ -229,7 +229,7 @@ void UIScene_HowToPlay::handleInput(int iPad, int key, bool repeat, bool pressed if(pressed) { // Previous page - int iPrevPage = ( int )( m_eCurrPage ) - 1; + int iPrevPage = static_cast(m_eCurrPage) - 1; // 4J Stu - Add back for future platforms #if 0 @@ -247,7 +247,7 @@ void UIScene_HowToPlay::handleInput(int iPad, int key, bool repeat, bool pressed { if ( iPrevPage >= 0 ) { - StartPage( ( EHowToPlayPage )( iPrevPage ) ); + StartPage( static_cast(iPrevPage) ); ui.PlayUISFX(eSFX_Press); } @@ -300,8 +300,8 @@ void UIScene_HowToPlay::StartPage( EHowToPlayPage ePage ) finalText = startTags + finalText; vector paragraphs; - int lastIndex = 0; - for ( int index = finalText.find(L"\r\n", lastIndex, 2); + size_t lastIndex = 0; + for ( size_t index = finalText.find(L"\r\n", lastIndex, 2); index != wstring::npos; index = finalText.find(L"\r\n", lastIndex, 2) ) @@ -318,7 +318,7 @@ void UIScene_HowToPlay::StartPage( EHowToPlayPage ePage ) IggyStringUTF16 * stringVal = new IggyStringUTF16[paragraphs.size()]; value[0].type = IGGY_DATATYPE_number; - value[0].number = gs_pageToFlashMapping[(int)ePage]; + value[0].number = gs_pageToFlashMapping[static_cast(ePage)]; for(unsigned int i = 0; i < paragraphs.size(); ++i) { diff --git a/Minecraft.Client/Common/UI/UIScene_HowToPlayMenu.cpp b/Minecraft.Client/Common/UI/UIScene_HowToPlayMenu.cpp index 92e8bdef8..728bd4c07 100644 --- a/Minecraft.Client/Common/UI/UIScene_HowToPlayMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_HowToPlayMenu.cpp @@ -122,7 +122,7 @@ void UIScene_HowToPlayMenu::updateTooltips() void UIScene_HowToPlayMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -191,13 +191,13 @@ void UIScene_HowToPlayMenu::handleInput(int iPad, int key, bool repeat, bool pre void UIScene_HowToPlayMenu::handlePress(F64 controlId, F64 childId) { - if( (int)controlId == eControl_Buttons) + if( static_cast(controlId) == eControl_Buttons) { //CD - Added for audio ui.PlayUISFX(eSFX_Press); unsigned int uiInitData; - uiInitData = ( ( 1 << 31 ) | ( m_uiHTPSceneA[(int)childId] << 16 ) | ( short )( m_iPad ) ); + uiInitData = ( ( 1 << 31 ) | ( m_uiHTPSceneA[static_cast(childId)] << 16 ) | static_cast(m_iPad) ); ui.NavigateToScene(m_iPad, eUIScene_HowToPlay, ( void* )( uiInitData ) ); } } diff --git a/Minecraft.Client/Common/UI/UIScene_InGameHostOptionsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InGameHostOptionsMenu.cpp index 68ac537ee..51992e322 100644 --- a/Minecraft.Client/Common/UI/UIScene_InGameHostOptionsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InGameHostOptionsMenu.cpp @@ -126,7 +126,7 @@ void UIScene_InGameHostOptionsMenu::handleInput(int iPad, int key, bool repeat, shared_ptr player = pMinecraft->localplayers[m_iPad]; if(player->connection) { - player->connection->send( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, hostOptions) ) ); + player->connection->send(std::make_shared(ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, hostOptions)); } } @@ -153,7 +153,7 @@ void UIScene_InGameHostOptionsMenu::handlePress(F64 controlId, F64 childId) TeleportMenuInitData *initData = new TeleportMenuInitData(); initData->iPad = m_iPad; initData->teleportToPlayer = false; - if( (int)controlId == eControl_TeleportToPlayer ) + if( static_cast(controlId) == eControl_TeleportToPlayer ) { initData->teleportToPlayer = true; } diff --git a/Minecraft.Client/Common/UI/UIScene_InGameInfoMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InGameInfoMenu.cpp index 57acf3458..338d1905c 100644 --- a/Minecraft.Client/Common/UI/UIScene_InGameInfoMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InGameInfoMenu.cpp @@ -23,7 +23,7 @@ UIScene_InGameInfoMenu::UIScene_InGameInfoMenu(int iPad, void *initData, UILayer { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL ) + if( player != nullptr ) { PlayerInfo *info = BuildPlayerInfo(player); @@ -36,7 +36,7 @@ UIScene_InGameInfoMenu::UIScene_InGameInfoMenu(int iPad, void *initData, UILayer INetworkPlayer *thisPlayer = g_NetworkManager.GetLocalPlayerByUserIndex( m_iPad ); m_isHostPlayer = false; - if(thisPlayer != NULL) m_isHostPlayer = thisPlayer->IsHost() == TRUE; + if(thisPlayer != nullptr) m_isHostPlayer = thisPlayer->IsHost() == TRUE; Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr localPlayer = pMinecraft->localplayers[m_iPad]; @@ -109,7 +109,7 @@ void UIScene_InGameInfoMenu::updateTooltips() { keyA = IDS_TOOLTIPS_SELECT; } - else if( selectedPlayer != NULL) + else if( selectedPlayer != nullptr) { bool editingHost = selectedPlayer->IsHost(); if( (cheats && (m_isHostPlayer || !editingHost ) ) || (!trust && (m_isHostPlayer || !editingHost)) @@ -134,7 +134,7 @@ void UIScene_InGameInfoMenu::updateTooltips() if(!m_buttonGameOptions.hasFocus()) { // if the player is me, then view gamer profile - if(selectedPlayer != NULL && selectedPlayer->IsLocal() && selectedPlayer->GetUserIndex()==m_iPad) + if(selectedPlayer != nullptr && selectedPlayer->IsLocal() && selectedPlayer->GetUserIndex()==m_iPad) { ikeyY = IDS_TOOLTIPS_VIEW_GAMERPROFILE; } @@ -150,8 +150,6 @@ void UIScene_InGameInfoMenu::updateTooltips() void UIScene_InGameInfoMenu::handleDestroy() { g_NetworkManager.UnRegisterPlayerChangedCallback(m_iPad, &UIScene_InGameInfoMenu::OnPlayerChanged, this); - - m_parentLayer->removeComponent(eUIComponent_MenuBackground); } void UIScene_InGameInfoMenu::handleGainFocus(bool navBack) @@ -172,7 +170,7 @@ void UIScene_InGameInfoMenu::handleReload() { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL ) + if( player != nullptr ) { PlayerInfo *info = BuildPlayerInfo(player); @@ -183,7 +181,7 @@ void UIScene_InGameInfoMenu::handleReload() INetworkPlayer *thisPlayer = g_NetworkManager.GetLocalPlayerByUserIndex( m_iPad ); m_isHostPlayer = false; - if(thisPlayer != NULL) m_isHostPlayer = thisPlayer->IsHost() == TRUE; + if(thisPlayer != nullptr) m_isHostPlayer = thisPlayer->IsHost() == TRUE; Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr localPlayer = pMinecraft->localplayers[m_iPad]; @@ -209,7 +207,7 @@ void UIScene_InGameInfoMenu::tick() { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if(player != NULL) + if(player != nullptr) { PlayerInfo *info = BuildPlayerInfo(player); @@ -283,7 +281,7 @@ void UIScene_InGameInfoMenu::handleInput(int iPad, int key, bool repeat, bool pr if(pressed && m_playerList.hasFocus() && (m_playerList.getItemCount() > 0) && (m_playerList.getCurrentSelection() < m_players.size()) ) { INetworkPlayer *player = g_NetworkManager.GetPlayerBySmallId(m_players[m_playerList.getCurrentSelection()]->m_smallId); - if( player != NULL ) + if( player != nullptr ) { PlayerUID uid = player->GetUID(); if( uid != INVALID_XUID ) @@ -327,14 +325,14 @@ void UIScene_InGameInfoMenu::handleInput(int iPad, int key, bool repeat, bool pr void UIScene_InGameInfoMenu::handlePress(F64 controlId, F64 childId) { - app.DebugPrintf("Pressed = %d, %d\n", (int)controlId, (int)childId); - switch((int)controlId) + app.DebugPrintf("Pressed = %d, %d\n", static_cast(controlId), static_cast(childId)); + switch(static_cast(controlId)) { case eControl_GameOptions: ui.NavigateToScene(m_iPad,eUIScene_InGameHostOptionsMenu); break; case eControl_GamePlayers: - int currentSelection = (int)childId; + int currentSelection = static_cast(childId); INetworkPlayer *selectedPlayer = g_NetworkManager.GetPlayerBySmallId(m_players[currentSelection]->m_smallId); Minecraft *pMinecraft = Minecraft::GetInstance(); @@ -344,7 +342,7 @@ void UIScene_InGameInfoMenu::handlePress(F64 controlId, F64 childId) bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; bool trust = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; - if( isOp && selectedPlayer != NULL) + if( isOp && selectedPlayer != nullptr) { bool editingHost = selectedPlayer->IsHost(); if( (cheats && (m_isHostPlayer || !editingHost ) ) || (!trust && (m_isHostPlayer || !editingHost)) @@ -377,10 +375,10 @@ void UIScene_InGameInfoMenu::handlePress(F64 controlId, F64 childId) void UIScene_InGameInfoMenu::handleFocusChange(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_GamePlayers: - m_playerList.updateChildFocus( (int) childId ); + m_playerList.updateChildFocus( static_cast(childId) ); }; updateTooltips(); } @@ -389,7 +387,7 @@ void UIScene_InGameInfoMenu::OnPlayerChanged(void *callbackParam, INetworkPlayer { app.DebugPrintf(" Player \"%ls\" %s (smallId: %d)\n", pPlayer->GetOnlineName(), leaving ? "leaving" : "joining", pPlayer->GetSmallId()); - UIScene_InGameInfoMenu *scene = (UIScene_InGameInfoMenu *)callbackParam; + UIScene_InGameInfoMenu *scene = static_cast(callbackParam); bool playerFound = false; int foundIndex = 0; for(int i = 0; i < scene->m_players.size(); ++i) @@ -439,7 +437,7 @@ void UIScene_InGameInfoMenu::OnPlayerChanged(void *callbackParam, INetworkPlayer int UIScene_InGameInfoMenu::KickPlayerReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - BYTE smallId = *(BYTE *)pParam; + BYTE smallId = *static_cast(pParam); delete pParam; if(result==C4JStorage::EMessage_ResultAccept) @@ -448,7 +446,7 @@ int UIScene_InGameInfoMenu::KickPlayerReturned(void *pParam,int iPad,C4JStorage: shared_ptr localPlayer = pMinecraft->localplayers[iPad]; if(localPlayer->connection) { - localPlayer->connection->send( shared_ptr( new KickPlayerPacket(smallId) ) ); + localPlayer->connection->send(std::make_shared(smallId)); } } @@ -473,7 +471,7 @@ UIScene_InGameInfoMenu::PlayerInfo *UIScene_InGameInfoMenu::BuildPlayerInfo(INet } int voiceStatus = 0; - if(player != NULL && player->HasVoice() ) + if(player != nullptr && player->HasVoice() ) { if( player->IsMutedByLocalUser(m_iPad) ) { diff --git a/Minecraft.Client/Common/UI/UIScene_InGamePlayerOptionsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InGamePlayerOptionsMenu.cpp index db9c1d4d0..57937543f 100644 --- a/Minecraft.Client/Common/UI/UIScene_InGamePlayerOptionsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InGamePlayerOptionsMenu.cpp @@ -6,7 +6,6 @@ #include "..\..\ClientConnection.h" #include "..\..\..\Minecraft.World\net.minecraft.network.packet.h" - #define CHECKBOXES_TIMER_ID 0 #define CHECKBOXES_TIMER_TIME 100 @@ -17,21 +16,21 @@ UIScene_InGamePlayerOptionsMenu::UIScene_InGamePlayerOptionsMenu(int iPad, void m_bShouldNavBack = false; - InGamePlayerOptionsInitData *initData = (InGamePlayerOptionsInitData *)_initData; + InGamePlayerOptionsInitData *initData = static_cast(_initData); m_networkSmallId = initData->networkSmallId; m_playerPrivileges = initData->playerPrivileges; INetworkPlayer *localPlayer = g_NetworkManager.GetLocalPlayerByUserIndex( m_iPad ); INetworkPlayer *editingPlayer = g_NetworkManager.GetPlayerBySmallId(m_networkSmallId); - if(editingPlayer != NULL) + if(editingPlayer != nullptr) { m_labelGamertag.init(editingPlayer->GetDisplayName()); } bool trustPlayers = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; - m_editingSelf = (localPlayer != NULL && localPlayer == editingPlayer); + m_editingSelf = (localPlayer != nullptr && localPlayer == editingPlayer); if( m_editingSelf || trustPlayers || editingPlayer->IsHost()) { @@ -241,7 +240,7 @@ void UIScene_InGamePlayerOptionsMenu::handleReload() bool trustPlayers = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; - m_editingSelf = (localPlayer != NULL && localPlayer == editingPlayer); + m_editingSelf = (localPlayer != nullptr && localPlayer == editingPlayer); if( m_editingSelf || trustPlayers || editingPlayer->IsHost()) { @@ -372,7 +371,7 @@ void UIScene_InGamePlayerOptionsMenu::handleInput(int iPad, int key, bool repeat else { INetworkPlayer *editingPlayer = g_NetworkManager.GetPlayerBySmallId(m_networkSmallId); - if(!trustPlayers && (editingPlayer != NULL && !editingPlayer->IsHost() ) ) + if(!trustPlayers && (editingPlayer != nullptr && !editingPlayer->IsHost() ) ) { Player::setPlayerGamePrivilege(m_playerPrivileges,Player::ePlayerGamePrivilege_CannotMine,!m_checkboxes[eControl_BuildAndMine].IsChecked()); Player::setPlayerGamePrivilege(m_playerPrivileges,Player::ePlayerGamePrivilege_CannotBuild,!m_checkboxes[eControl_BuildAndMine].IsChecked()); @@ -405,7 +404,7 @@ void UIScene_InGamePlayerOptionsMenu::handleInput(int iPad, int key, bool repeat shared_ptr player = pMinecraft->localplayers[m_iPad]; if(player->connection) { - player->connection->send( shared_ptr( new PlayerInfoPacket( m_networkSmallId, -1, m_playerPrivileges) ) ); + player->connection->send(std::make_shared(m_networkSmallId, -1, m_playerPrivileges)); } } navigateBack(); @@ -428,7 +427,7 @@ void UIScene_InGamePlayerOptionsMenu::handleInput(int iPad, int key, bool repeat void UIScene_InGamePlayerOptionsMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Kick: { @@ -446,7 +445,7 @@ void UIScene_InGamePlayerOptionsMenu::handlePress(F64 controlId, F64 childId) int UIScene_InGamePlayerOptionsMenu::KickPlayerReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - BYTE smallId = *(BYTE *)pParam; + BYTE smallId = *static_cast(pParam); delete pParam; if(result==C4JStorage::EMessage_ResultAccept) @@ -455,7 +454,7 @@ int UIScene_InGamePlayerOptionsMenu::KickPlayerReturned(void *pParam,int iPad,C4 shared_ptr localPlayer = pMinecraft->localplayers[iPad]; if(localPlayer->connection) { - localPlayer->connection->send( shared_ptr( new KickPlayerPacket(smallId) ) ); + localPlayer->connection->send(std::make_shared(smallId)); } // Fix for #61494 - [CRASH]: TU7: Code: Multiplayer: Title may crash while kicking a player from an online game. @@ -470,12 +469,12 @@ int UIScene_InGamePlayerOptionsMenu::KickPlayerReturned(void *pParam,int iPad,C4 void UIScene_InGamePlayerOptionsMenu::OnPlayerChanged(void *callbackParam, INetworkPlayer *pPlayer, bool leaving) { app.DebugPrintf("UIScene_InGamePlayerOptionsMenu::OnPlayerChanged"); - UIScene_InGamePlayerOptionsMenu *scene = (UIScene_InGamePlayerOptionsMenu *)callbackParam; + UIScene_InGamePlayerOptionsMenu *scene = static_cast(callbackParam); - UIScene_InGameInfoMenu *infoScene = (UIScene_InGameInfoMenu *)scene->getBackScene(); - if(infoScene != NULL) UIScene_InGameInfoMenu::OnPlayerChanged(infoScene,pPlayer,leaving); + UIScene_InGameInfoMenu *infoScene = static_cast(scene->getBackScene()); + if(infoScene != nullptr) UIScene_InGameInfoMenu::OnPlayerChanged(infoScene,pPlayer,leaving); - if(leaving && pPlayer != NULL && pPlayer->GetSmallId() == scene->m_networkSmallId) + if(leaving && pPlayer != nullptr && pPlayer->GetSmallId() == scene->m_networkSmallId) { scene->m_bShouldNavBack = true; } @@ -497,7 +496,7 @@ void UIScene_InGamePlayerOptionsMenu::resetCheatCheckboxes() void UIScene_InGamePlayerOptionsMenu::handleCheckboxToggled(F64 controlId, bool selected) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Op: // flag that the moderator state has changed diff --git a/Minecraft.Client/Common/UI/UIScene_InGameSaveManagementMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InGameSaveManagementMenu.cpp index fa2c7e613..fb118b154 100644 --- a/Minecraft.Client/Common/UI/UIScene_InGameSaveManagementMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InGameSaveManagementMenu.cpp @@ -8,7 +8,7 @@ int UIScene_InGameSaveManagementMenu::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) { - UIScene_InGameSaveManagementMenu *pClass= (UIScene_InGameSaveManagementMenu *)lpParam; + UIScene_InGameSaveManagementMenu *pClass= static_cast(lpParam); app.DebugPrintf("Received data for save thumbnail\n"); @@ -20,9 +20,9 @@ int UIScene_InGameSaveManagementMenu::LoadSaveDataThumbnailReturned(LPVOID lpPar } else { - pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].pbThumbnailData = NULL; + pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].pbThumbnailData = nullptr; pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].dwThumbnailSize = 0; - app.DebugPrintf("Save thumbnail data is NULL, or has size 0\n"); + app.DebugPrintf("Save thumbnail data is nullptr, or has size 0\n"); } pClass->m_bSaveThumbnailReady = true; @@ -55,9 +55,9 @@ UIScene_InGameSaveManagementMenu::UIScene_InGameSaveManagementMenu(int iPad, voi m_bRetrievingSaveThumbnails = false; m_bSaveThumbnailReady = false; m_bExitScene=false; - m_pSaveDetails=NULL; + m_pSaveDetails=nullptr; m_bSavesDisplayed=false; - m_saveDetails = NULL; + m_saveDetails = nullptr; m_iSaveDetailsCount = 0; #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) || defined(_DURANGO) @@ -198,17 +198,17 @@ void UIScene_InGameSaveManagementMenu::tick() if(!m_bSavesDisplayed) { m_pSaveDetails=StorageManager.ReturnSavesInfo(); - if(m_pSaveDetails!=NULL) + if(m_pSaveDetails!=nullptr) { m_spaceIndicatorSaves.reset(); m_bSavesDisplayed=true; - if(m_saveDetails!=NULL) + if(m_saveDetails!=nullptr) { for(unsigned int i = 0; i < m_pSaveDetails->iSaveC; ++i) { - if(m_saveDetails[i].pbThumbnailData!=NULL) + if(m_saveDetails[i].pbThumbnailData!=nullptr) { delete m_saveDetails[i].pbThumbnailData; } @@ -371,9 +371,9 @@ void UIScene_InGameSaveManagementMenu::GetSaveInfo( ) m_controlSavesTimer.setVisible(true); m_pSaveDetails=StorageManager.ReturnSavesInfo(); - if(m_pSaveDetails==NULL) + if(m_pSaveDetails==nullptr) { - C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); + C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,nullptr,this,"save"); } @@ -418,12 +418,12 @@ void UIScene_InGameSaveManagementMenu::handleInput(int iPad, int key, bool repea void UIScene_InGameSaveManagementMenu::handleInitFocus(F64 controlId, F64 childId) { - app.DebugPrintf(app.USER_SR, "UIScene_InGameSaveManagementMenu::handleInitFocus - %d , %d\n", (int)controlId, (int)childId); + app.DebugPrintf(app.USER_SR, "UIScene_InGameSaveManagementMenu::handleInitFocus - %d , %d\n", static_cast(controlId), static_cast(childId)); } void UIScene_InGameSaveManagementMenu::handleFocusChange(F64 controlId, F64 childId) { - app.DebugPrintf(app.USER_SR, "UIScene_InGameSaveManagementMenu::handleFocusChange - %d , %d\n", (int)controlId, (int)childId); + app.DebugPrintf(app.USER_SR, "UIScene_InGameSaveManagementMenu::handleFocusChange - %d , %d\n", static_cast(controlId), static_cast(childId)); m_iSaveListIndex = childId; if(m_bSavesDisplayed) m_bUpdateSaveSize = true; updateTooltips(); @@ -431,7 +431,7 @@ void UIScene_InGameSaveManagementMenu::handleFocusChange(F64 controlId, F64 chil void UIScene_InGameSaveManagementMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_SavesList: { @@ -452,7 +452,7 @@ void UIScene_InGameSaveManagementMenu::handlePress(F64 controlId, F64 childId) int UIScene_InGameSaveManagementMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_InGameSaveManagementMenu* pClass = (UIScene_InGameSaveManagementMenu*)pParam; + UIScene_InGameSaveManagementMenu* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -477,7 +477,7 @@ int UIScene_InGameSaveManagementMenu::DeleteSaveDialogReturned(void *pParam,int int UIScene_InGameSaveManagementMenu::DeleteSaveDataReturned(LPVOID lpParam,bool bRes) { - UIScene_InGameSaveManagementMenu* pClass = (UIScene_InGameSaveManagementMenu*)lpParam; + UIScene_InGameSaveManagementMenu* pClass = static_cast(lpParam); if(bRes) { diff --git a/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp index 4a9dab43d..4e217c772 100644 --- a/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp @@ -23,17 +23,17 @@ UIScene_InventoryMenu::UIScene_InventoryMenu(int iPad, void *_initData, UILayer // Setup all the Iggy references we need for this scene initialiseMovie(); - InventoryScreenInput *initData = (InventoryScreenInput *)_initData; + InventoryScreenInput *initData = static_cast(_initData); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[initData->iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Inventory_Menu, this); } - InventoryMenu *menu = (InventoryMenu *)initData->player->inventoryMenu; + InventoryMenu *menu = static_cast(initData->player->inventoryMenu); initData->player->awardStat(GenericStats::openInventory(),GenericStats::param_openInventory()); @@ -182,7 +182,7 @@ void UIScene_InventoryMenu::setSectionSelectedSlot(ESceneSection eSection, int x int index = (y * cols) + x; - UIControl_SlotList *slotList = NULL; + UIControl_SlotList *slotList = nullptr; switch( eSection ) { case eSectionInventoryArmor: @@ -201,7 +201,7 @@ void UIScene_InventoryMenu::setSectionSelectedSlot(ESceneSection eSection, int x UIControl *UIScene_InventoryMenu::getSection(ESceneSection eSection) { - UIControl *control = NULL; + UIControl *control = nullptr; switch( eSection ) { case eSectionInventoryArmor: @@ -220,7 +220,7 @@ UIControl *UIScene_InventoryMenu::getSection(ESceneSection eSection) void UIScene_InventoryMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; if(wcscmp((wchar_t *)region->name,L"player")==0) { @@ -253,7 +253,7 @@ void UIScene_InventoryMenu::updateEffectsDisplay() Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player == NULL) return; + if(player == nullptr) return; vector *activeEffects = player->getActiveEffects(); diff --git a/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp index ccb572b83..417c1700c 100644 --- a/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp @@ -16,7 +16,7 @@ UIScene_JoinMenu::UIScene_JoinMenu(int iPad, void *_initData, UILayer *parentLay // Setup all the Iggy references we need for this scene initialiseMovie(); - JoinMenuInitData *initData = (JoinMenuInitData *)_initData; + JoinMenuInitData *initData = static_cast(_initData); m_selectedSession = initData->selectedSession; m_friendInfoUpdatedOK = false; m_friendInfoUpdatedERROR = false; @@ -77,7 +77,7 @@ void UIScene_JoinMenu::tick() #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ for( int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++ ) { - if( m_selectedSession->data.players[i] != NULL ) + if( m_selectedSession->data.players[i] != nullptr ) { #ifndef _CONTENT_PACKAGE if(app.DebugSettingsOn() && (app.GetGameSettingsDebugMask()&(1L<(pParam); ui.NavigateBack(scene->m_iPad); if( success ) { @@ -263,7 +263,7 @@ void UIScene_JoinMenu::friendSessionUpdated(bool success, void *pParam) int UIScene_JoinMenu::ErrorDialogReturned(void *pParam, int iPad, const C4JStorage::EMessageResult) { - UIScene_JoinMenu *scene = (UIScene_JoinMenu *)pParam; + UIScene_JoinMenu *scene = static_cast(pParam); ui.NavigateBack(scene->m_iPad); return 0; @@ -297,7 +297,7 @@ void UIScene_JoinMenu::handleInput(int iPad, int key, bool repeat, bool pressed, break; #ifdef _DURANGO case ACTION_MENU_Y: - if(m_selectedSession != NULL && getControlFocus() == eControl_GamePlayers && m_buttonListPlayers.getItemCount() > 0) + if(m_selectedSession != nullptr && getControlFocus() == eControl_GamePlayers && m_buttonListPlayers.getItemCount() > 0) { PlayerUID uid = m_selectedSession->searchResult.m_playerXuids[m_buttonListPlayers.getCurrentSelection()]; if( uid != INVALID_XUID ) ProfileManager.ShowProfileCard(ProfileManager.GetLockedProfile(),uid); @@ -352,7 +352,7 @@ void UIScene_JoinMenu::handleInput(int iPad, int key, bool repeat, bool pressed, void UIScene_JoinMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_JoinGame: { @@ -385,10 +385,10 @@ void UIScene_JoinMenu::handlePress(F64 controlId, F64 childId) void UIScene_JoinMenu::handleFocusChange(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_GamePlayers: - m_buttonListPlayers.updateChildFocus( (int) childId ); + m_buttonListPlayers.updateChildFocus( static_cast(childId) ); }; updateTooltips(); } @@ -431,7 +431,7 @@ void UIScene_JoinMenu::StartSharedLaunchFlow() int UIScene_JoinMenu::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - UIScene_JoinMenu* pClass = (UIScene_JoinMenu*)ui.GetSceneFromCallbackId((size_t)pParam); + UIScene_JoinMenu* pClass = static_cast(ui.GetSceneFromCallbackId((size_t)pParam)); if(pClass) { @@ -534,7 +534,7 @@ void UIScene_JoinMenu::JoinGame(UIScene_JoinMenu* pClass) #if defined(__PS3__) || defined(__PSVITA__) if(isSignedInLive) { - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&noUGC,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&noUGC,nullptr,nullptr); } #else ProfileManager.AllowedPlayerCreatedContent(ProfileManager.GetPrimaryPad(),false,&pccAllowed,&pccFriendsAllowed); @@ -572,7 +572,7 @@ void UIScene_JoinMenu::JoinGame(UIScene_JoinMenu* pClass) { #if defined(__ORBIS__) || defined(__PSVITA__) bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); @@ -669,7 +669,7 @@ void UIScene_JoinMenu::handleTimerComplete(int id) int selectedIndex = 0; for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { - if( m_selectedSession->data.players[i] != NULL ) + if( m_selectedSession->data.players[i] != nullptr ) { if(m_selectedSession->data.players[i] == selectedPlayerXUID) selectedIndex = i; playersList.InsertItems(i,1); @@ -686,7 +686,7 @@ void UIScene_JoinMenu::handleTimerComplete(int id) } else { - // Leave the loop when we hit the first NULL player + // Leave the loop when we hit the first nullptr player break; } } diff --git a/Minecraft.Client/Common/UI/UIScene_Keyboard.cpp b/Minecraft.Client/Common/UI/UIScene_Keyboard.cpp index 0af343bb0..2f2f91326 100644 --- a/Minecraft.Client/Common/UI/UIScene_Keyboard.cpp +++ b/Minecraft.Client/Common/UI/UIScene_Keyboard.cpp @@ -17,8 +17,8 @@ UIScene_Keyboard::UIScene_Keyboard(int iPad, void *initData, UILayer *parentLaye initialiseMovie(); #ifdef _WINDOWS64 - m_win64Callback = NULL; - m_win64CallbackParam = NULL; + m_win64Callback = nullptr; + m_win64CallbackParam = nullptr; m_win64TextBuffer = L""; m_win64MaxChars = 25; @@ -28,7 +28,7 @@ UIScene_Keyboard::UIScene_Keyboard(int iPad, void *initData, UILayer *parentLaye m_bPCMode = false; if (initData) { - UIKeyboardInitData* kbData = (UIKeyboardInitData*)initData; + UIKeyboardInitData* kbData = static_cast(initData); m_win64Callback = kbData->callback; m_win64CallbackParam = kbData->lpParam; if (kbData->title) titleText = kbData->title; @@ -38,6 +38,7 @@ UIScene_Keyboard::UIScene_Keyboard(int iPad, void *initData, UILayer *parentLaye } m_win64TextBuffer = defaultText; + m_iCursorPos = (int)m_win64TextBuffer.length(); m_EnterTextLabel.init(titleText); m_KeyboardTextInput.init(defaultText, -1); @@ -105,12 +106,15 @@ UIScene_Keyboard::UIScene_Keyboard(int iPad, void *initData, UILayer *parentLaye }; IggyName nameVisible = registerFastName(L"visible"); IggyValuePath* root = IggyPlayerRootPath(getMovie()); - for (int i = 0; i < (int)(sizeof(s_keyNames) / sizeof(s_keyNames[0])); ++i) + for (int i = 0; i < static_cast(sizeof(s_keyNames) / sizeof(s_keyNames[0])); ++i) { IggyValuePath keyPath; if (IggyValuePathMakeNameRef(&keyPath, root, s_keyNames[i])) - IggyValueSetBooleanRS(&keyPath, nameVisible, NULL, false); + IggyValueSetBooleanRS(&keyPath, nameVisible, nullptr, false); } + + m_KeyboardTextInput.setCaretVisible(true); + m_KeyboardTextInput.setCaretIndex(m_iCursorPos); } #endif @@ -165,9 +169,13 @@ void UIScene_Keyboard::tick() // Sync our buffer from Flash so we pick up changes made via controller/on-screen buttons. // Without this, switching between controller and keyboard would use stale text. - const wchar_t* flashText = m_KeyboardTextInput.getLabel(); - if (flashText) - m_win64TextBuffer = flashText; + // In PC mode we own the buffer — skip sync to preserve cursor position. + if (!m_bPCMode) + { + const wchar_t* flashText = m_KeyboardTextInput.getLabel(); + if (flashText) + m_win64TextBuffer = flashText; + } // Accumulate physical keyboard chars into our own buffer, then push to Flash via setLabel. // This bypasses Iggy's focus system (char events only route to the focused element). @@ -178,7 +186,16 @@ void UIScene_Keyboard::tick() { if (ch == 0x08) // backspace { - if (!m_win64TextBuffer.empty()) + if (m_bPCMode) + { + if (m_iCursorPos > 0) + { + m_win64TextBuffer.erase(m_iCursorPos - 1, 1); + m_iCursorPos--; + changed = true; + } + } + else if (!m_win64TextBuffer.empty()) { m_win64TextBuffer.pop_back(); changed = true; @@ -192,15 +209,47 @@ void UIScene_Keyboard::tick() m_bKeyboardDonePressed = true; } } - else if ((int)m_win64TextBuffer.length() < m_win64MaxChars) + else if (static_cast(m_win64TextBuffer.length()) < m_win64MaxChars) { - m_win64TextBuffer += ch; + if (m_bPCMode) + { + m_win64TextBuffer.insert(m_iCursorPos, 1, ch); + m_iCursorPos++; + } + else + { + m_win64TextBuffer += ch; + } + changed = true; + } + } + + if (m_bPCMode) + { + // Arrow keys, Home, End, Delete for cursor movement + if (g_KBMInput.IsKeyPressed(VK_LEFT) && m_iCursorPos > 0) + m_iCursorPos--; + if (g_KBMInput.IsKeyPressed(VK_RIGHT) && m_iCursorPos < (int)m_win64TextBuffer.length()) + m_iCursorPos++; + if (g_KBMInput.IsKeyPressed(VK_HOME)) + m_iCursorPos = 0; + if (g_KBMInput.IsKeyPressed(VK_END)) + m_iCursorPos = (int)m_win64TextBuffer.length(); + if (g_KBMInput.IsKeyPressed(VK_DELETE) && m_iCursorPos < (int)m_win64TextBuffer.length()) + { + m_win64TextBuffer.erase(m_iCursorPos, 1); changed = true; } } if (changed) m_KeyboardTextInput.setLabel(m_win64TextBuffer.c_str(), true /*instant*/); + + if (m_bPCMode) + { + m_KeyboardTextInput.setCaretVisible(true); + m_KeyboardTextInput.setCaretIndex(m_iCursorPos); + } } #endif @@ -243,23 +292,23 @@ void UIScene_Keyboard::handleInput(int iPad, int key, bool repeat, bool pressed, } #endif if (key == ACTION_MENU_X) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcBackspaceButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcBackspaceButtonPressed, 0 , nullptr); else if (key == ACTION_MENU_PAGEUP) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSymbolButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSymbolButtonPressed, 0 , nullptr); else if (key == ACTION_MENU_Y) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSpaceButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSpaceButtonPressed, 0 , nullptr); else if (key == ACTION_MENU_STICK_PRESS) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCapsButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCapsButtonPressed, 0 , nullptr); else if (key == ACTION_MENU_LEFT_SCROLL) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCursorLeftButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCursorLeftButtonPressed, 0 , nullptr); else if (key == ACTION_MENU_RIGHT_SCROLL) - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCursorRightButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcCursorRightButtonPressed, 0 , nullptr); handled = true; break; case ACTION_MENU_PAUSEMENU: // Start if(!m_bKeyboardDonePressed) { - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcDoneButtonPressed, 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcDoneButtonPressed, 0 , nullptr ); // kick off done timer addTimer(KEYBOARD_DONE_TIMER_ID,KEYBOARD_DONE_TIMER_TIME); @@ -286,7 +335,10 @@ void UIScene_Keyboard::handleInput(int iPad, int key, bool repeat, bool pressed, case ACTION_MENU_RIGHT: case ACTION_MENU_UP: case ACTION_MENU_DOWN: - sendInputToMovie(key, repeat, pressed, released); +#ifdef _WINDOWS64 + if (!m_bPCMode) +#endif + sendInputToMovie(key, repeat, pressed, released); handled = true; break; } @@ -294,7 +346,7 @@ void UIScene_Keyboard::handleInput(int iPad, int key, bool repeat, bool pressed, void UIScene_Keyboard::handlePress(F64 controlId, F64 childId) { - if((int)controlId == 0) + if(static_cast(controlId) == 0) { // Done has been pressed. At this point we can query for the input string and pass it on to wherever it is needed. // we can not query for m_KeyboardTextInput.getLabel() here because we're in an iggy callback so we need to wait a frame. diff --git a/Minecraft.Client/Common/UI/UIScene_Keyboard.h b/Minecraft.Client/Common/UI/UIScene_Keyboard.h index 054322f20..146934c1f 100644 --- a/Minecraft.Client/Common/UI/UIScene_Keyboard.h +++ b/Minecraft.Client/Common/UI/UIScene_Keyboard.h @@ -13,6 +13,7 @@ private: wstring m_win64TextBuffer; int m_win64MaxChars; bool m_bPCMode; // Hides on-screen keyboard buttons; physical keyboard only + int m_iCursorPos; #endif protected: diff --git a/Minecraft.Client/Common/UI/UIScene_LanguageSelector.cpp b/Minecraft.Client/Common/UI/UIScene_LanguageSelector.cpp index 070391356..c2a30d3c2 100644 --- a/Minecraft.Client/Common/UI/UIScene_LanguageSelector.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LanguageSelector.cpp @@ -58,7 +58,7 @@ void UIScene_LanguageSelector::updateTooltips() void UIScene_LanguageSelector::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -112,14 +112,14 @@ void UIScene_LanguageSelector::handleInput(int iPad, int key, bool repeat, bool void UIScene_LanguageSelector::handlePress(F64 controlId, F64 childId) { - if( (int)controlId == eControl_Buttons ) + if( static_cast(controlId) == eControl_Buttons ) { //CD - Added for audio ui.PlayUISFX(eSFX_Press); int newLanguage, newLocale; - newLanguage = uiLangMap[(int)childId]; - newLocale = uiLocaleMap[(int)childId]; + newLanguage = uiLangMap[static_cast(childId)]; + newLocale = uiLocaleMap[static_cast(childId)]; app.SetMinecraftLanguage(m_iPad, newLanguage); app.SetMinecraftLocale(m_iPad, newLocale); diff --git a/Minecraft.Client/Common/UI/UIScene_LaunchMoreOptionsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LaunchMoreOptionsMenu.cpp index 96dd744e9..b2981ebf6 100644 --- a/Minecraft.Client/Common/UI/UIScene_LaunchMoreOptionsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LaunchMoreOptionsMenu.cpp @@ -20,7 +20,7 @@ UIScene_LaunchMoreOptionsMenu::UIScene_LaunchMoreOptionsMenu(int iPad, void *ini // Setup all the Iggy references we need for this scene initialiseMovie(); - m_params = (LaunchMoreOptionsMenuInitData *)initData; + m_params = static_cast(initData); m_labelWorldOptions.init(app.GetString(IDS_WORLD_OPTIONS)); @@ -116,9 +116,9 @@ UIScene_LaunchMoreOptionsMenu::UIScene_LaunchMoreOptionsMenu(int iPad, void *ini if(m_params->currentWorldSize != e_worldSize_Unknown) { m_labelWorldResize.init(app.GetString(IDS_INCREASE_WORLD_SIZE)); - int min= int(m_params->currentWorldSize)-1; + int min= static_cast(m_params->currentWorldSize)-1; int max=3; - int curr = int(m_params->newWorldSize)-1; + int curr = static_cast(m_params->newWorldSize)-1; m_sliderWorldResize.init(app.GetString(m_iWorldSizeTitleA[curr]),eControl_WorldResize,min,max,curr); m_checkboxes[eLaunchCheckbox_WorldResizeType].init(app.GetString(IDS_INCREASE_WORLD_SIZE_OVERWRITE_EDGES),eLaunchCheckbox_WorldResizeType,m_params->newWorldSizeOverwriteEdges); } @@ -308,7 +308,7 @@ void UIScene_LaunchMoreOptionsMenu::handleInput(int iPad, int key, bool repeat, m_tabIndex = m_tabIndex == 0 ? 1 : 0; updateTooltips(); IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcChangeTab , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcChangeTab , 0 , nullptr ); } break; } @@ -330,7 +330,7 @@ void UIScene_LaunchMoreOptionsMenu::handleTouchInput(unsigned int iPad, S32 x, S m_tabIndex = iNewTabIndex; updateTooltips(); IggyDataValue result; - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcChangeTab , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcChangeTab , 0 , nullptr ); } ui.TouchBoxRebuild(this); break; @@ -354,7 +354,7 @@ void UIScene_LaunchMoreOptionsMenu::handleCheckboxToggled(F64 controlId, bool se //CD - Added for audio ui.PlayUISFX(eSFX_Press); - switch((EControls)((int)controlId)) + switch(static_cast((int)controlId)) { case eLaunchCheckbox_Online: m_params->bOnlineGame = selected; @@ -428,7 +428,7 @@ void UIScene_LaunchMoreOptionsMenu::handleCheckboxToggled(F64 controlId, bool se void UIScene_LaunchMoreOptionsMenu::handleFocusChange(F64 controlId, F64 childId) { int stringId = 0; - switch((int)controlId) + switch(static_cast(controlId)) { case eLaunchCheckbox_Online: stringId = IDS_GAMEOPTION_ONLINE; @@ -549,7 +549,7 @@ void UIScene_LaunchMoreOptionsMenu::handleTimerComplete(int id) int UIScene_LaunchMoreOptionsMenu::KeyboardCompleteSeedCallback(LPVOID lpParam,bool bRes) { - UIScene_LaunchMoreOptionsMenu *pClass=(UIScene_LaunchMoreOptionsMenu *)lpParam; + UIScene_LaunchMoreOptionsMenu *pClass=static_cast(lpParam); pClass->m_bIgnoreInput=false; if (bRes) { @@ -595,7 +595,7 @@ void UIScene_LaunchMoreOptionsMenu::handlePress(F64 controlId, F64 childId) if (isDirectEditBlocking()) return; #endif - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_EditSeed: { @@ -642,8 +642,8 @@ void UIScene_LaunchMoreOptionsMenu::handlePress(F64 controlId, F64 childId) void UIScene_LaunchMoreOptionsMenu::handleSliderMove(F64 sliderId, F64 currentValue) { - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_WorldSize: #ifdef _LARGE_WORLDS @@ -654,11 +654,11 @@ void UIScene_LaunchMoreOptionsMenu::handleSliderMove(F64 sliderId, F64 currentVa break; case eControl_WorldResize: #ifdef _LARGE_WORLDS - EGameHostOptionWorldSize changedSize = EGameHostOptionWorldSize(value+1); + EGameHostOptionWorldSize changedSize = static_cast(value + 1); if(changedSize >= m_params->currentWorldSize) { m_sliderWorldResize.handleSliderMove(value); - m_params->newWorldSize = EGameHostOptionWorldSize(value+1); + m_params->newWorldSize = static_cast(value + 1); m_sliderWorldResize.setLabel(app.GetString(m_iWorldSizeTitleA[value])); } #endif diff --git a/Minecraft.Client/Common/UI/UIScene_LeaderboardsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LeaderboardsMenu.cpp index 12b219053..ed0b3151f 100644 --- a/Minecraft.Client/Common/UI/UIScene_LeaderboardsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LeaderboardsMenu.cpp @@ -9,12 +9,12 @@ #define PLAYER_ONLINE_TIMER_TIME 100 // if the value is greater than 32000, it's an xzp icon that needs displayed, rather than the game icon -const int UIScene_LeaderboardsMenu::TitleIcons[UIScene_LeaderboardsMenu::NUM_LEADERBOARDS][7] = +const int UIScene_LeaderboardsMenu::TitleIcons[UIScene_LeaderboardsMenu::NUM_LEADERBOARDS][7] = { - { UIControl_LeaderboardList::e_ICON_TYPE_WALKED, UIControl_LeaderboardList::e_ICON_TYPE_FALLEN, Item::minecart_Id, Item::boat_Id, NULL }, - { Tile::dirt_Id, Tile::cobblestone_Id, Tile::sand_Id, Tile::stone_Id, Tile::gravel_Id, Tile::clay_Id, Tile::obsidian_Id }, - { Item::egg_Id, Item::wheat_Id, Tile::mushroom_brown_Id, Tile::reeds_Id, Item::bucket_milk_Id, Tile::pumpkin_Id, NULL }, - { UIControl_LeaderboardList::e_ICON_TYPE_ZOMBIE, UIControl_LeaderboardList::e_ICON_TYPE_SKELETON, UIControl_LeaderboardList::e_ICON_TYPE_CREEPER, UIControl_LeaderboardList::e_ICON_TYPE_SPIDER, UIControl_LeaderboardList::e_ICON_TYPE_SPIDERJOKEY, UIControl_LeaderboardList::e_ICON_TYPE_ZOMBIEPIGMAN, UIControl_LeaderboardList::e_ICON_TYPE_SLIME }, + {UIControl_LeaderboardList::e_ICON_TYPE_WALKED, UIControl_LeaderboardList::e_ICON_TYPE_FALLEN, Item::minecart_Id, Item::boat_Id, -1}, + {Tile::dirt_Id, Tile::cobblestone_Id, Tile::sand_Id, Tile::stone_Id, Tile::gravel_Id, Tile::clay_Id, Tile::obsidian_Id}, + {Item::egg_Id, Item::wheat_Id, Tile::mushroom_brown_Id, Tile::reeds_Id, Item::bucket_milk_Id, Tile::pumpkin_Id, -1}, + {UIControl_LeaderboardList::e_ICON_TYPE_ZOMBIE, UIControl_LeaderboardList::e_ICON_TYPE_SKELETON, UIControl_LeaderboardList::e_ICON_TYPE_CREEPER, UIControl_LeaderboardList::e_ICON_TYPE_SPIDER, UIControl_LeaderboardList::e_ICON_TYPE_SPIDERJOKEY, UIControl_LeaderboardList::e_ICON_TYPE_ZOMBIEPIGMAN, UIControl_LeaderboardList::e_ICON_TYPE_SLIME}, }; const UIScene_LeaderboardsMenu::LeaderboardDescriptor UIScene_LeaderboardsMenu::LEADERBOARD_DESCRIPTORS[UIScene_LeaderboardsMenu::NUM_LEADERBOARDS][4] = { { @@ -438,7 +438,7 @@ void UIScene_LeaderboardsMenu::ReadStats(int startIndex) } else { - m_newEntryIndex = (unsigned int)startIndex; + m_newEntryIndex = static_cast(startIndex); // m_newReadSize = min((int)READ_SIZE, (int)m_leaderboard.m_totalEntryCount-(startIndex-1)); } @@ -462,7 +462,7 @@ void UIScene_LeaderboardsMenu::ReadStats(int startIndex) { m_interface.ReadStats_TopRank( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), m_newEntryIndex, m_newReadSize ); } @@ -472,7 +472,7 @@ void UIScene_LeaderboardsMenu::ReadStats(int startIndex) PlayerUID uid; ProfileManager.GetXUID(ProfileManager.GetPrimaryPad(),&uid, true); m_interface.ReadStats_MyScore( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), uid /*ignored on PS3*/, m_newReadSize ); @@ -483,7 +483,7 @@ void UIScene_LeaderboardsMenu::ReadStats(int startIndex) PlayerUID uid; ProfileManager.GetXUID(ProfileManager.GetPrimaryPad(),&uid, true); m_interface.ReadStats_Friends( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), uid /*ignored on PS3*/, m_newEntryIndex, m_newReadSize ); @@ -558,7 +558,7 @@ bool UIScene_LeaderboardsMenu::RetrieveStats() else { m_leaderboard.m_entries[entryIndex].m_columns[i] = UINT_MAX; - swprintf(m_leaderboard.m_entries[entryIndex].m_wcColumns[i], 12, L"%.1fkm", ((float)m_leaderboard.m_entries[entryIndex].m_columns[i])/100.f/1000.f); + swprintf(m_leaderboard.m_entries[entryIndex].m_wcColumns[i], 12, L"%.1fkm", static_cast(m_leaderboard.m_entries[entryIndex].m_columns[i])/100.f/1000.f); } } @@ -576,7 +576,7 @@ bool UIScene_LeaderboardsMenu::RetrieveStats() return true; } - //assert( LeaderboardManager::Instance()->GetStats() != NULL ); + //assert( LeaderboardManager::Instance()->GetStats() != nullptr ); //PXUSER_STATS_READ_RESULTS stats = LeaderboardManager::Instance()->GetStats(); //if( m_currentFilter == LeaderboardManager::eFM_Friends ) LeaderboardManager::Instance()->SortFriendStats(); @@ -781,7 +781,7 @@ void UIScene_LeaderboardsMenu::CopyLeaderboardEntry(LeaderboardManager::ReadScor else if(iDigitC<8) { // km with a .X - swprintf(leaderboardEntry->m_wcColumns[i], 12, L"%.1fkm", ((float)leaderboardEntry->m_columns[i])/1000.f); + swprintf(leaderboardEntry->m_wcColumns[i], 12, L"%.1fkm", static_cast(leaderboardEntry->m_columns[i])/1000.f); #ifdef _DEBUG //app.DebugPrintf("Display - %.1fkm\n", ((float)leaderboardEntry->m_columns[i])/1000.f); #endif @@ -789,7 +789,7 @@ void UIScene_LeaderboardsMenu::CopyLeaderboardEntry(LeaderboardManager::ReadScor else { // bigger than that, so no decimal point - swprintf(leaderboardEntry->m_wcColumns[i], 12, L"%.0fkm", ((float)leaderboardEntry->m_columns[i])/1000.f); + swprintf(leaderboardEntry->m_wcColumns[i], 12, L"%.0fkm", static_cast(leaderboardEntry->m_columns[i])/1000.f); #ifdef _DEBUG //app.DebugPrintf("Display - %.0fkm\n", ((float)leaderboardEntry->m_columns[i])/1000.f); #endif @@ -964,14 +964,14 @@ int UIScene_LeaderboardsMenu::SetLeaderboardTitleIcons() void UIScene_LeaderboardsMenu::customDraw(IggyCustomDrawCallbackRegion *region) { int slotId = -1; - swscanf((wchar_t*)region->name,L"slot_%d",&slotId); + swscanf(static_cast(region->name),L"slot_%d",&slotId); if (slotId == -1) { //app.DebugPrintf("This is not the control we are looking for\n"); } else { - shared_ptr item = shared_ptr( new ItemInstance(TitleIcons[m_currentLeaderboard][slotId], 1, 0) ); + shared_ptr item = std::make_shared(TitleIcons[m_currentLeaderboard][slotId], 1, 0); customDrawSlotControl(region,m_iPad,item,1.0f,false,false); } } @@ -979,14 +979,14 @@ void UIScene_LeaderboardsMenu::customDraw(IggyCustomDrawCallbackRegion *region) void UIScene_LeaderboardsMenu::handleSelectionChanged(F64 selectedId) { ui.PlayUISFX(eSFX_Focus); - m_newSel = (int)selectedId; + m_newSel = static_cast(selectedId); updateTooltips(); } // Handle a request from Iggy for more data void UIScene_LeaderboardsMenu::handleRequestMoreData(F64 startIndex, bool up) { - unsigned int item = (int)startIndex; + unsigned int item = static_cast(startIndex); if( m_leaderboard.m_totalEntryCount > 0 && (item+1) < GetEntryStartIndex() ) { @@ -995,7 +995,7 @@ void UIScene_LeaderboardsMenu::handleRequestMoreData(F64 startIndex, bool up) int readIndex = (GetEntryStartIndex() + 1) - READ_SIZE; if( readIndex <= 0 ) readIndex = 1; - assert( readIndex >= 1 && readIndex <= (int)m_leaderboard.m_totalEntryCount ); + assert( readIndex >= 1 && readIndex <= static_cast(m_leaderboard.m_totalEntryCount)); ReadStats(readIndex); } } @@ -1004,7 +1004,7 @@ void UIScene_LeaderboardsMenu::handleRequestMoreData(F64 startIndex, bool up) if( LeaderboardManager::Instance()->isIdle() ) { int readIndex = (GetEntryStartIndex() + 1) + m_leaderboard.m_entries.size(); - assert( readIndex >= 1 && readIndex <= (int)m_leaderboard.m_totalEntryCount ); + assert( readIndex >= 1 && readIndex <= static_cast(m_leaderboard.m_totalEntryCount)); ReadStats(readIndex); } } @@ -1033,7 +1033,7 @@ void UIScene_LeaderboardsMenu::handleTimerComplete(int id) int UIScene_LeaderboardsMenu::ExitLeaderboards(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LeaderboardsMenu* pClass = (UIScene_LeaderboardsMenu*)pParam; + UIScene_LeaderboardsMenu* pClass = static_cast(pParam); pClass->navigateBack(); diff --git a/Minecraft.Client/Common/UI/UIScene_LoadMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadMenu.cpp index ed3c8137e..d61a79022 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadMenu.cpp @@ -34,7 +34,7 @@ int UIScene_LoadMenu::m_iDifficultyTitleSettingA[4]= int UIScene_LoadMenu::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) { - UIScene_LoadMenu *pClass= (UIScene_LoadMenu *)ui.GetSceneFromCallbackId((size_t)lpParam); + UIScene_LoadMenu *pClass= static_cast(ui.GetSceneFromCallbackId((size_t)lpParam)); if(pClass) { @@ -50,7 +50,7 @@ int UIScene_LoadMenu::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumb } else { - app.DebugPrintf("Thumbnail data is NULL, or has size 0\n"); + app.DebugPrintf("Thumbnail data is nullptr, or has size 0\n"); pClass->m_bThumbnailGetFailed = true; } pClass->m_bRetrievingSaveThumbnail = false; @@ -64,7 +64,7 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye // Setup all the Iggy references we need for this scene initialiseMovie(); - LoadMenuInitData *params = (LoadMenuInitData *)initData; + LoadMenuInitData *params = static_cast(initData); m_labelGameName.init(app.GetString(IDS_WORLD_NAME)); m_labelSeed.init(L""); @@ -102,7 +102,7 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye m_bSaveThumbnailReady = false; m_bRetrievingSaveThumbnail = true; m_bShowTimer = false; - m_pDLCPack = NULL; + m_pDLCPack = nullptr; m_bAvailableTexturePacksChecked=false; m_bRequestQuadrantSignin = false; m_iTexturePacksNotInstalled=0; @@ -249,7 +249,7 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye #endif #endif #ifdef _WINDOWS64 - if (params->saveDetails != NULL && params->saveDetails->UTF8SaveName[0] != '\0') + if (params->saveDetails != nullptr && params->saveDetails->UTF8SaveName[0] != '\0') { wchar_t wSaveName[128]; ZeroMemory(wSaveName, sizeof(wSaveName)); @@ -305,7 +305,7 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye if(!m_bAvailableTexturePacksChecked) #endif { - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -451,9 +451,9 @@ void UIScene_LoadMenu::tick() // #ifdef _DEBUG // // dump out the thumbnail - // HANDLE hThumbnail = CreateFile("GAME:\\thumbnail.png", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, NULL); + // HANDLE hThumbnail = CreateFile("GAME:\\thumbnail.png", GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, nullptr); // DWORD dwBytes; - // WriteFile(hThumbnail,pbImageData,dwImageBytes,&dwBytes,NULL); + // WriteFile(hThumbnail,pbImageData,dwImageBytes,&dwBytes,nullptr); // XCloseHandle(hThumbnail); // #endif @@ -477,7 +477,7 @@ void UIScene_LoadMenu::tick() m_MoreOptionsParams.bTNT = app.GetGameHostOption(uiHostOptions,eGameHostOption_TNT)>0?TRUE:FALSE; m_MoreOptionsParams.bHostPrivileges = app.GetGameHostOption(uiHostOptions,eGameHostOption_CheatsEnabled)>0?TRUE:FALSE; m_MoreOptionsParams.bDisableSaving = app.GetGameHostOption(uiHostOptions,eGameHostOption_DisableSaving)>0?TRUE:FALSE; - m_MoreOptionsParams.currentWorldSize = (EGameHostOptionWorldSize)app.GetGameHostOption(uiHostOptions,eGameHostOption_WorldSize); + m_MoreOptionsParams.currentWorldSize = static_cast(app.GetGameHostOption(uiHostOptions, eGameHostOption_WorldSize)); m_MoreOptionsParams.newWorldSize = m_MoreOptionsParams.currentWorldSize; m_MoreOptionsParams.bMobGriefing = app.GetGameHostOption(uiHostOptions, eGameHostOption_MobGriefing); @@ -696,7 +696,7 @@ void UIScene_LoadMenu::handlePress(F64 controlId, F64 childId) //CD - Added for audio ui.PlayUISFX(eSFX_Press); - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_GameMode: switch(m_iGameModeId) @@ -725,7 +725,7 @@ void UIScene_LoadMenu::handlePress(F64 controlId, F64 childId) break; case eControl_TexturePackList: { - UpdateCurrentTexturePack((int)childId); + UpdateCurrentTexturePack(static_cast(childId)); } break; case eControl_LoadWorld: @@ -771,7 +771,7 @@ void UIScene_LoadMenu::StartSharedLaunchFlow() // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack==nullptr) { #if TO_BE_IMPLEMENTED // They've selected a texture pack they don't have yet @@ -821,7 +821,7 @@ void UIScene_LoadMenu::StartSharedLaunchFlow() { // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)pTexturePack; + DLCTexturePack *pDLCTexPack=static_cast(pTexturePack); m_pDLCPack=pDLCTexPack->getDLCInfoParentPack(); // do we have a license? @@ -849,7 +849,7 @@ void UIScene_LoadMenu::StartSharedLaunchFlow() DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_pDLCPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -946,8 +946,8 @@ void UIScene_LoadMenu::StartSharedLaunchFlow() void UIScene_LoadMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_Difficulty: m_sliderDifficulty.handleSliderMove(value); @@ -1107,7 +1107,7 @@ void UIScene_LoadMenu::LaunchGame(void) // inform them that leaderboard writes and achievements will be disabled //ui.RequestMessageBox(IDS_TITLE_START_GAME, IDS_CONFIRM_START_SAVEDINCREATIVE_CONTINUE, uiIDA, 1, m_iPad,&CScene_LoadGameSettings::ConfirmLoadReturned,this,app.GetStringTable()); - if(m_levelGen != NULL) + if(m_levelGen != nullptr) { m_bIsCorrupt = false; LoadDataComplete(this); @@ -1150,7 +1150,7 @@ void UIScene_LoadMenu::LaunchGame(void) } else { - if(m_levelGen != NULL) + if(m_levelGen != nullptr) { m_bIsCorrupt = false; LoadDataComplete(this); @@ -1182,7 +1182,7 @@ void UIScene_LoadMenu::LaunchGame(void) int UIScene_LoadMenu::CheckResetNetherReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -1206,11 +1206,11 @@ int UIScene_LoadMenu::CheckResetNetherReturned(void *pParam,int iPad,C4JStorage: int UIScene_LoadMenu::ConfirmLoadReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { - if(pClass->m_levelGen != NULL) + if(pClass->m_levelGen != nullptr) { pClass->m_bIsCorrupt = false; pClass->LoadDataComplete(pClass); @@ -1246,7 +1246,7 @@ int UIScene_LoadMenu::ConfirmLoadReturned(void *pParam,int iPad,C4JStorage::EMes int UIScene_LoadMenu::LoadDataComplete(void *pParam) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); if(!pClass->m_bIsCorrupt) { @@ -1312,7 +1312,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) #if defined(__PS3__) || defined(__PSVITA__) if(isOnlineGame) { - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,nullptr,&bContentRestricted,nullptr); } #endif @@ -1362,7 +1362,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return 0; } @@ -1381,7 +1381,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) // UINT uiIDA[2]; // uiIDA[0]=IDS_PLAY_OFFLINE; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; -// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadMenu::PSPlusReturned,pClass, app.GetStringTable(),NULL,0,false); +// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadMenu::PSPlusReturned,pClass, app.GetStringTable(),nullptr,0,false); } #endif @@ -1392,7 +1392,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) if(isOnlineGame) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); @@ -1431,7 +1431,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return 0; } @@ -1450,7 +1450,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) // UINT uiIDA[2]; // uiIDA[0]=IDS_PLAY_OFFLINE; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; -// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadMenu::PSPlusReturned,pClass, app.GetStringTable(),NULL,0,false); +// ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadMenu::PSPlusReturned,pClass, app.GetStringTable(),nullptr,0,false); } #endif else @@ -1484,7 +1484,7 @@ int UIScene_LoadMenu::LoadDataComplete(void *pParam) int UIScene_LoadMenu::LoadSaveDataReturned(void *pParam,bool bIsCorrupt, bool bIsOwner) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); pClass->m_bIsCorrupt=bIsCorrupt; @@ -1520,13 +1520,13 @@ int UIScene_LoadMenu::LoadSaveDataReturned(void *pParam,bool bIsCorrupt, bool bI int UIScene_LoadMenu::TrophyDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); return LoadDataComplete(pClass); } int UIScene_LoadMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -1543,7 +1543,7 @@ int UIScene_LoadMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage: int UIScene_LoadMenu::DeleteSaveDataReturned(void *pParam,bool bSuccess) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); app.SetCorruptSaveDeleted(true); pClass->navigateBack(); @@ -1554,7 +1554,7 @@ int UIScene_LoadMenu::DeleteSaveDataReturned(void *pParam,bool bSuccess) // 4J Stu - Shared functionality that is the same whether we needed a quadrant sign-in or not void UIScene_LoadMenu::StartGameFromSave(UIScene_LoadMenu* pClass, DWORD dwLocalUsersMask) { - if(pClass->m_levelGen == NULL) + if(pClass->m_levelGen == nullptr) { INT saveOrCheckpointId = 0; bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); @@ -1582,7 +1582,7 @@ void UIScene_LoadMenu::StartGameFromSave(UIScene_LoadMenu* pClass, DWORD dwLocal NetworkGameInitData *param = new NetworkGameInitData(); param->seed = pClass->m_seed; - param->saveData = NULL; + param->saveData = nullptr; param->levelGen = pClass->m_levelGen; param->texturePackId = pClass->m_MoreOptionsParams.dwTexturePack; param->levelName = pClass->m_levelName; @@ -1642,7 +1642,7 @@ void UIScene_LoadMenu::StartGameFromSave(UIScene_LoadMenu* pClass, DWORD dwLocal LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave time app.SetAutosaveTimerTime(); @@ -1676,7 +1676,7 @@ void UIScene_LoadMenu::checkStateAndStartGame() int UIScene_LoadMenu::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - UIScene_LoadMenu* pClass = (UIScene_LoadMenu*)pParam; + UIScene_LoadMenu* pClass = static_cast(pParam); if(bContinue==true) { @@ -1779,7 +1779,7 @@ int UIScene_LoadMenu::StartGame_SignInReturned(void *pParam,bool bContinue, int if(ProfileManager.IsSignedInLive(i)) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, i ); diff --git a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp index a0498d5f9..d73148f5d 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp @@ -36,13 +36,13 @@ static wstring ReadLevelNameFromSaveFile(const wstring& filePath) if (slashPos != wstring::npos) { wstring sidecarPath = filePath.substr(0, slashPos + 1) + L"worldname.txt"; - FILE *fr = NULL; + FILE *fr = nullptr; if (_wfopen_s(&fr, sidecarPath.c_str(), L"r") == 0 && fr) { char buf[128] = {}; if (fgets(buf, sizeof(buf), fr)) { - int len = (int)strlen(buf); + int len = static_cast(strlen(buf)); while (len > 0 && (buf[len-1] == '\n' || buf[len-1] == '\r' || buf[len-1] == ' ')) buf[--len] = '\0'; fclose(fr); @@ -57,15 +57,15 @@ static wstring ReadLevelNameFromSaveFile(const wstring& filePath) } } - HANDLE hFile = CreateFileW(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); + HANDLE hFile = CreateFileW(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if (hFile == INVALID_HANDLE_VALUE) return L""; - DWORD fileSize = GetFileSize(hFile, NULL); + DWORD fileSize = GetFileSize(hFile, nullptr); if (fileSize < 12 || fileSize == INVALID_FILE_SIZE) { CloseHandle(hFile); return L""; } unsigned char *rawData = new unsigned char[fileSize]; DWORD bytesRead = 0; - if (!ReadFile(hFile, rawData, fileSize, &bytesRead, NULL) || bytesRead != fileSize) + if (!ReadFile(hFile, rawData, fileSize, &bytesRead, nullptr) || bytesRead != fileSize) { CloseHandle(hFile); delete[] rawData; @@ -73,7 +73,7 @@ static wstring ReadLevelNameFromSaveFile(const wstring& filePath) } CloseHandle(hFile); - unsigned char *saveData = NULL; + unsigned char *saveData = nullptr; unsigned int saveSize = 0; bool freeSaveData = false; @@ -120,10 +120,10 @@ static wstring ReadLevelNameFromSaveFile(const wstring& filePath) ba.data = (byte*)(saveData + off); ba.length = len; CompoundTag *root = NbtIo::decompress(ba); - if (root != NULL) + if (root != nullptr) { CompoundTag *dataTag = root->getCompound(L"Data"); - if (dataTag != NULL) + if (dataTag != nullptr) result = dataTag->getString(L"LevelName"); delete root; } @@ -172,7 +172,7 @@ C4JStorage::SAVETRANSFER_FILE_DETAILS UIScene_LoadOrJoinMenu::m_debugTransferDet int UIScene_LoadOrJoinMenu::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) { - UIScene_LoadOrJoinMenu *pClass= (UIScene_LoadOrJoinMenu *)lpParam; + UIScene_LoadOrJoinMenu *pClass= static_cast(lpParam); app.DebugPrintf("Received data for save thumbnail\n"); @@ -184,9 +184,9 @@ int UIScene_LoadOrJoinMenu::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE p } else { - pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].pbThumbnailData = NULL; + pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].pbThumbnailData = nullptr; pClass->m_saveDetails[pClass->m_iRequestingThumbnailId].dwThumbnailSize = 0; - app.DebugPrintf("Save thumbnail data is NULL, or has size 0\n"); + app.DebugPrintf("Save thumbnail data is nullptr, or has size 0\n"); } pClass->m_bSaveThumbnailReady = true; @@ -215,7 +215,7 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer m_bIgnoreInput = false; m_bShowingPartyGamesOnly = false; m_bInParty = false; - m_currentSessions = NULL; + m_currentSessions = nullptr; m_iState=e_SavesIdle; //m_bRetrievingSaveInfo=false; @@ -239,9 +239,9 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer m_bRetrievingSaveThumbnails = false; m_bSaveThumbnailReady = false; m_bExitScene=false; - m_pSaveDetails=NULL; + m_pSaveDetails=nullptr; m_bSavesDisplayed=false; - m_saveDetails = NULL; + m_saveDetails = nullptr; m_iSaveDetailsCount = 0; m_iTexturePacksNotInstalled = 0; m_bCopying = false; @@ -320,7 +320,7 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer #ifdef _XBOX // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -399,15 +399,15 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer UIScene_LoadOrJoinMenu::~UIScene_LoadOrJoinMenu() { - g_NetworkManager.SetSessionsUpdatedCallback( NULL, NULL ); + g_NetworkManager.SetSessionsUpdatedCallback( nullptr, nullptr ); app.SetLiveLinkRequired( false ); if (m_currentSessions) { - for (auto& it : *m_currentSessions) + for (const auto& it : *m_currentSessions) delete it; delete m_currentSessions; - m_currentSessions = NULL; + m_currentSessions = nullptr; } #if TO_BE_IMPLEMENTED @@ -713,7 +713,7 @@ void UIScene_LoadOrJoinMenu::tick() if(!m_bSavesDisplayed) { m_pSaveDetails=StorageManager.ReturnSavesInfo(); - if(m_pSaveDetails!=NULL) + if(m_pSaveDetails!=nullptr) { //CD - Fix - Adding define for ORBIS/XBOXONE #if defined(_XBOX_ONE) || defined(__ORBIS__) @@ -724,11 +724,11 @@ void UIScene_LoadOrJoinMenu::tick() m_bSavesDisplayed=true; UpdateGamesList(); - if(m_saveDetails!=NULL) + if(m_saveDetails!=nullptr) { for(unsigned int i = 0; i < m_iSaveDetailsCount; ++i) { - if(m_saveDetails[i].pbThumbnailData!=NULL) + if(m_saveDetails[i].pbThumbnailData!=nullptr) { delete m_saveDetails[i].pbThumbnailData; } @@ -1008,9 +1008,9 @@ void UIScene_LoadOrJoinMenu::GetSaveInfo() #ifdef __ORBIS__ // We need to make sure this is non-null so that we have an idea of free space m_pSaveDetails=StorageManager.ReturnSavesInfo(); - if(m_pSaveDetails==NULL) + if(m_pSaveDetails==nullptr) { - C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); + C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,nullptr,this,"save"); } #endif @@ -1023,7 +1023,7 @@ void UIScene_LoadOrJoinMenu::GetSaveInfo() if( savesDir.exists() ) { m_saves = savesDir.listFiles(); - uiSaveC = (unsigned int)m_saves->size(); + uiSaveC = static_cast(m_saves->size()); } // add the New Game and Tutorial after the saves list is retrieved, if there are any saves @@ -1057,9 +1057,9 @@ void UIScene_LoadOrJoinMenu::GetSaveInfo() m_controlSavesTimer.setVisible(true); m_pSaveDetails=StorageManager.ReturnSavesInfo(); - if(m_pSaveDetails==NULL) + if(m_pSaveDetails==nullptr) { - C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); + C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad, nullptr,this,"save"); } #if TO_BE_IMPLEMENTED @@ -1398,7 +1398,7 @@ void UIScene_LoadOrJoinMenu::handleInput(int iPad, int key, bool repeat, bool pr int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,bool bRes) { // 4J HEG - No reason to set value if keyboard was cancelled - UIScene_LoadOrJoinMenu *pClass=(UIScene_LoadOrJoinMenu *)lpParam; + UIScene_LoadOrJoinMenu *pClass=static_cast(lpParam); pClass->m_bIgnoreInput=false; if (bRes) { @@ -1423,7 +1423,7 @@ int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,boo // Convert the ui16Text input to a wide string wchar_t wNewName[128] = {}; for (int k = 0; k < 127 && ui16Text[k]; k++) - wNewName[k] = (wchar_t)ui16Text[k]; + wNewName[k] = static_cast(ui16Text[k]); // Convert to narrow for storage and in-memory update char narrowName[128] = {}; @@ -1434,7 +1434,7 @@ int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,boo mbstowcs(wFilename, pClass->m_saveDetails[listPos].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH - 1); wstring sidecarPath = wstring(L"Windows64\\GameHDD\\") + wstring(wFilename) + wstring(L"\\worldname.txt"); - FILE *fw = NULL; + FILE *fw = nullptr; if (_wfopen_s(&fw, sidecarPath.c_str(), L"w") == 0 && fw) { fputs(narrowName, fw); @@ -1467,14 +1467,14 @@ int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,boo } void UIScene_LoadOrJoinMenu::handleInitFocus(F64 controlId, F64 childId) { - app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleInitFocus - %d , %d\n", (int)controlId, (int)childId); + app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleInitFocus - %d , %d\n", static_cast(controlId), static_cast(childId)); } void UIScene_LoadOrJoinMenu::handleFocusChange(F64 controlId, F64 childId) { - app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleFocusChange - %d , %d\n", (int)controlId, (int)childId); + app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleFocusChange - %d , %d\n", static_cast(controlId), static_cast(childId)); - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_GamesList: m_iGameListIndex = childId; @@ -1482,7 +1482,7 @@ void UIScene_LoadOrJoinMenu::handleFocusChange(F64 controlId, F64 childId) // Offset past the "Add Server" button so m_iGameListIndex is a session index m_iGameListIndex -= 1; #endif - m_buttonListGames.updateChildFocus( (int) childId ); + m_buttonListGames.updateChildFocus( static_cast(childId) ); break; case eControl_SavesList: m_iSaveListIndex = childId; @@ -1504,18 +1504,18 @@ void UIScene_LoadOrJoinMenu::remoteStorageGetSaveCallback(LPVOID lpParam, SonyRe void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_SavesList: { m_bIgnoreInput=true; - int lGenID = (int)childId - 1; + int lGenID = static_cast(childId) - 1; //CD - Added for audio ui.PlayUISFX(eSFX_Press); - if((int)childId == JOIN_LOAD_CREATE_BUTTON_INDEX) + if(static_cast(childId) == JOIN_LOAD_CREATE_BUTTON_INDEX) { app.SetTutorialMode( false ); @@ -1546,7 +1546,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) params->iSaveGameInfoIndex=-1; //params->pbSaveRenamed=&m_bSaveRenamed; params->levelGen = levelGen; - params->saveDetails = NULL; + params->saveDetails = nullptr; // navigate to the settings scene ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_LoadMenu, params); @@ -1557,7 +1557,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) #ifdef __ORBIS__ // check if this is a damaged save PSAVE_INFO pSaveInfo = &m_pSaveDetails->SaveInfoA[((int)childId)-m_iDefaultButtonsC]; - if(pSaveInfo->thumbnailData == NULL && pSaveInfo->modifiedTime == 0) // no thumbnail data and time of zero and zero blocks useset for corrupt files + if(pSaveInfo->thumbnailData == nullptr && pSaveInfo->modifiedTime == 0) // no thumbnail data and time of zero and zero blocks useset for corrupt files { // give the option to delete the save UINT uiIDA[2]; @@ -1573,17 +1573,17 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) if(app.DebugSettingsOn() && app.GetLoadSavesFromFolderEnabled()) { - LoadSaveFromDisk(m_saves->at((int)childId-m_iDefaultButtonsC)); + LoadSaveFromDisk(m_saves->at(static_cast(childId)-m_iDefaultButtonsC)); } else { LoadMenuInitData *params = new LoadMenuInitData(); params->iPad = m_iPad; // need to get the iIndex from the list item, since the position in the list doesn't correspond to the GetSaveGameInfo list because of sorting - params->iSaveGameInfoIndex=m_saveDetails[((int)childId)-m_iDefaultButtonsC].saveId; + params->iSaveGameInfoIndex=m_saveDetails[static_cast(childId)-m_iDefaultButtonsC].saveId; //params->pbSaveRenamed=&m_bSaveRenamed; - params->levelGen = NULL; - params->saveDetails = &m_saveDetails[ ((int)childId)-m_iDefaultButtonsC ]; + params->levelGen = nullptr; + params->saveDetails = &m_saveDetails[ static_cast(childId)-m_iDefaultButtonsC ]; #ifdef _XBOX_ONE // On XB1, saves might need syncing, in which case inform the user so they can decide whether they want to wait for this to happen @@ -1610,7 +1610,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) case eControl_GamesList: { #ifdef _WINDOWS64 - if ((int)childId == ADD_SERVER_BUTTON_INDEX) + if (static_cast(childId) == ADD_SERVER_BUTTON_INDEX) { ui.PlayUISFX(eSFX_Press); BeginAddServer(); @@ -1625,7 +1625,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) ui.PlayUISFX(eSFX_Press); { - int nIndex = (int)childId; + int nIndex = static_cast(childId); #ifdef _WINDOWS64 // Offset by 1 because the "Add Server" button is at index 0 nIndex -= 1; @@ -1649,7 +1649,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) bool bContentRestricted=false; // we're online, since we are joining a game - ProfileManager.GetChatAndContentRestrictions(m_iPad,true,&noUGC,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(m_iPad,true,&noUGC,&bContentRestricted,nullptr); #ifdef __ORBIS__ // 4J Stu - On PS4 we don't restrict playing multiplayer based on chat restriction, so remove this check @@ -1693,7 +1693,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; // Not allowed to play online - ui.RequestAlertMessage(IDS_ONLINE_GAME, IDS_CHAT_RESTRICTION_UGC, uiIDA, 1, m_iPad,NULL,this); + ui.RequestAlertMessage(IDS_ONLINE_GAME, IDS_CHAT_RESTRICTION_UGC, uiIDA, 1, m_iPad,nullptr,this); #else // Not allowed to play online ProfileManager.ShowSystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, 0 ); @@ -1738,7 +1738,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) // MGH - added this so we don't try and upsell when we don't know if the player has PS Plus yet (if it can't connect to the PS Plus server). UINT uiIDA[1]; uiIDA[0]=IDS_OK; - ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL); + ui.RequestAlertMessage(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr); return; } @@ -1758,7 +1758,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) // UINT uiIDA[2]; // uiIDA[0]=IDS_CONFIRM_OK; // uiIDA[1]=IDS_PLAYSTATIONPLUS_SIGNUP; - // ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadOrJoinMenu::PSPlusReturned,this, app.GetStringTable(),NULL,0,false); + // ui.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA,2,ProfileManager.GetPrimaryPad(),&UIScene_LoadOrJoinMenu::PSPlusReturned,this, app.GetStringTable(),nullptr,0,false); m_bIgnoreInput=false; return; @@ -1783,11 +1783,11 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) fread(&version, sizeof(uint32_t), 1, dbFile); fread(&count, sizeof(uint32_t), 1, dbFile); if (version == 1) - serverDbCount = (int)count; + serverDbCount = static_cast(count); } fclose(dbFile); } - int lanCount = (int)m_currentSessions->size() - serverDbCount; + int lanCount = static_cast(m_currentSessions->size()) - serverDbCount; if (gameIndex >= lanCount && lanCount >= 0) m_initData->serverIndex = gameIndex - lanCount; else @@ -1878,7 +1878,7 @@ void UIScene_LoadOrJoinMenu::LoadLevelGen(LevelGenerationOptions *levelGen) NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->settings = app.GetGameHostOption( eGameHostOption_Tutorial ); param->levelGen = levelGen; @@ -1897,7 +1897,7 @@ void UIScene_LoadOrJoinMenu::LoadLevelGen(LevelGenerationOptions *levelGen) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1911,9 +1911,9 @@ void UIScene_LoadOrJoinMenu::LoadLevelGen(LevelGenerationOptions *levelGen) void UIScene_LoadOrJoinMenu::UpdateGamesListCallback(LPVOID pParam) { - if(pParam != NULL) + if(pParam != nullptr) { - UIScene_LoadOrJoinMenu *pScene = (UIScene_LoadOrJoinMenu *)pParam; + UIScene_LoadOrJoinMenu *pScene = static_cast(pParam); pScene->UpdateGamesList(); } } @@ -1933,7 +1933,7 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() } - FriendSessionInfo *pSelectedSession = NULL; + FriendSessionInfo *pSelectedSession = nullptr; if(DoesGamesListHaveFocus() && m_buttonListGames.getItemCount() > 0) { unsigned int nIndex = m_buttonListGames.getCurrentSelection(); @@ -1948,8 +1948,8 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() SessionID selectedSessionId; ZeroMemory(&selectedSessionId,sizeof(SessionID)); - if( pSelectedSession != NULL )selectedSessionId = pSelectedSession->sessionId; - pSelectedSession = NULL; + if( pSelectedSession != nullptr )selectedSessionId = pSelectedSession->sessionId; + pSelectedSession = nullptr; m_controlJoinTimer.setVisible( false ); @@ -1993,7 +1993,7 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() // Update the xui list displayed unsigned int xuiListSize = m_buttonListGames.getItemCount(); - unsigned int filteredListSize = (unsigned int)m_currentSessions->size(); + unsigned int filteredListSize = static_cast(m_currentSessions->size()); BOOL gamesListHasFocus = DoesGamesListHaveFocus(); @@ -2049,12 +2049,12 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() HRESULT hr; DWORD dwImageBytes=0; - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; - if(tp==NULL) + if(tp==nullptr) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; app.GetTPD(sessionInfo->data.texturePackParentId,&pbData,&dwBytes); // is it in the tpd data ? @@ -2260,7 +2260,7 @@ void UIScene_LoadOrJoinMenu::LoadSaveFromDisk(File *saveFile, ESavePlatform save int64_t fileSize = saveFile->length(); FileInputStream fis(*saveFile); - byteArray ba(fileSize); + byteArray ba(static_cast(fileSize)); fis.read(ba); fis.close(); @@ -2294,7 +2294,7 @@ void UIScene_LoadOrJoinMenu::LoadSaveFromDisk(File *saveFile, ESavePlatform save LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -2400,7 +2400,7 @@ static bool Win64_DeleteSaveDirectory(const wchar_t* wPath) int UIScene_LoadOrJoinMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; + UIScene_LoadOrJoinMenu* pClass = static_cast(pParam); // results switched for this dialog // Check that we have a valid save selected (can get a bad index if the save list has been refreshed) @@ -2422,7 +2422,7 @@ int UIScene_LoadOrJoinMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JSt if (pClass->m_saveDetails && displayIdx >= 0 && pClass->m_saveDetails[displayIdx].UTF8SaveFilename[0]) { wchar_t wFilename[MAX_SAVEFILENAME_LENGTH] = {}; - mbstowcs_s(NULL, wFilename, MAX_SAVEFILENAME_LENGTH, pClass->m_saveDetails[displayIdx].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH - 1); + mbstowcs_s(nullptr, wFilename, MAX_SAVEFILENAME_LENGTH, pClass->m_saveDetails[displayIdx].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH - 1); wchar_t wFolderPath[MAX_PATH] = {}; swprintf_s(wFolderPath, MAX_PATH, L"Windows64\\GameHDD\\%s", wFilename); bSuccess = Win64_DeleteSaveDirectory(wFolderPath); @@ -2446,7 +2446,7 @@ int UIScene_LoadOrJoinMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JSt int UIScene_LoadOrJoinMenu::DeleteSaveDataReturned(LPVOID lpParam,bool bRes) { ui.EnterCallbackIdCriticalSection(); - UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)ui.GetSceneFromCallbackId((size_t)lpParam); + UIScene_LoadOrJoinMenu* pClass = static_cast(ui.GetSceneFromCallbackId((size_t)lpParam)); if(pClass) { @@ -2466,7 +2466,7 @@ int UIScene_LoadOrJoinMenu::DeleteSaveDataReturned(LPVOID lpParam,bool bRes) int UIScene_LoadOrJoinMenu::RenameSaveDataReturned(LPVOID lpParam,bool bRes) { - UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)lpParam; + UIScene_LoadOrJoinMenu* pClass = static_cast(lpParam); if(bRes) { @@ -2498,7 +2498,7 @@ void UIScene_LoadOrJoinMenu::LoadRemoteFileFromDisk(char* remoteFilename) int UIScene_LoadOrJoinMenu::SaveOptionsDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; + UIScene_LoadOrJoinMenu* pClass = static_cast(pParam); // results switched for this dialog // EMessage_ResultAccept means cancel @@ -2511,7 +2511,7 @@ int UIScene_LoadOrJoinMenu::SaveOptionsDialogReturned(void *pParam,int iPad,C4JS { wchar_t wSaveName[128]; ZeroMemory(wSaveName, 128 * sizeof(wchar_t)); - mbstowcs_s(NULL, wSaveName, 128, pClass->m_saveDetails[pClass->m_iSaveListIndex - pClass->m_iDefaultButtonsC].UTF8SaveName, _TRUNCATE); + mbstowcs_s(nullptr, wSaveName, 128, pClass->m_saveDetails[pClass->m_iSaveListIndex - pClass->m_iDefaultButtonsC].UTF8SaveName, _TRUNCATE); UIKeyboardInitData kbData; kbData.title = app.GetString(IDS_RENAME_WORLD_TITLE); kbData.defaultText = wSaveName; @@ -2628,7 +2628,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack(void *pParam,bool bCon if(bContinue==true) { SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chKeyName[20]; @@ -2637,7 +2637,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack(void *pParam,bool bCon memset(chSkuID,0,SCE_NP_COMMERCE2_SKU_ID_LEN); // we have to retrieve the skuid from the store info, it can't be hardcoded since Sony may change it. // So we assume the first sku for the product is the one we want - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char + // MGH - keyname in the DLC file is 16 chars long, but there's no space for a nullptr terminating char memset(chKeyName, 0, sizeof(chKeyName)); strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); @@ -2669,7 +2669,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack(void *pParam,bool bCon int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_LoadOrJoinMenu *pClass = (UIScene_LoadOrJoinMenu *)pParam; + UIScene_LoadOrJoinMenu *pClass = static_cast(pParam); // Exit with or without saving if(result==C4JStorage::EMessage_ResultAccept) @@ -2691,7 +2691,7 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS #endif SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chKeyName[20]; @@ -2700,7 +2700,7 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS memset(chSkuID,0,SCE_NP_COMMERCE2_SKU_ID_LEN); // we have to retrieve the skuid from the store info, it can't be hardcoded since Sony may change it. // So we assume the first sku for the product is the one we want - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char + // MGH - keyname in the DLC file is 16 chars long, but there's no space for a nullptr terminating char memset(chKeyName, 0, sizeof(chKeyName)); strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); @@ -2734,7 +2734,7 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS wstring ProductId; app.GetDLCFullOfferIDForPackID(pClass->m_initData->selectedSession->data.texturePackParentId,ProductId); - StorageManager.InstallOffer(1,(WCHAR *)ProductId.c_str(),NULL,NULL); + StorageManager.InstallOffer(1,(WCHAR *)ProductId.c_str(),nullptr,nullptr); } else { @@ -2926,7 +2926,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter pMinecraft->progressRenderer->progressStart(IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD); pMinecraft->progressRenderer->progressStage( IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD ); - ConsoleSaveFile* pSave = NULL; + ConsoleSaveFile* pSave = nullptr; pClass->m_eSaveTransferState = eSaveTransfer_GetRemoteSaveInfo; @@ -2981,10 +2981,10 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter const char* pNameUTF8 = app.getRemoteStorage()->getSaveNameUTF8(); mbstowcs(wSaveName, pNameUTF8, strlen(pNameUTF8)+1); // plus null StorageManager.SetSaveTitle(wSaveName); - PBYTE pbThumbnailData=NULL; + PBYTE pbThumbnailData=nullptr; DWORD dwThumbnailDataSize=0; - PBYTE pbDataSaveImage=NULL; + PBYTE pbDataSaveImage=nullptr; DWORD dwDataSizeSaveImage=0; StorageManager.GetDefaultSaveImage(&pbDataSaveImage, &dwDataSizeSaveImage); // Get the default save thumbnail (as set by SetDefaultImages) for use on saving games t @@ -3145,10 +3145,10 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter StorageManager.ResetSaveData(); { - PBYTE pbThumbnailData=NULL; + PBYTE pbThumbnailData=nullptr; DWORD dwThumbnailDataSize=0; - PBYTE pbDataSaveImage=NULL; + PBYTE pbDataSaveImage=nullptr; DWORD dwDataSizeSaveImage=0; StorageManager.GetDefaultSaveImage(&pbDataSaveImage, &dwDataSizeSaveImage); // Get the default save thumbnail (as set by SetDefaultImages) for use on saving games t @@ -3356,7 +3356,7 @@ void UIScene_LoadOrJoinMenu::SaveTransferReturned(LPVOID lpParam, SonyRemoteStor } ConsoleSaveFile* UIScene_LoadOrJoinMenu::SonyCrossSaveConvert() { - return NULL; + return nullptr; } void UIScene_LoadOrJoinMenu::CancelSaveTransferCallback(LPVOID lpParam) @@ -3579,7 +3579,7 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) SaveTransferStateContainer *pStateContainer = (SaveTransferStateContainer *) lpParameter; Minecraft *pMinecraft=Minecraft::GetInstance(); - ConsoleSaveFile* pSave = NULL; + ConsoleSaveFile* pSave = nullptr; while(StorageManager.SaveTransferClearState()!=C4JStorage::eSaveTransfer_Idle) { @@ -3681,7 +3681,7 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) int iTextMetadataBytes = app.CreateImageTextData(bTextMetadata, seedVal, true, uiHostOptions, dwTexturePack); // set the icon and save image - StorageManager.SetSaveImages(ba.data, ba.length, NULL, 0, bTextMetadata, iTextMetadataBytes); + StorageManager.SetSaveImages(ba.data, ba.length, nullptr, 0, bTextMetadata, iTextMetadataBytes); delete ba.data; } @@ -3844,12 +3844,12 @@ void UIScene_LoadOrJoinMenu::RequestFileData( SaveTransferStateContainer *pClass File targetFile( wstring(L"FakeTMSPP\\").append(filename) ); if(targetFile.exists()) { - HANDLE hSaveFile = CreateFile( targetFile.getPath().c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL); + HANDLE hSaveFile = CreateFile( targetFile.getPath().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, nullptr); m_debugTransferDetails.pbData = new BYTE[m_debugTransferDetails.ulFileLen]; DWORD numberOfBytesRead = 0; - ReadFile( hSaveFile,m_debugTransferDetails.pbData,m_debugTransferDetails.ulFileLen,&numberOfBytesRead,NULL); + ReadFile( hSaveFile,m_debugTransferDetails.pbData,m_debugTransferDetails.ulFileLen,&numberOfBytesRead,nullptr); assert(numberOfBytesRead == m_debugTransferDetails.ulFileLen); CloseHandle(hSaveFile); @@ -3877,7 +3877,7 @@ int UIScene_LoadOrJoinMenu::SaveTransferReturned(LPVOID lpParam,C4JStorage::SAVE app.DebugPrintf("Save Transfer - size is %d\n",pSaveTransferDetails->ulFileLen); // if the file data is null, then assume this is the file size retrieval - if(pSaveTransferDetails->pbData==NULL) + if(pSaveTransferDetails->pbData==nullptr) { pClass->m_eSaveTransferState=C4JStorage::eSaveTransfer_FileSizeRetrieved; UIScene_LoadOrJoinMenu::s_ulFileSize=pSaveTransferDetails->ulFileLen; @@ -4158,7 +4158,7 @@ void UIScene_LoadOrJoinMenu::BeginAddServer() int UIScene_LoadOrJoinMenu::AddServerKeyboardCallback(LPVOID lpParam, bool bRes) { - UIScene_LoadOrJoinMenu *pClass = (UIScene_LoadOrJoinMenu *)lpParam; + UIScene_LoadOrJoinMenu *pClass = static_cast(lpParam); if (!bRes) { @@ -4173,7 +4173,7 @@ int UIScene_LoadOrJoinMenu::AddServerKeyboardCallback(LPVOID lpParam, bool bRes) wchar_t wBuf[256] = {}; for (int k = 0; k < 255 && ui16Text[k]; k++) - wBuf[k] = (wchar_t)ui16Text[k]; + wBuf[k] = static_cast(ui16Text[k]); if (wBuf[0] == 0) { @@ -4242,7 +4242,7 @@ void UIScene_LoadOrJoinMenu::AppendServerToFile(const wstring& ip, const wstring wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1); wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1); - uint16_t portNum = (uint16_t)atoi(narrowPort); + uint16_t portNum = static_cast(atoi(narrowPort)); struct ServerEntry { std::string ip; uint16_t port; std::string name; }; std::vector entries; @@ -4284,17 +4284,17 @@ void UIScene_LoadOrJoinMenu::AppendServerToFile(const wstring& ip, const wstring { fwrite("MCSV", 1, 4, file); uint32_t version = 1; - uint32_t count = (uint32_t)entries.size(); + uint32_t count = static_cast(entries.size()); fwrite(&version, sizeof(uint32_t), 1, file); fwrite(&count, sizeof(uint32_t), 1, file); for (size_t i = 0; i < entries.size(); i++) { - uint16_t ipLen = (uint16_t)entries[i].ip.length(); + uint16_t ipLen = static_cast(entries[i].ip.length()); fwrite(&ipLen, sizeof(uint16_t), 1, file); fwrite(entries[i].ip.c_str(), 1, ipLen, file); fwrite(&entries[i].port, sizeof(uint16_t), 1, file); - uint16_t nameLen = (uint16_t)entries[i].name.length(); + uint16_t nameLen = static_cast(entries[i].name.length()); fwrite(&nameLen, sizeof(uint16_t), 1, file); fwrite(entries[i].name.c_str(), 1, nameLen, file); } diff --git a/Minecraft.Client/Common/UI/UIScene_MainMenu.cpp b/Minecraft.Client/Common/UI/UIScene_MainMenu.cpp index fe743adc2..93f1edf11 100644 --- a/Minecraft.Client/Common/UI/UIScene_MainMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_MainMenu.cpp @@ -12,7 +12,7 @@ Random *UIScene_MainMenu::random = new Random(); -EUIScene UIScene_MainMenu::eNavigateWhenReady = (EUIScene) -1; +EUIScene UIScene_MainMenu::eNavigateWhenReady = static_cast(-1); UIScene_MainMenu::UIScene_MainMenu(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { @@ -33,29 +33,29 @@ UIScene_MainMenu::UIScene_MainMenu(int iPad, void *initData, UILayer *parentLaye m_bIgnorePress=false; - m_buttons[(int)eControl_PlayGame].init(IDS_PLAY_GAME,eControl_PlayGame); + m_buttons[static_cast(eControl_PlayGame)].init(IDS_PLAY_GAME,eControl_PlayGame); #ifdef _XBOX_ONE if(!ProfileManager.IsFullVersion()) m_buttons[(int)eControl_PlayGame].setLabel(IDS_PLAY_TRIAL_GAME); app.SetReachedMainMenu(); #endif - m_buttons[(int)eControl_Leaderboards].init(IDS_LEADERBOARDS,eControl_Leaderboards); - m_buttons[(int)eControl_Achievements].init( (UIString)IDS_ACHIEVEMENTS,eControl_Achievements); - m_buttons[(int)eControl_HelpAndOptions].init(IDS_HELP_AND_OPTIONS,eControl_HelpAndOptions); + m_buttons[static_cast(eControl_Leaderboards)].init(IDS_LEADERBOARDS,eControl_Leaderboards); + m_buttons[static_cast(eControl_Achievements)].init( (UIString)IDS_ACHIEVEMENTS,eControl_Achievements); + m_buttons[static_cast(eControl_HelpAndOptions)].init(IDS_HELP_AND_OPTIONS,eControl_HelpAndOptions); if(ProfileManager.IsFullVersion()) { m_bTrialVersion=false; - m_buttons[(int)eControl_UnlockOrDLC].init(IDS_DOWNLOADABLECONTENT,eControl_UnlockOrDLC); + m_buttons[static_cast(eControl_UnlockOrDLC)].init(IDS_DOWNLOADABLECONTENT,eControl_UnlockOrDLC); } else { m_bTrialVersion=true; - m_buttons[(int)eControl_UnlockOrDLC].init(IDS_UNLOCK_FULL_GAME,eControl_UnlockOrDLC); + m_buttons[static_cast(eControl_UnlockOrDLC)].init(IDS_UNLOCK_FULL_GAME,eControl_UnlockOrDLC); } #ifndef _DURANGO - m_buttons[(int)eControl_Exit].init(app.GetString(IDS_EXIT_GAME),eControl_Exit); + m_buttons[static_cast(eControl_Exit)].init(app.GetString(IDS_EXIT_GAME),eControl_Exit); #else m_buttons[(int)eControl_XboxHelp].init(IDS_XBOX_HELP_APP, eControl_XboxHelp); #endif @@ -104,7 +104,7 @@ UIScene_MainMenu::UIScene_MainMenu(int iPad, void *initData, UILayer *parentLaye m_bLoadTrialOnNetworkManagerReady = false; // 4J Stu - Clear out any loaded game rules - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // 4J Stu - Reset the leaving game flag so that we correctly handle signouts while in the menus g_NetworkManager.ResetLeavingGame(); @@ -182,7 +182,7 @@ void UIScene_MainMenu::handleGainFocus(bool navBack) if(navBack && ProfileManager.IsFullVersion()) { // Replace the Unlock Full Game with Downloadable Content - m_buttons[(int)eControl_UnlockOrDLC].setLabel(IDS_DOWNLOADABLECONTENT); + m_buttons[static_cast(eControl_UnlockOrDLC)].setLabel(IDS_DOWNLOADABLECONTENT); } #if TO_BE_IMPLEMENTED @@ -196,7 +196,7 @@ void UIScene_MainMenu::handleGainFocus(bool navBack) #ifdef __PSVITA__ int splashIndex = eSplashRandomStart + 2 + random->nextInt( (int)m_splashes.size() - (eSplashRandomStart + 2) ); #else - int splashIndex = eSplashRandomStart + 1 + random->nextInt( (int)m_splashes.size() - (eSplashRandomStart + 1) ); + int splashIndex = eSplashRandomStart + 1 + random->nextInt( static_cast(m_splashes.size()) - (eSplashRandomStart + 1) ); #endif // Override splash text on certain dates @@ -303,12 +303,12 @@ void UIScene_MainMenu::handlePress(F64 controlId, F64 childId) int primaryPad = ProfileManager.GetPrimaryPad(); #ifdef _XBOX_ONE - int (*signInReturnedFunc) (LPVOID,const bool, const int iPad, const int iController) = NULL; + int (*signInReturnedFunc) (LPVOID,const bool, const int iPad, const int iController) = nullptr; #else - int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = NULL; + int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = nullptr; #endif - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_PlayGame: #ifdef __ORBIS__ @@ -368,7 +368,7 @@ void UIScene_MainMenu::handlePress(F64 controlId, F64 childId) UINT uiIDA[2]; uiIDA[0]=IDS_CANCEL; uiIDA[1]=IDS_OK; - ui.RequestErrorMessage(IDS_WARNING_ARCADE_TITLE, IDS_WARNING_ARCADE_TEXT, uiIDA, 2, XUSER_INDEX_ANY,&UIScene_MainMenu::ExitGameReturned,this); + ui.RequestErrorMessage(IDS_WINDOWS_EXIT, IDS_WARNING_ARCADE_TEXT, uiIDA, 2, XUSER_INDEX_ANY,&UIScene_MainMenu::ExitGameReturned,this); } else { @@ -396,7 +396,7 @@ void UIScene_MainMenu::handlePress(F64 controlId, F64 childId) bool confirmUser = false; // Note: if no sign in returned func, assume this isn't required - if (signInReturnedFunc != NULL) + if (signInReturnedFunc != nullptr) { if(ProfileManager.IsSignedIn(primaryPad)) { @@ -466,10 +466,10 @@ void UIScene_MainMenu::customDrawSplash(IggyCustomDrawCallbackRegion *region) // 4J Stu - Move this to the ctor when the main menu is not the first scene we navigate to ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); // Setup GDraw, normal game render states and matrices @@ -513,7 +513,7 @@ void UIScene_MainMenu::customDrawSplash(IggyCustomDrawCallbackRegion *region) int UIScene_MainMenu::MustSignInReturned(void *pParam, int iPad, C4JStorage::EMessageResult result) { - UIScene_MainMenu* pClass = (UIScene_MainMenu*)pParam; + UIScene_MainMenu* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -643,7 +643,7 @@ int UIScene_MainMenu::HelpAndOptions_SignInReturned(void *pParam,bool bContinue, int UIScene_MainMenu::HelpAndOptions_SignInReturned(void *pParam,bool bContinue,int iPad) #endif { - UIScene_MainMenu *pClass = (UIScene_MainMenu *)pParam; + UIScene_MainMenu *pClass = static_cast(pParam); if(bContinue) { @@ -714,7 +714,7 @@ int UIScene_MainMenu::CreateLoad_SignInReturned(void *pParam, bool bContinue, in int UIScene_MainMenu::CreateLoad_SignInReturned(void *pParam, bool bContinue, int iPad) #endif { - UIScene_MainMenu* pClass = (UIScene_MainMenu*)pParam; + UIScene_MainMenu* pClass = static_cast(pParam); if(bContinue) { @@ -916,7 +916,7 @@ int UIScene_MainMenu::Leaderboards_SignInReturned(void *pParam,bool bContinue,in int UIScene_MainMenu::Leaderboards_SignInReturned(void *pParam,bool bContinue,int iPad) #endif { - UIScene_MainMenu *pClass = (UIScene_MainMenu *)pParam; + UIScene_MainMenu *pClass = static_cast(pParam); if(bContinue) { @@ -940,7 +940,7 @@ int UIScene_MainMenu::Leaderboards_SignInReturned(void *pParam,bool bContinue,in { bool bContentRestricted=false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); #endif if(bContentRestricted) { @@ -986,7 +986,7 @@ int UIScene_MainMenu::Achievements_SignInReturned(void *pParam,bool bContinue,in int UIScene_MainMenu::Achievements_SignInReturned(void *pParam,bool bContinue,int iPad) #endif { - UIScene_MainMenu *pClass = (UIScene_MainMenu *)pParam; + UIScene_MainMenu *pClass = static_cast(pParam); if (bContinue) { @@ -1020,7 +1020,7 @@ int UIScene_MainMenu::UnlockFullGame_SignInReturned(void *pParam,bool bContinue, int UIScene_MainMenu::UnlockFullGame_SignInReturned(void *pParam,bool bContinue,int iPad) #endif { - UIScene_MainMenu* pClass = (UIScene_MainMenu*)pParam; + UIScene_MainMenu* pClass = static_cast(pParam); if (bContinue) { @@ -1098,7 +1098,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_PlayGame(void * UIScene_MainMenu* pClass = (UIScene_MainMenu*)pParam; - int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = NULL; + int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = nullptr; // 4J-PB - Check if there is a patch for the game pClass->m_errorCode = ProfileManager.getNPAvailability(ProfileManager.GetPrimaryPad()); @@ -1141,7 +1141,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_PlayGame(void * // UINT uiIDA[1]; // uiIDA[0]=IDS_OK; -// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,NULL,pClass); +// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,nullptr,pClass); } // Check if PSN is unavailable because of age restriction @@ -1157,7 +1157,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_PlayGame(void * bool confirmUser = false; // Note: if no sign in returned func, assume this isn't required - if (signInReturnedFunc != NULL) + if (signInReturnedFunc != nullptr) { if(ProfileManager.IsSignedIn(primaryPad)) { @@ -1187,7 +1187,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_Leaderboards(vo UIScene_MainMenu* pClass = (UIScene_MainMenu*)pParam; - int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = NULL; + int (*signInReturnedFunc) (LPVOID,const bool, const int iPad) = nullptr; // 4J-PB - Check if there is a patch for the game pClass->m_errorCode = ProfileManager.getNPAvailability(ProfileManager.GetPrimaryPad()); @@ -1228,7 +1228,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_Leaderboards(vo // UINT uiIDA[1]; // uiIDA[0]=IDS_OK; -// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,NULL,pClass); +// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,nullptr,pClass); } bool confirmUser = false; @@ -1247,7 +1247,7 @@ void UIScene_MainMenu::RefreshChatAndContentRestrictionsReturned_Leaderboards(vo } // Note: if no sign in returned func, assume this isn't required - if (signInReturnedFunc != NULL) + if (signInReturnedFunc != nullptr) { if(ProfileManager.IsSignedIn(primaryPad)) { @@ -1600,7 +1600,7 @@ void UIScene_MainMenu::RunLeaderboards(int iPad) bool bContentRestricted=false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); #endif if(bContentRestricted) { @@ -1608,7 +1608,7 @@ void UIScene_MainMenu::RunLeaderboards(int iPad) // you can't see leaderboards UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, ProfileManager.GetPrimaryPad(),NULL,this); + ui.RequestErrorMessage(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, ProfileManager.GetPrimaryPad(),nullptr,this); #endif } else @@ -1669,7 +1669,7 @@ void UIScene_MainMenu::RunUnlockOrDLC(int iPad) // UINT uiIDA[1]; // uiIDA[0]=IDS_OK; -// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,NULL,this); +// ui.RequestMessageBox(IDS_PATCH_AVAILABLE_TITLE, IDS_PATCH_AVAILABLE_TEXT, uiIDA, 1, XUSER_INDEX_ANY,nullptr,this); return; } @@ -1704,7 +1704,7 @@ void UIScene_MainMenu::RunUnlockOrDLC(int iPad) { bool bContentRestricted=false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); #endif if(bContentRestricted) { @@ -1713,7 +1713,7 @@ void UIScene_MainMenu::RunUnlockOrDLC(int iPad) // you can't see the store UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, ProfileManager.GetPrimaryPad(),NULL,this); + ui.RequestErrorMessage(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, ProfileManager.GetPrimaryPad(),nullptr,this); #endif } else @@ -1898,7 +1898,7 @@ void UIScene_MainMenu::tick() { app.DebugPrintf("[MainMenu] Navigating away from MainMenu.\n"); ui.NavigateToScene(lockedProfile, eNavigateWhenReady); - eNavigateWhenReady = (EUIScene) -1; + eNavigateWhenReady = static_cast(-1); } #ifdef _DURANGO else @@ -1925,7 +1925,7 @@ void UIScene_MainMenu::tick() // 4J-PB - need to check this user can access the store bool bContentRestricted=false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -2102,7 +2102,7 @@ void UIScene_MainMenu::LoadTrial(void) NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->settings = app.GetGameHostOption( eGameHostOption_Tutorial ) | app.GetGameHostOption(eGameHostOption_DisableSaving); vector *generators = app.getLevelGenerators(); @@ -2110,7 +2110,7 @@ void UIScene_MainMenu::LoadTrial(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -2129,7 +2129,7 @@ void UIScene_MainMenu::LoadTrial(void) void UIScene_MainMenu::handleUnlockFullVersion() { - m_buttons[(int)eControl_UnlockOrDLC].setLabel(IDS_DOWNLOADABLECONTENT,true); + m_buttons[static_cast(eControl_UnlockOrDLC)].setLabel(IDS_DOWNLOADABLECONTENT,true); } diff --git a/Minecraft.Client/Common/UI/UIScene_MessageBox.cpp b/Minecraft.Client/Common/UI/UIScene_MessageBox.cpp index 6b8dc552e..7a0749d4a 100644 --- a/Minecraft.Client/Common/UI/UIScene_MessageBox.cpp +++ b/Minecraft.Client/Common/UI/UIScene_MessageBox.cpp @@ -7,7 +7,7 @@ UIScene_MessageBox::UIScene_MessageBox(int iPad, void *initData, UILayer *parent // Setup all the Iggy references we need for this scene initialiseMovie(); - MessageBoxInfo *param = (MessageBoxInfo *)initData; + MessageBoxInfo *param = static_cast(initData); m_buttonCount = param->uiOptionC; @@ -41,7 +41,7 @@ UIScene_MessageBox::UIScene_MessageBox(int iPad, void *initData, UILayer *parent m_labelTitle.init(app.GetString(param->uiTitle)); m_labelContent.init(app.GetString(param->uiText)); - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , nullptr ); m_Func = param->Func; m_lpParam = param->lpParam; @@ -84,10 +84,10 @@ void UIScene_MessageBox::handleReload() value[0].number = m_buttonCount; value[1].type = IGGY_DATATYPE_number; - value[1].number = (F64)getControlFocus(); + value[1].number = static_cast(getControlFocus()); IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcInit , 2 , value ); - out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , NULL ); + out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , nullptr ); } void UIScene_MessageBox::handleInput(int iPad, int key, bool repeat, bool pressed, bool released, bool &handled) @@ -120,7 +120,7 @@ void UIScene_MessageBox::handleInput(int iPad, int key, bool repeat, bool presse void UIScene_MessageBox::handlePress(F64 controlId, F64 childId) { C4JStorage::EMessageResult result = C4JStorage::EMessage_Cancelled; - switch((int)controlId) + switch(static_cast(controlId)) { case 0: result = C4JStorage::EMessage_ResultAccept; diff --git a/Minecraft.Client/Common/UI/UIScene_NewUpdateMessage.cpp b/Minecraft.Client/Common/UI/UIScene_NewUpdateMessage.cpp index 998679cab..118712a46 100644 --- a/Minecraft.Client/Common/UI/UIScene_NewUpdateMessage.cpp +++ b/Minecraft.Client/Common/UI/UIScene_NewUpdateMessage.cpp @@ -19,8 +19,8 @@ UIScene_NewUpdateMessage::UIScene_NewUpdateMessage(int iPad, void *initData, UIL message=app.FormatHTMLString(m_iPad,message); vector paragraphs; - int lastIndex = 0; - for ( int index = message.find(L"\r\n", lastIndex, 2); + size_t lastIndex = 0; + for ( size_t index = message.find(L"\r\n", lastIndex, 2); index != wstring::npos; index = message.find(L"\r\n", lastIndex, 2) ) @@ -100,7 +100,7 @@ void UIScene_NewUpdateMessage::handleInput(int iPad, int key, bool repeat, bool void UIScene_NewUpdateMessage::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Confirm: { diff --git a/Minecraft.Client/Common/UI/UIScene_PauseMenu.cpp b/Minecraft.Client/Common/UI/UIScene_PauseMenu.cpp index 6f502db86..7cec38b3c 100644 --- a/Minecraft.Client/Common/UI/UIScene_PauseMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_PauseMenu.cpp @@ -101,9 +101,9 @@ UIScene_PauseMenu::UIScene_PauseMenu(int iPad, void *initData, UILayer *parentLa TelemetryManager->RecordPauseOrInactive(m_iPad); Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[iPad]); // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(false); @@ -114,9 +114,9 @@ UIScene_PauseMenu::UIScene_PauseMenu(int iPad, void *initData, UILayer *parentLa UIScene_PauseMenu::~UIScene_PauseMenu() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(true); @@ -506,7 +506,7 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) { if(m_bIgnoreInput) return; - switch((int)controlId) + switch(static_cast(controlId)) { case BUTTON_PAUSE_RESUMEGAME: if( m_iPad == ProfileManager.GetPrimaryPad() && g_NetworkManager.IsLocalGame() ) @@ -593,7 +593,7 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) { bool bContentRestricted=false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(m_iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(m_iPad,true,nullptr,&bContentRestricted,nullptr); #endif if(bContentRestricted) { @@ -654,9 +654,9 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) if(m_iPad==ProfileManager.GetPrimaryPad()) { int playTime = -1; - if( pMinecraft->localplayers[m_iPad] != NULL ) + if( pMinecraft->localplayers[m_iPad] != nullptr ) { - playTime = (int)pMinecraft->localplayers[m_iPad]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[m_iPad]->getSessionTimer()); } #if defined(_XBOX_ONE) || defined(__ORBIS__) @@ -723,9 +723,9 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) else { int playTime = -1; - if( pMinecraft->localplayers[m_iPad] != NULL ) + if( pMinecraft->localplayers[m_iPad] != nullptr ) { - playTime = (int)pMinecraft->localplayers[m_iPad]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[m_iPad]->getSessionTimer()); } TelemetryManager->RecordLevelExit(m_iPad, eSen_LevelExitStatus_Exited); @@ -741,9 +741,9 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) if(m_iPad==ProfileManager.GetPrimaryPad()) { int playTime = -1; - if( pMinecraft->localplayers[m_iPad] != NULL ) + if( pMinecraft->localplayers[m_iPad] != nullptr ) { - playTime = (int)pMinecraft->localplayers[m_iPad]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[m_iPad]->getSessionTimer()); } // adjust the trial time played @@ -759,9 +759,9 @@ void UIScene_PauseMenu::handlePress(F64 controlId, F64 childId) else { int playTime = -1; - if( pMinecraft->localplayers[m_iPad] != NULL ) + if( pMinecraft->localplayers[m_iPad] != nullptr ) { - playTime = (int)pMinecraft->localplayers[m_iPad]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[m_iPad]->getSessionTimer()); } TelemetryManager->RecordLevelExit(m_iPad, eSen_LevelExitStatus_Exited); @@ -839,7 +839,7 @@ void UIScene_PauseMenu::PerformActionSaveGame() if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); m_pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); @@ -979,7 +979,7 @@ int UIScene_PauseMenu::UnlockFullSaveReturned(void *pParam,int iPad,C4JStorage:: // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -1003,7 +1003,7 @@ int UIScene_PauseMenu::UnlockFullSaveReturned(void *pParam,int iPad,C4JStorage:: int UIScene_PauseMenu::SaveGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - UIScene_PauseMenu* pClass = (UIScene_PauseMenu*)ui.GetSceneFromCallbackId((size_t)pParam); + UIScene_PauseMenu* pClass = static_cast(ui.GetSceneFromCallbackId((size_t)pParam)); if(pClass) pClass->SetIgnoreInput(false); if(bContinue==true) @@ -1112,7 +1112,7 @@ int UIScene_PauseMenu::ViewLeaderboards_SignInReturned(void *pParam,bool bContin { #ifndef __ORBIS__ bool bContentRestricted=false; - ProfileManager.GetChatAndContentRestrictions(pClass->m_iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(pClass->m_iPad,true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { // you can't see leaderboards @@ -1183,7 +1183,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J #ifndef __ORBIS__ // 4J-PB - need to check this user can access the store bool bContentRestricted=false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -1203,7 +1203,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J app.DebugPrintf("Texture Pack - %s\n",pchPackName); SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo((char *)pchPackName); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chKeyName[20]; @@ -1214,7 +1214,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J // we have to retrieve the skuid from the store info, it can't be hardcoded since Sony may change it. // So we assume the first sku for the product is the one we want - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char + // MGH - keyname in the DLC file is 16 chars long, but there's no space for a nullptr terminating char memset(chKeyName, 0, sizeof(chKeyName)); strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); @@ -1260,7 +1260,7 @@ int UIScene_PauseMenu::BuyTexturePack_SignInReturned(void *pParam,bool bContinue #ifndef __ORBIS__ // 4J-PB - need to check this user can access the store bool bContentRestricted=false; - ProfileManager.GetChatAndContentRestrictions(iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad,true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; @@ -1280,7 +1280,7 @@ int UIScene_PauseMenu::BuyTexturePack_SignInReturned(void *pParam,bool bContinue app.DebugPrintf("Texture Pack - %s\n",pchPackName); SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo((char *)pchPackName); - if(pSONYDLCInfo!=NULL) + if(pSONYDLCInfo!=nullptr) { char chName[42]; char chKeyName[20]; @@ -1291,7 +1291,7 @@ int UIScene_PauseMenu::BuyTexturePack_SignInReturned(void *pParam,bool bContinue // we have to retrieve the skuid from the store info, it can't be hardcoded since Sony may change it. // So we assume the first sku for the product is the one we want - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char + // MGH - keyname in the DLC file is 16 chars long, but there's no space for a nullptr terminating char memset(chKeyName, 0, sizeof(chKeyName)); strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); diff --git a/Minecraft.Client/Common/UI/UIScene_QuadrantSignin.cpp b/Minecraft.Client/Common/UI/UIScene_QuadrantSignin.cpp index 0cb6cf2bd..766765614 100644 --- a/Minecraft.Client/Common/UI/UIScene_QuadrantSignin.cpp +++ b/Minecraft.Client/Common/UI/UIScene_QuadrantSignin.cpp @@ -11,7 +11,7 @@ UIScene_QuadrantSignin::UIScene_QuadrantSignin(int iPad, void *_initData, UILaye // Setup all the Iggy references we need for this scene initialiseMovie(); - m_signInInfo = *((SignInInfo *)_initData); + m_signInInfo = *static_cast(_initData); m_bIgnoreInput = false; @@ -167,7 +167,7 @@ int UIScene_QuadrantSignin::SignInReturned(void *pParam,bool bContinue, int iPad { app.DebugPrintf("SignInReturned for pad %d\n", iPad); - UIScene_QuadrantSignin *pClass = (UIScene_QuadrantSignin *)pParam; + UIScene_QuadrantSignin *pClass = static_cast(pParam); #ifdef _XBOX_ONE if(bContinue && pClass->m_signInInfo.requireOnline && ProfileManager.IsSignedIn(iPad)) @@ -264,7 +264,7 @@ void UIScene_QuadrantSignin::setControllerState(int iPad, EControllerStatus stat value[0].number = iPad; value[1].type = IGGY_DATATYPE_number; - value[1].number = (int)state; + value[1].number = static_cast(state); IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcSetControllerStatus , 2 , value ); } @@ -272,9 +272,9 @@ void UIScene_QuadrantSignin::setControllerState(int iPad, EControllerStatus stat int UIScene_QuadrantSignin::AvatarReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) { - UIScene_QuadrantSignin *pClass = (UIScene_QuadrantSignin *)lpParam; + UIScene_QuadrantSignin *pClass = static_cast(lpParam); app.DebugPrintf(app.USER_SR,"AvatarReturned callback\n"); - if(pbThumbnail != NULL) + if(pbThumbnail != nullptr) { // 4J-JEV - Added to ensure each new texture gets a unique name. static unsigned int quadrantImageCount = 0; diff --git a/Minecraft.Client/Common/UI/UIScene_ReinstallMenu.cpp b/Minecraft.Client/Common/UI/UIScene_ReinstallMenu.cpp index 3b67f79e7..c713a3900 100644 --- a/Minecraft.Client/Common/UI/UIScene_ReinstallMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_ReinstallMenu.cpp @@ -36,7 +36,7 @@ void UIScene_ReinstallMenu::updateTooltips() void UIScene_ReinstallMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); diff --git a/Minecraft.Client/Common/UI/UIScene_SaveMessage.cpp b/Minecraft.Client/Common/UI/UIScene_SaveMessage.cpp index b58f86fda..0b8e0ca4a 100644 --- a/Minecraft.Client/Common/UI/UIScene_SaveMessage.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SaveMessage.cpp @@ -19,7 +19,7 @@ UIScene_SaveMessage::UIScene_SaveMessage(int iPad, void *initData, UILayer *pare IggyDataValue result; // Russian needs to resize the box - IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , NULL ); + IggyResult out = IggyPlayerCallMethodRS ( getMovie() , &result, IggyPlayerRootPath( getMovie() ), m_funcAutoResize , 0 , nullptr ); // 4J-PB - If we have a signed in user connected, let's get the DLC now for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) @@ -101,7 +101,7 @@ void UIScene_SaveMessage::handleInput(int iPad, int key, bool repeat, bool press void UIScene_SaveMessage::handlePress(F64 controlId, F64 childId) { - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Confirm: diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsAudioMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsAudioMenu.cpp index 6d892d703..083fbd358 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsAudioMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsAudioMenu.cpp @@ -47,7 +47,7 @@ void UIScene_SettingsAudioMenu::updateTooltips() void UIScene_SettingsAudioMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -93,8 +93,8 @@ void UIScene_SettingsAudioMenu::handleInput(int iPad, int key, bool repeat, bool void UIScene_SettingsAudioMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_Music: m_sliderMusic.handleSliderMove(value); diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsControlMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsControlMenu.cpp index d5447f779..7dbd243b7 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsControlMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsControlMenu.cpp @@ -47,7 +47,7 @@ void UIScene_SettingsControlMenu::updateTooltips() void UIScene_SettingsControlMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -93,8 +93,8 @@ void UIScene_SettingsControlMenu::handleInput(int iPad, int key, bool repeat, bo void UIScene_SettingsControlMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_SensitivityInGame: m_sliderSensitivityInGame.handleSliderMove(value); diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsGraphicsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsGraphicsMenu.cpp index 423c8f4b2..b258d8c31 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsGraphicsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsGraphicsMenu.cpp @@ -7,20 +7,21 @@ namespace { - const int FOV_MIN = 70; - const int FOV_MAX = 110; - const int FOV_SLIDER_MAX = 100; + constexpr int FOV_MIN = 70; + constexpr int FOV_MAX = 110; + constexpr int FOV_SLIDER_MAX = 100; - int clampFov(int value) + int ClampFov(int value) { if (value < FOV_MIN) return FOV_MIN; if (value > FOV_MAX) return FOV_MAX; return value; } - int fovToSliderValue(float fov) + [[maybe_unused]] + int FovToSliderValue(float fov) { - int clampedFov = clampFov((int)(fov + 0.5f)); + const int clampedFov = ClampFov(static_cast(fov + 0.5f)); return ((clampedFov - FOV_MIN) * FOV_SLIDER_MAX) / (FOV_MAX - FOV_MIN); } @@ -56,7 +57,7 @@ UIScene_SettingsGraphicsMenu::UIScene_SettingsGraphicsMenu(int iPad, void *initD initialiseMovie(); Minecraft* pMinecraft = Minecraft::GetInstance(); - m_bNotInGame=(Minecraft::GetInstance()->level==NULL); + m_bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_checkboxClouds.init(app.GetString(IDS_CHECKBOX_RENDER_CLOUDS),eControl_Clouds,(app.GetGameSettings(m_iPad,eGameSetting_Clouds)!=0)); m_checkboxBedrockFog.init(app.GetString(IDS_CHECKBOX_RENDER_BEDROCKFOG),eControl_BedrockFog,(app.GetGameSettings(m_iPad,eGameSetting_BedrockFog)!=0)); @@ -65,24 +66,24 @@ UIScene_SettingsGraphicsMenu::UIScene_SettingsGraphicsMenu(int iPad, void *initD WCHAR TempString[256]; - swprintf((WCHAR*)TempString, 256, L"Render Distance: %d",app.GetGameSettings(m_iPad,eGameSetting_RenderDistance)); + swprintf(TempString, 256, L"Render Distance: %d",app.GetGameSettings(m_iPad,eGameSetting_RenderDistance)); m_sliderRenderDistance.init(TempString,eControl_RenderDistance,0,5,DistanceToLevel(app.GetGameSettings(m_iPad,eGameSetting_RenderDistance))); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),app.GetGameSettings(m_iPad,eGameSetting_Gamma)); + swprintf( TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),app.GetGameSettings(m_iPad,eGameSetting_Gamma)); m_sliderGamma.init(TempString,eControl_Gamma,0,100,app.GetGameSettings(m_iPad,eGameSetting_Gamma)); - int initialFovSlider = app.GetGameSettings(m_iPad, eGameSetting_FOV); - int initialFovDeg = sliderValueToFov(initialFovSlider); - swprintf((WCHAR*)TempString, 256, L"FOV: %d", initialFovDeg); + const int initialFovSlider = app.GetGameSettings(m_iPad, eGameSetting_FOV); + const int initialFovDeg = sliderValueToFov(initialFovSlider); + swprintf(TempString, 256, L"FOV: %d", initialFovDeg); m_sliderFOV.init(TempString, eControl_FOV, 0, FOV_SLIDER_MAX, initialFovSlider); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),app.GetGameSettings(m_iPad,eGameSetting_InterfaceOpacity)); + swprintf( TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),app.GetGameSettings(m_iPad,eGameSetting_InterfaceOpacity)); m_sliderInterfaceOpacity.init(TempString,eControl_InterfaceOpacity,0,100,app.GetGameSettings(m_iPad,eGameSetting_InterfaceOpacity)); doHorizontalResizeCheck(); - - bool bInGame=(Minecraft::GetInstance()->level!=NULL); - bool bIsPrimaryPad=(ProfileManager.GetPrimaryPad()==m_iPad); + + const bool bInGame=(Minecraft::GetInstance()->level!=nullptr); + const bool bIsPrimaryPad=(ProfileManager.GetPrimaryPad()==m_iPad); // if we're not in the game, we need to use basescene 0 if(bInGame) { @@ -136,7 +137,7 @@ void UIScene_SettingsGraphicsMenu::updateTooltips() void UIScene_SettingsGraphicsMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + const bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -187,20 +188,20 @@ void UIScene_SettingsGraphicsMenu::handleInput(int iPad, int key, bool repeat, b void UIScene_SettingsGraphicsMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + const int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_RenderDistance: { m_sliderRenderDistance.handleSliderMove(value); - int dist = LevelToDistance(value); + const int dist = LevelToDistance(value); app.SetGameSettings(m_iPad,eGameSetting_RenderDistance,dist); - Minecraft* mc = Minecraft::GetInstance(); + const Minecraft* mc = Minecraft::GetInstance(); mc->options->viewDistance = 3 - value; - swprintf((WCHAR*)TempString,256,L"Render Distance: %d",dist); + swprintf(TempString,256,L"Render Distance: %d",dist); m_sliderRenderDistance.setLabel(TempString); } break; @@ -209,7 +210,7 @@ void UIScene_SettingsGraphicsMenu::handleSliderMove(F64 sliderId, F64 currentVal m_sliderGamma.handleSliderMove(value); app.SetGameSettings(m_iPad,eGameSetting_Gamma,value); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),value); + swprintf( TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),value); m_sliderGamma.setLabel(TempString); break; @@ -217,13 +218,13 @@ void UIScene_SettingsGraphicsMenu::handleSliderMove(F64 sliderId, F64 currentVal case eControl_FOV: { m_sliderFOV.handleSliderMove(value); - Minecraft* pMinecraft = Minecraft::GetInstance(); - int fovValue = sliderValueToFov(value); - pMinecraft->gameRenderer->SetFovVal((float)fovValue); + const Minecraft* pMinecraft = Minecraft::GetInstance(); + const int fovValue = sliderValueToFov(value); + pMinecraft->gameRenderer->SetFovVal(static_cast(fovValue)); app.SetGameSettings(m_iPad, eGameSetting_FOV, value); - WCHAR TempString[256]; - swprintf((WCHAR*)TempString, 256, L"FOV: %d", fovValue); - m_sliderFOV.setLabel(TempString); + WCHAR tempString[256]; + swprintf(tempString, 256, L"FOV: %d", fovValue); + m_sliderFOV.setLabel(tempString); } break; @@ -231,7 +232,7 @@ void UIScene_SettingsGraphicsMenu::handleSliderMove(F64 sliderId, F64 currentVal m_sliderInterfaceOpacity.handleSliderMove(value); app.SetGameSettings(m_iPad,eGameSetting_InterfaceOpacity,value); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),value); + swprintf( TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),value); m_sliderInterfaceOpacity.setLabel(TempString); break; diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsMenu.cpp index 39a0b7c66..2ae9c897d 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsMenu.cpp @@ -8,7 +8,7 @@ UIScene_SettingsMenu::UIScene_SettingsMenu(int iPad, void *initData, UILayer *pa // Setup all the Iggy references we need for this scene initialiseMovie(); - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_buttons[BUTTON_ALL_OPTIONS].init(IDS_OPTIONS,BUTTON_ALL_OPTIONS); m_buttons[BUTTON_ALL_AUDIO].init(IDS_AUDIO,BUTTON_ALL_AUDIO); @@ -51,7 +51,7 @@ wstring UIScene_SettingsMenu::getMoviePath() void UIScene_SettingsMenu::handleReload() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(ProfileManager.GetPrimaryPad()!=m_iPad) { removeControl( &m_buttons[BUTTON_ALL_AUDIO], bNotInGame); @@ -68,7 +68,7 @@ void UIScene_SettingsMenu::updateTooltips() void UIScene_SettingsMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -119,7 +119,7 @@ void UIScene_SettingsMenu::handlePress(F64 controlId, F64 childId) //CD - Added for audio ui.PlayUISFX(eSFX_Press); - switch((int)controlId) + switch(static_cast(controlId)) { case BUTTON_ALL_OPTIONS: ui.NavigateToScene(m_iPad, eUIScene_SettingsOptionsMenu); @@ -151,7 +151,7 @@ void UIScene_SettingsMenu::handlePress(F64 controlId, F64 childId) int UIScene_SettingsMenu::ResetDefaultsDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_SettingsMenu* pClass = (UIScene_SettingsMenu*)pParam; + UIScene_SettingsMenu* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsOptionsMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsOptionsMenu.cpp index 6898d489a..7b4d3d9dd 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsOptionsMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsOptionsMenu.cpp @@ -29,7 +29,7 @@ UIScene_SettingsOptionsMenu::UIScene_SettingsOptionsMenu(int iPad, void *initDat // Setup all the Iggy references we need for this scene initialiseMovie(); - m_bNotInGame=(Minecraft::GetInstance()->level==NULL); + m_bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_checkboxViewBob.init(IDS_VIEW_BOBBING,eControl_ViewBob,(app.GetGameSettings(m_iPad,eGameSetting_ViewBob)!=0)); m_checkboxShowHints.init(IDS_HINTS,eControl_ShowHints,(app.GetGameSettings(m_iPad,eGameSetting_Hints)!=0)); @@ -99,7 +99,7 @@ UIScene_SettingsOptionsMenu::UIScene_SettingsOptionsMenu(int iPad, void *initDat bool bRemoveAutosave=false; bool bRemoveInGameGamertags=false; - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bPrimaryPlayer = ProfileManager.GetPrimaryPad()==m_iPad; if(!bPrimaryPlayer) { @@ -196,7 +196,7 @@ void UIScene_SettingsOptionsMenu::updateTooltips() void UIScene_SettingsOptionsMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -243,7 +243,7 @@ void UIScene_SettingsOptionsMenu::handlePress(F64 controlId, F64 childId) //CD - Added for audio ui.PlayUISFX(eSFX_Press); - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Languages: m_bNavigateToLanguageSelector = true; @@ -324,7 +324,7 @@ void UIScene_SettingsOptionsMenu::handleReload() bool bRemoveAutosave=false; bool bRemoveInGameGamertags=false; - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bPrimaryPlayer = ProfileManager.GetPrimaryPad()==m_iPad; if(!bPrimaryPlayer) { @@ -378,8 +378,8 @@ void UIScene_SettingsOptionsMenu::handleReload() void UIScene_SettingsOptionsMenu::handleSliderMove(F64 sliderId, F64 currentValue) { - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_Autosave: m_sliderAutosave.handleSliderMove(value); diff --git a/Minecraft.Client/Common/UI/UIScene_SettingsUIMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SettingsUIMenu.cpp index 917012d6b..873564f62 100644 --- a/Minecraft.Client/Common/UI/UIScene_SettingsUIMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SettingsUIMenu.cpp @@ -7,7 +7,7 @@ UIScene_SettingsUIMenu::UIScene_SettingsUIMenu(int iPad, void *initData, UILayer // Setup all the Iggy references we need for this scene initialiseMovie(); - m_bNotInGame=(Minecraft::GetInstance()->level==NULL); + m_bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_checkboxDisplayHUD.init(app.GetString(IDS_CHECKBOX_DISPLAY_HUD),eControl_DisplayHUD,(app.GetGameSettings(m_iPad,eGameSetting_DisplayHUD)!=0)); m_checkboxDisplayHand.init(app.GetString(IDS_CHECKBOX_DISPLAY_HAND),eControl_DisplayHand,(app.GetGameSettings(m_iPad,eGameSetting_DisplayHand)!=0)); @@ -26,7 +26,7 @@ UIScene_SettingsUIMenu::UIScene_SettingsUIMenu(int iPad, void *initData, UILayer doHorizontalResizeCheck(); - bool bInGame=(Minecraft::GetInstance()->level!=NULL); + bool bInGame=(Minecraft::GetInstance()->level!=nullptr); bool bPrimaryPlayer = ProfileManager.GetPrimaryPad()==m_iPad; // if we're not in the game, we need to use basescene 0 @@ -57,7 +57,7 @@ void UIScene_SettingsUIMenu::updateTooltips() void UIScene_SettingsUIMenu::updateComponents() { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { m_parentLayer->showComponent(m_iPad,eUIComponent_Panorama,true); @@ -146,8 +146,8 @@ void UIScene_SettingsUIMenu::handleInput(int iPad, int key, bool repeat, bool pr void UIScene_SettingsUIMenu::handleSliderMove(F64 sliderId, F64 currentValue) { WCHAR TempString[256]; - int value = (int)currentValue; - switch((int)sliderId) + int value = static_cast(currentValue); + switch(static_cast(sliderId)) { case eControl_UISize: m_sliderUISize.handleSliderMove(value); diff --git a/Minecraft.Client/Common/UI/UIScene_SignEntryMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SignEntryMenu.cpp index 9f049c8c9..5ef783d39 100644 --- a/Minecraft.Client/Common/UI/UIScene_SignEntryMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SignEntryMenu.cpp @@ -13,7 +13,7 @@ UIScene_SignEntryMenu::UIScene_SignEntryMenu(int iPad, void *_initData, UILayer // Setup all the Iggy references we need for this scene initialiseMovie(); - SignEntryScreenInput* initData = (SignEntryScreenInput*)_initData; + SignEntryScreenInput* initData = static_cast(_initData); m_sign = initData->sign; m_bConfirmed = false; @@ -175,9 +175,9 @@ void UIScene_SignEntryMenu::tick() if (pMinecraft->level->isClientSide) { shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player != NULL && player->connection && player->connection->isStarted()) + if(player != nullptr && player->connection && player->connection->isStarted()) { - player->connection->send( shared_ptr( new SignUpdatePacket(m_sign->x, m_sign->y, m_sign->z, m_sign->IsVerified(), m_sign->IsCensored(), m_sign->GetMessages()) ) ); + player->connection->send(std::make_shared(m_sign->x, m_sign->y, m_sign->z, m_sign->IsVerified(), m_sign->IsCensored(), m_sign->GetMessages())); } } ui.CloseUIScenes(m_iPad); @@ -309,7 +309,7 @@ bool UIScene_SignEntryMenu::handleMouseClick(F32 x, F32 y) int UIScene_SignEntryMenu::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) { - UIScene_SignEntryMenu *pClass=(UIScene_SignEntryMenu *)lpParam; + const auto pClass=static_cast(lpParam); pClass->m_bIgnoreInput = false; if (bRes) { @@ -317,7 +317,7 @@ int UIScene_SignEntryMenu::KeyboardCompleteCallback(LPVOID lpParam,bool bRes) uint16_t pchText[128]; ZeroMemory(pchText, 128 * sizeof(uint16_t)); Win64_GetKeyboardText(pchText, 128); - pClass->m_textInputLines[pClass->m_iEditingLine].setLabel((wchar_t *)pchText); + pClass->m_textInputLines[pClass->m_iEditingLine].setLabel(reinterpret_cast(pchText)); #else uint16_t pchText[128]; ZeroMemory(pchText, 128 * sizeof(uint16_t) ); @@ -333,7 +333,7 @@ void UIScene_SignEntryMenu::handlePress(F64 controlId, F64 childId) #ifdef _WINDOWS64 if (isDirectEditBlocking()) return; #endif - switch((int)controlId) + switch(static_cast(controlId)) { case eControl_Confirm: { @@ -345,7 +345,7 @@ void UIScene_SignEntryMenu::handlePress(F64 controlId, F64 childId) case eControl_Line3: case eControl_Line4: { - m_iEditingLine = (int)controlId; + m_iEditingLine = static_cast(controlId); #ifdef _WINDOWS64 if (g_KBMInput.IsKBMActive()) { @@ -384,7 +384,7 @@ void UIScene_SignEntryMenu::handlePress(F64 controlId, F64 childId) break; } #else - InputManager.RequestKeyboard(app.GetString(IDS_SIGN_TITLE),m_textInputLines[m_iEditingLine].getLabel(),(DWORD)m_iPad,15,&UIScene_SignEntryMenu::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Alphabet); + InputManager.RequestKeyboard(app.GetString(IDS_SIGN_TITLE),m_textInputLines[m_iEditingLine].getLabel(),static_cast(m_iPad),15,&UIScene_SignEntryMenu::KeyboardCompleteCallback,this,C_4JInput::EKeyboardMode_Alphabet); #endif #endif } diff --git a/Minecraft.Client/Common/UI/UIScene_SkinSelectMenu.cpp b/Minecraft.Client/Common/UI/UIScene_SkinSelectMenu.cpp index 9e0059f3b..a3482a24d 100644 --- a/Minecraft.Client/Common/UI/UIScene_SkinSelectMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_SkinSelectMenu.cpp @@ -40,7 +40,7 @@ UIScene_SkinSelectMenu::UIScene_SkinSelectMenu(int iPad, void *initData, UILayer m_bIgnoreInput=false; m_bNoSkinsToShow = false; - m_currentPack = NULL; + m_currentPack = nullptr; m_packIndex = SKIN_SELECT_PACK_DEFAULT; m_skinIndex = 0; @@ -48,7 +48,7 @@ UIScene_SkinSelectMenu::UIScene_SkinSelectMenu(int iPad, void *initData, UILayer m_currentSkinPath = app.GetPlayerSkinName(iPad); m_selectedSkinPath = L""; m_selectedCapePath = L""; - m_vAdditionalSkinBoxes = NULL; + m_vAdditionalSkinBoxes = nullptr; m_bSlidingSkins = false; m_bAnimatingMove = false; @@ -107,7 +107,7 @@ UIScene_SkinSelectMenu::UIScene_SkinSelectMenu(int iPad, void *initData, UILayer // Change to display the favorites if there are any. The current skin will be in there (probably) - need to check for it m_currentPack = app.m_dlcManager.getPackContainingSkin(m_currentSkinPath); bool bFound; - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { m_packIndex = app.m_dlcManager.getPackIndex(m_currentPack,bFound,DLCManager::e_DLCType_Skin) + SKIN_SELECT_MAX_DEFAULTS; } @@ -436,7 +436,7 @@ void UIScene_SkinSelectMenu::InputActionOK(unsigned int iPad) } break; default: - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { bool renableInputAfterOperation = true; m_bIgnoreInput = true; @@ -520,7 +520,7 @@ void UIScene_SkinSelectMenu::InputActionOK(unsigned int iPad) DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_currentPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -534,7 +534,7 @@ void UIScene_SkinSelectMenu::InputActionOK(unsigned int iPad) #endif bool bContentRestricted=false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(m_iPad,true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(m_iPad,true,nullptr,&bContentRestricted,nullptr); #endif if(bContentRestricted) { @@ -599,7 +599,7 @@ void UIScene_SkinSelectMenu::InputActionOK(unsigned int iPad) void UIScene_SkinSelectMenu::customDraw(IggyCustomDrawCallbackRegion *region) { int characterId = -1; - swscanf((wchar_t*)region->name,L"Character%d",&characterId); + swscanf(static_cast(region->name),L"Character%d",&characterId); if (characterId == -1) { app.DebugPrintf("Invalid character to render found\n"); @@ -635,8 +635,8 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() wstring skinOrigin = L""; bool bSkinIsFree=false; bool bLicensed=false; - DLCSkinFile *skinFile=NULL; - DLCPack *Pack=NULL; + DLCSkinFile *skinFile=nullptr; + DLCPack *Pack=nullptr; BYTE sidePreviewControlsL,sidePreviewControlsR; m_bNoSkinsToShow=false; @@ -646,7 +646,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() m_controlSkinNamePlate.setVisible( false ); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(m_skinIndex); m_selectedSkinPath = skinFile->getPath(); @@ -673,7 +673,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() { m_selectedSkinPath = L""; m_selectedCapePath = L""; - m_vAdditionalSkinBoxes = NULL; + m_vAdditionalSkinBoxes = nullptr; switch(m_packIndex) { @@ -758,13 +758,13 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() // add the boxes to the humanoid model, but only if we've not done this already vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),m_vAdditionalSkinBoxes); } } - if(skinFile!=NULL) + if(skinFile!=nullptr) { app.SetAnimOverrideBitmask(skinFile->getSkinID(),skinFile->getAnimOverrideBitmask()); } @@ -779,7 +779,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() wstring otherSkinPath = L""; wstring otherCapePath = L""; - vector *othervAdditionalSkinBoxes=NULL; + vector *othervAdditionalSkinBoxes=nullptr; wchar_t chars[256]; // turn off all displays @@ -824,11 +824,11 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() { if(showNext) { - skinFile=NULL; + skinFile=nullptr; m_characters[eCharacter_Next1 + i].setVisible(true); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(nextIndex); otherSkinPath = skinFile->getPath(); @@ -840,7 +840,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() { otherSkinPath = L""; otherCapePath = L""; - othervAdditionalSkinBoxes=NULL; + othervAdditionalSkinBoxes=nullptr; switch(m_packIndex) { case SKIN_SELECT_PACK_DEFAULT: @@ -872,13 +872,13 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() if(othervAdditionalSkinBoxes && othervAdditionalSkinBoxes->size()!=0) { vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),othervAdditionalSkinBoxes); } } // 4J-PB - anim override needs set before SetTexture - if(skinFile!=NULL) + if(skinFile!=nullptr) { app.SetAnimOverrideBitmask(skinFile->getSkinID(),skinFile->getAnimOverrideBitmask()); } @@ -895,11 +895,11 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() { if(showPrevious) { - skinFile=NULL; + skinFile=nullptr; m_characters[eCharacter_Previous1 + i].setVisible(true); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(previousIndex); otherSkinPath = skinFile->getPath(); @@ -911,7 +911,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() { otherSkinPath = L""; otherCapePath = L""; - othervAdditionalSkinBoxes=NULL; + othervAdditionalSkinBoxes=nullptr; switch(m_packIndex) { case SKIN_SELECT_PACK_DEFAULT: @@ -943,7 +943,7 @@ void UIScene_SkinSelectMenu::handleSkinIndexChanged() if(othervAdditionalSkinBoxes && othervAdditionalSkinBoxes->size()!=0) { vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),othervAdditionalSkinBoxes); } @@ -1021,7 +1021,7 @@ int UIScene_SkinSelectMenu::getNextSkinIndex(DWORD sourceIndex) { nextSkin = eDefaultSkins_ServerSelected; } - else if(m_currentPack != NULL && nextSkin>=m_currentPack->getSkinCount()) + else if(m_currentPack != nullptr && nextSkin>=m_currentPack->getSkinCount()) { nextSkin = 0; } @@ -1055,7 +1055,7 @@ int UIScene_SkinSelectMenu::getPreviousSkinIndex(DWORD sourceIndex) { previousSkin = eDefaultSkins_Count - 1; } - else if(m_currentPack != NULL) + else if(m_currentPack != nullptr) { previousSkin = m_currentPack->getSkinCount()-1; } @@ -1079,10 +1079,10 @@ void UIScene_SkinSelectMenu::handlePackIndexChanged() } else { - m_currentPack = NULL; + m_currentPack = nullptr; } m_skinIndex = 0; - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { bool found; DWORD currentSkinIndex = m_currentPack->getSkinIndexAt(m_currentSkinPath, found); @@ -1099,7 +1099,7 @@ void UIScene_SkinSelectMenu::handlePackIndexChanged() DWORD defaultSkinIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(m_originalSkinId); if( ugcSkinIndex == 0 ) { - m_skinIndex = (EDefaultSkins) defaultSkinIndex; + m_skinIndex = static_cast(defaultSkinIndex); } } break; @@ -1130,7 +1130,7 @@ void UIScene_SkinSelectMenu::handlePackIndexChanged() std::wstring fakeWideToRealWide(const wchar_t* original) { const char* name = reinterpret_cast(original); - int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0); + int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, nullptr, 0); std::wstring wName(len, 0); MultiByteToWideChar(CP_UTF8, 0, name, -1, &wName[0], len); return wName.c_str(); @@ -1500,7 +1500,7 @@ void UIScene_SkinSelectMenu::HandleDLCMountingComplete() if(app.m_dlcManager.getPackCount(DLCManager::e_DLCType_Skin)>0) { m_currentPack = app.m_dlcManager.getPackContainingSkin(m_currentSkinPath); - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { bool bFound = false; m_packIndex = app.m_dlcManager.getPackIndex(m_currentPack,bFound,DLCManager::e_DLCType_Skin) + SKIN_SELECT_MAX_DEFAULTS; @@ -1520,7 +1520,7 @@ void UIScene_SkinSelectMenu::HandleDLCMountingComplete() m_bIgnoreInput=false; app.m_dlcManager.checkForCorruptDLCAndAlert(); - bool bInGame=(Minecraft::GetInstance()->level!=NULL); + bool bInGame=(Minecraft::GetInstance()->level!=nullptr); #if TO_BE_IMPLEMENTED if(bInGame) XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_AUTO); @@ -1534,7 +1534,7 @@ void UIScene_SkinSelectMenu::showNotOnlineDialog(int iPad) { // need to be signed in to live. get them to sign in to online #if defined(__PS3__) - SQRNetworkManager_PS3::AttemptPSNSignIn(NULL, this); + SQRNetworkManager_PS3::AttemptPSNSignIn(nullptr, this); #elif defined(__PSVITA__) if(CGameNetworkManager::usingAdhocMode() && SQRNetworkManager_AdHoc_Vita::GetAdhocStatus()) @@ -1543,15 +1543,15 @@ void UIScene_SkinSelectMenu::showNotOnlineDialog(int iPad) UINT uiIDA[2]; uiIDA[0]=IDS_PRO_NOTONLINE_ACCEPT; uiIDA[1]=IDS_CANCEL; - ui.RequestErrorMessage(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, ProfileManager.GetPrimaryPad(),&UIScene_SkinSelectMenu::MustSignInReturned,NULL); + ui.RequestErrorMessage(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, ProfileManager.GetPrimaryPad(),&UIScene_SkinSelectMenu::MustSignInReturned,nullptr); } else { - SQRNetworkManager_Vita::AttemptPSNSignIn(NULL, this); + SQRNetworkManager_Vita::AttemptPSNSignIn(nullptr, this); } #elif defined(__ORBIS__) - SQRNetworkManager_Orbis::AttemptPSNSignIn(NULL, this, false, iPad); + SQRNetworkManager_Orbis::AttemptPSNSignIn(nullptr, this, false, iPad); #elif defined(_DURANGO) @@ -1563,7 +1563,7 @@ void UIScene_SkinSelectMenu::showNotOnlineDialog(int iPad) int UIScene_SkinSelectMenu::UnlockSkinReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_SkinSelectMenu* pScene = (UIScene_SkinSelectMenu*)pParam; + UIScene_SkinSelectMenu* pScene = static_cast(pParam); if ( (result == C4JStorage::EMessage_ResultAccept) && ProfileManager.IsSignedIn(iPad) @@ -1579,7 +1579,7 @@ int UIScene_SkinSelectMenu::UnlockSkinReturned(void *pParam,int iPad,C4JStorage: const char *pchPackName=wstringtofilename(wStrPackName); SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo((char *)pchPackName); - if (pSONYDLCInfo != NULL) + if (pSONYDLCInfo != nullptr) { char chName[42]; char chKeyName[20]; @@ -1593,7 +1593,7 @@ int UIScene_SkinSelectMenu::UnlockSkinReturned(void *pParam,int iPad,C4JStorage: // while the store is screwed, hardcode the sku //sprintf(chName,"%s-%s-%s",app.GetCommerceCategory(),pSONYDLCInfo->chDLCKeyname,"EURO"); - // MGH - keyname in the DLC file is 16 chars long, but there's no space for a NULL terminating char + // MGH - keyname in the DLC file is 16 chars long, but there's no space for a nullptr terminating char memset(chKeyName, 0, sizeof(chKeyName)); strncpy(chKeyName, pSONYDLCInfo->chDLCKeyname, 16); @@ -1623,7 +1623,7 @@ int UIScene_SkinSelectMenu::UnlockSkinReturned(void *pParam,int iPad,C4JStorage: // need to re-enable input because the user can back out of the store purchase, and we'll be stuck pScene->m_bIgnoreInput = false; // MGH - moved this to outside the pSONYDLCInfo, so we don't get stuck #elif defined _XBOX_ONE - StorageManager.InstallOffer(1,(WCHAR *)(pScene->m_currentPack->getPurchaseOfferId().c_str()), &RenableInput, pScene, NULL); + StorageManager.InstallOffer(1,(WCHAR *)(pScene->m_currentPack->getPurchaseOfferId().c_str()), &RenableInput, pScene, nullptr); #endif } else // Is signed in, but not live. @@ -1642,7 +1642,7 @@ int UIScene_SkinSelectMenu::UnlockSkinReturned(void *pParam,int iPad,C4JStorage: int UIScene_SkinSelectMenu::RenableInput(LPVOID lpVoid, int, int) { - ((UIScene_SkinSelectMenu*) lpVoid)->m_bIgnoreInput = false; + static_cast(lpVoid)->m_bIgnoreInput = false; return 0; } diff --git a/Minecraft.Client/Common/UI/UIScene_TeleportMenu.cpp b/Minecraft.Client/Common/UI/UIScene_TeleportMenu.cpp index f6916d133..017af93ef 100644 --- a/Minecraft.Client/Common/UI/UIScene_TeleportMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_TeleportMenu.cpp @@ -12,7 +12,7 @@ UIScene_TeleportMenu::UIScene_TeleportMenu(int iPad, void *initData, UILayer *pa // Setup all the Iggy references we need for this scene initialiseMovie(); - TeleportMenuInitData *initParam = (TeleportMenuInitData *)initData; + TeleportMenuInitData *initParam = static_cast(initData); m_teleportToPlayer = initParam->teleportToPlayer; @@ -41,7 +41,7 @@ UIScene_TeleportMenu::UIScene_TeleportMenu(int iPad, void *initData, UILayer *pa { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) + if( player != nullptr && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) { m_players[m_playersCount] = player->GetSmallId(); ++m_playersCount; @@ -59,7 +59,7 @@ UIScene_TeleportMenu::UIScene_TeleportMenu(int iPad, void *initData, UILayer *pa } int voiceStatus = 0; - if(player != NULL && player->HasVoice() ) + if(player != nullptr && player->HasVoice() ) { if( player->IsMutedByLocalUser(m_iPad) ) { @@ -131,7 +131,7 @@ void UIScene_TeleportMenu::handleReload() { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) + if( player != nullptr && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) { m_players[m_playersCount] = player->GetSmallId(); ++m_playersCount; @@ -149,7 +149,7 @@ void UIScene_TeleportMenu::handleReload() } int voiceStatus = 0; - if(player != NULL && player->HasVoice() ) + if(player != nullptr && player->HasVoice() ) { if( player->IsMutedByLocalUser(m_iPad) ) { @@ -189,7 +189,7 @@ void UIScene_TeleportMenu::tick() { INetworkPlayer *player = g_NetworkManager.GetPlayerBySmallId( m_players[i] ); - if( player != NULL ) + if( player != nullptr ) { m_players[i] = player->GetSmallId(); @@ -250,11 +250,11 @@ void UIScene_TeleportMenu::handleInput(int iPad, int key, bool repeat, bool pres void UIScene_TeleportMenu::handlePress(F64 controlId, F64 childId) { - app.DebugPrintf("Pressed = %d, %d\n", (int)controlId, (int)childId); - switch((int)controlId) + app.DebugPrintf("Pressed = %d, %d\n", static_cast(controlId), static_cast(childId)); + switch(static_cast(controlId)) { case eControl_GamePlayers: - int currentSelection = (int)childId; + int currentSelection = static_cast(childId); INetworkPlayer *selectedPlayer = g_NetworkManager.GetPlayerBySmallId( m_players[ currentSelection ] ); INetworkPlayer *thisPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(m_iPad); @@ -275,7 +275,7 @@ void UIScene_TeleportMenu::handlePress(F64 controlId, F64 childId) void UIScene_TeleportMenu::OnPlayerChanged(void *callbackParam, INetworkPlayer *pPlayer, bool leaving) { - UIScene_TeleportMenu *scene = (UIScene_TeleportMenu *)callbackParam; + UIScene_TeleportMenu *scene = static_cast(callbackParam); bool playerFound = false; int foundIndex = 0; for(int i = 0; i < scene->m_playersCount; ++i) @@ -320,7 +320,7 @@ void UIScene_TeleportMenu::OnPlayerChanged(void *callbackParam, INetworkPlayer * } int voiceStatus = 0; - if(pPlayer != NULL && pPlayer->HasVoice() ) + if(pPlayer != nullptr && pPlayer->HasVoice() ) { if( pPlayer->IsMutedByLocalUser(scene->m_iPad) ) { diff --git a/Minecraft.Client/Common/UI/UIScene_TradingMenu.cpp b/Minecraft.Client/Common/UI/UIScene_TradingMenu.cpp index 0a35c8e5b..bb9e30af4 100644 --- a/Minecraft.Client/Common/UI/UIScene_TradingMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_TradingMenu.cpp @@ -25,13 +25,13 @@ UIScene_TradingMenu::UIScene_TradingMenu(int iPad, void *_initData, UILayer *par m_labelRequest1.init(L""); m_labelRequest2.init(L""); - TradingScreenInput *initData = (TradingScreenInput *)_initData; + TradingScreenInput *initData = static_cast(_initData); m_merchant = initData->trader; Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[iPad] != NULL ) + if( pMinecraft->localgameModes[iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Trading_Menu, this); } @@ -87,15 +87,15 @@ void UIScene_TradingMenu::handleDestroy() { app.DebugPrintf("UIScene_TradingMenu::handleDestroy\n"); Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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) - if(pMinecraft->localplayers[m_iPad] != NULL) pMinecraft->localplayers[m_iPad]->closeContainer(); + if(pMinecraft->localplayers[m_iPad] != nullptr) pMinecraft->localplayers[m_iPad]->closeContainer(); ui.OverrideSFX(m_iPad,ACTION_MENU_A,false); ui.OverrideSFX(m_iPad,ACTION_MENU_OK,false); @@ -155,11 +155,11 @@ void UIScene_TradingMenu::handleInput(int iPad, int key, bool repeat, bool press void UIScene_TradingMenu::customDraw(IggyCustomDrawCallbackRegion *region) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return; shared_ptr item = nullptr; int slotId = -1; - swscanf((wchar_t*)region->name,L"slot_%d",&slotId); + swscanf(static_cast(region->name),L"slot_%d",&slotId); if(slotId < MerchantMenu::USE_ROW_SLOT_END) { @@ -190,7 +190,7 @@ void UIScene_TradingMenu::customDraw(IggyCustomDrawCallbackRegion *region) }; } } - if(item != NULL) customDrawSlotControl(region,m_iPad,item,1.0f,item->isFoil(),true); + if(item != nullptr) customDrawSlotControl(region,m_iPad,item,1.0f,item->isFoil(),true); } void UIScene_TradingMenu::showScrollRightArrow(bool show) diff --git a/Minecraft.Client/Common/UI/UIScene_TrialExitUpsell.cpp b/Minecraft.Client/Common/UI/UIScene_TrialExitUpsell.cpp index 9ef8f189a..9338daba7 100644 --- a/Minecraft.Client/Common/UI/UIScene_TrialExitUpsell.cpp +++ b/Minecraft.Client/Common/UI/UIScene_TrialExitUpsell.cpp @@ -50,7 +50,7 @@ void UIScene_TrialExitUpsell::handleInput(int iPad, int key, bool repeat, bool p // 4J-PB - need to check this user can access the store #if defined(__PS3__) || defined(__PSVITA__) bool bContentRestricted; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,NULL,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),true,nullptr,&bContentRestricted,nullptr); if(bContentRestricted) { UINT uiIDA[1]; diff --git a/Minecraft.Client/Common/UI/UISplitScreenHelpers.h b/Minecraft.Client/Common/UI/UISplitScreenHelpers.h new file mode 100644 index 000000000..e451b3f2d --- /dev/null +++ b/Minecraft.Client/Common/UI/UISplitScreenHelpers.h @@ -0,0 +1,114 @@ +#pragma once + +// Shared split-screen UI helpers to avoid duplicating viewport math +// across HUD, Chat, Tooltips, and container menus. + +// Compute the raw viewport rectangle for a given viewport type. +inline void GetViewportRect(F32 screenW, F32 screenH, C4JRender::eViewportType viewport, + F32 &originX, F32 &originY, F32 &viewW, F32 &viewH) +{ + originX = originY = 0; + viewW = screenW; + viewH = screenH; + switch(viewport) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + viewH = screenH * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + originY = screenH * 0.5f; viewH = screenH * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + viewW = screenW * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + originX = screenW * 0.5f; viewW = screenW * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + viewW = screenW * 0.5f; viewH = screenH * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + originX = screenW * 0.5f; viewW = screenW * 0.5f; viewH = screenH * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + originY = screenH * 0.5f; viewW = screenW * 0.5f; viewH = screenH * 0.5f; break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + originX = screenW * 0.5f; originY = screenH * 0.5f; + viewW = screenW * 0.5f; viewH = screenH * 0.5f; break; + default: break; + } +} + +// Fit a 16:9 rectangle inside the given dimensions. +inline void Fit16x9(F32 viewW, F32 viewH, S32 &fitW, S32 &fitH, S32 &offsetX, S32 &offsetY) +{ + const F32 kAspect = 16.0f / 9.0f; + if(viewW / viewH > kAspect) + { + fitH = (S32)viewH; + fitW = (S32)(viewH * kAspect); + } + else + { + fitW = (S32)viewW; + fitH = (S32)(viewW / kAspect); + } + offsetX = (S32)((viewW - fitW) * 0.5f); + offsetY = (S32)((viewH - fitH) * 0.5f); +} + +// Convenience: just fit 16:9 dimensions, ignore offsets. +inline void Fit16x9(S32 &width, S32 &height) +{ + S32 offX, offY; + Fit16x9((F32)width, (F32)height, width, height, offX, offY); +} + +// Compute the uniform scale and tileYStart for split-screen tile rendering. +// Used by HUD, Chat, and Tooltips to scale the SWF movie to cover the viewport tile. +inline void ComputeTileScale(S32 tileWidth, S32 tileHeight, S32 movieWidth, S32 movieHeight, + bool needsYTile, F32 &outScale, S32 &outTileYStart) +{ + F32 scaleW = (F32)tileWidth / (F32)movieWidth; + F32 scaleH = (F32)tileHeight / (F32)movieHeight; + F32 scale = (scaleW > scaleH) ? scaleW : scaleH; + if(scale < 1.0f) scale = 1.0f; + + outTileYStart = 0; + if(needsYTile) + { + S32 dispH = (S32)(movieHeight * scale); + outTileYStart = dispH - tileHeight; + if(outTileYStart < 0) outTileYStart = 0; + scaleH = (F32)(outTileYStart + tileHeight) / (F32)movieHeight; + scale = (scaleW > scaleH) ? scaleW : scaleH; + if(scale < 1.0f) scale = 1.0f; + } + + outScale = scale; +} + +// Compute the render offset to center split-screen SWF content in the viewport. +// Used by Chat and Tooltips (HUD uses repositionHud instead). +inline void ComputeSplitContentOffset(C4JRender::eViewportType viewport, S32 movieWidth, S32 movieHeight, + F32 scale, S32 tileWidth, S32 tileHeight, S32 tileYStart, + S32 &outXOffset, S32 &outYOffset) +{ + S32 contentCenterX, contentCenterY; + if(viewport == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || viewport == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT) + { + contentCenterX = (S32)(movieWidth * scale / 4); + contentCenterY = (S32)(movieHeight * scale / 2); + } + else if(viewport == C4JRender::VIEWPORT_TYPE_SPLIT_TOP || viewport == C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM) + { + contentCenterX = (S32)(movieWidth * scale / 2); + contentCenterY = (S32)(movieHeight * scale * 3 / 4); + } + else + { + contentCenterX = (S32)(movieWidth * scale / 4); + contentCenterY = (S32)(movieHeight * scale * 3 / 4); + } + + outXOffset = 0; + outYOffset = 0; + if(viewport == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || viewport == C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT || viewport == C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT) + outXOffset = -(tileWidth / 2 - contentCenterX); + if(viewport == C4JRender::VIEWPORT_TYPE_SPLIT_TOP || viewport == C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT || viewport == C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT) + outYOffset = -(tileHeight / 2 - (contentCenterY - tileYStart)); +} diff --git a/Minecraft.Client/Common/UI/UIString.cpp b/Minecraft.Client/Common/UI/UIString.cpp index 288fa87a9..04d8b8e37 100644 --- a/Minecraft.Client/Common/UI/UIString.cpp +++ b/Minecraft.Client/Common/UI/UIString.cpp @@ -139,7 +139,7 @@ UIString::~UIString() bool UIString::empty() { - return m_core.get() == NULL; + return m_core.get() == nullptr; } bool UIString::compare(const UIString &uiString) @@ -149,19 +149,19 @@ bool UIString::compare(const UIString &uiString) bool UIString::needsUpdating() { - if (m_core != NULL) return m_core->needsUpdating(); + if (m_core != nullptr) return m_core->needsUpdating(); else return false; } void UIString::setUpdated() { - if (m_core != NULL) m_core->setUpdated(); + if (m_core != nullptr) m_core->setUpdated(); } wstring &UIString::getString() { static wstring blank(L""); - if (m_core != NULL) return m_core->getString(); + if (m_core != nullptr) return m_core->getString(); else return blank; } diff --git a/Minecraft.Client/Common/UI/UIStructs.h b/Minecraft.Client/Common/UI/UIStructs.h index b34228329..99c3d7bda 100644 --- a/Minecraft.Client/Common/UI/UIStructs.h +++ b/Minecraft.Client/Common/UI/UIStructs.h @@ -196,8 +196,8 @@ typedef struct _ConnectionProgressParams showTooltips = false; setFailTimer = false; timerTime = 0; - cancelFunc = NULL; - cancelFuncParam = NULL; + cancelFunc = nullptr; + cancelFuncParam = nullptr; } } ConnectionProgressParams; @@ -250,7 +250,7 @@ typedef struct _SaveListDetails _SaveListDetails() { saveId = 0; - pbThumbnailData = NULL; + pbThumbnailData = nullptr; dwThumbnailSize = 0; #ifdef _DURANGO ZeroMemory(UTF16SaveName,sizeof(wchar_t)*128); @@ -406,15 +406,15 @@ typedef struct _LoadingInputParams _LoadingInputParams() { - func = NULL; - lpParam = NULL; - completionData = NULL; + func = nullptr; + lpParam = nullptr; + completionData = nullptr; cancelText = -1; - cancelFunc = NULL; - completeFunc = NULL; - m_cancelFuncParam = NULL; - m_completeFuncParam = NULL; + cancelFunc = nullptr; + completeFunc = nullptr; + m_cancelFuncParam = nullptr; + m_completeFuncParam = nullptr; waitForThreadToDelete = false; } } LoadingInputParams; @@ -442,7 +442,7 @@ typedef struct _TutorialPopupInfo _TutorialPopupInfo() { - interactScene = NULL; + interactScene = nullptr; desc = L""; title = L""; icon = -1; @@ -450,7 +450,7 @@ typedef struct _TutorialPopupInfo isFoil = false; allowFade = true; isReminder = false; - tutorial = NULL; + tutorial = nullptr; } } TutorialPopupInfo; diff --git a/Minecraft.Client/Common/UI/UITTFFont.cpp b/Minecraft.Client/Common/UI/UITTFFont.cpp index 5d72ed97c..359ac76b8 100644 --- a/Minecraft.Client/Common/UI/UITTFFont.cpp +++ b/Minecraft.Client/Common/UI/UITTFFont.cpp @@ -11,9 +11,9 @@ UITTFFont::UITTFFont(const string &name, const string &path, S32 fallbackCharact #ifdef _UNICODE wstring wPath = convStringToWstring(path); - HANDLE file = CreateFile(wPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(wPath.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #else - HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -30,7 +30,7 @@ UITTFFont::UITTFFont(const string &name, const string &path, S32 fallbackCharact DWORD bytesRead; pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(file,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); diff --git a/Minecraft.Client/Common/XUI/XUI_Chat.cpp b/Minecraft.Client/Common/XUI/XUI_Chat.cpp index 3e3faa773..640056217 100644 --- a/Minecraft.Client/Common/XUI/XUI_Chat.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Chat.cpp @@ -5,7 +5,7 @@ HRESULT CScene_Chat::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -37,7 +37,7 @@ HRESULT CScene_Chat::OnTimer( XUIMessageTimer *pXUIMessageTimer, BOOL &bHandled) m_Labels[i].SetOpacity(0); } } - if(pMinecraft->localplayers[m_iPad]!= NULL) + if(pMinecraft->localplayers[m_iPad]!= nullptr) { m_Jukebox.SetText( pGui->getJukeboxMessage(m_iPad).c_str() ); m_Jukebox.SetOpacity( pGui->getJukeboxOpacity(m_iPad) ); diff --git a/Minecraft.Client/Common/XUI/XUI_ConnectingProgress.cpp b/Minecraft.Client/Common/XUI/XUI_ConnectingProgress.cpp index 9a82a7b3b..5ae736a3d 100644 --- a/Minecraft.Client/Common/XUI/XUI_ConnectingProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_ConnectingProgress.cpp @@ -12,7 +12,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_ConnectingProgress::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - ConnectionProgressParams *param = (ConnectionProgressParams *)pInitData->pvInitData; + ConnectionProgressParams *param = static_cast(pInitData->pvInitData); m_iPad = param->iPad; MapChildControls(); @@ -203,7 +203,7 @@ HRESULT CScene_ConnectingProgress::OnTimer( XUIMessageTimer *pTimer, BOOL& bHand UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; #ifdef _XBOX - StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); #endif exitReasonStringId = -1; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JEdit.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JEdit.cpp index cc3afeca4..576b75577 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JEdit.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JEdit.cpp @@ -10,7 +10,7 @@ HRESULT CXuiCtrl4JEdit::OnInit(XUIMessageInit* pInitData, BOOL& rfHandled) // set a limit for the text box m_uTextLimit=XUI_4JEDIT_MAX_CHARS-1; XuiEditSetTextLimit(m_hObj,m_uTextLimit); - // Find the text limit. (Add one for NULL terminator) + // Find the text limit. (Add one for nullptr terminator) //m_uTextLimit = min( XuiEditGetTextLimit(m_hObj) + 1, XUI_4JEDIT_MAX_CHARS); ZeroMemory( wchText , sizeof(WCHAR)*(m_uTextLimit+1) ); @@ -127,7 +127,7 @@ HRESULT CXuiCtrl4JEdit::OnChar(XUIMessageChar* pInputData, BOOL& rfHandled) XuiSendMessage( hBaseObj, &xuiMsg ); rfHandled = TRUE; - SendNotifyValueChanged((int)pInputData->wch); + SendNotifyValueChanged(static_cast(pInputData->wch)); return hr; } @@ -145,7 +145,7 @@ HRESULT CXuiCtrl4JEdit::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled) if( pThis->m_bReadOnly ) return hr; - // Find the text limit. (Add one for NULL terminator) + // Find the text limit. (Add one for nullptr terminator) //m_uTextLimit = min( XuiEditGetTextLimit(m_hObj) + 1, XUI_4JEDIT_MAX_CHARS); if((((pInputData->dwKeyCode == VK_PAD_A) && (pInputData->wch == 0)) || (pInputData->dwKeyCode == VK_PAD_START)) && !(pInputData->dwFlags & XUI_INPUT_FLAG_REPEAT)) @@ -185,14 +185,14 @@ HRESULT CXuiCtrl4JEdit::SendNotifyValueChanged(int iValue) int CXuiCtrl4JEdit::KeyboardReturned(void *pParam,bool bSet) { - CXuiCtrl4JEdit* pClass = (CXuiCtrl4JEdit*)pParam; + CXuiCtrl4JEdit* pClass = static_cast(pParam); HRESULT hr = S_OK; if(bSet) { pClass->SetText(pClass->wchText); // need to move the caret to the end of the newly set text - XuiEditSetCaretPosition(pClass->m_hObj, (int)wcsnlen(pClass->wchText, 50)); + XuiEditSetCaretPosition(pClass->m_hObj, static_cast(wcsnlen(pClass->wchText, 50))); pClass->SendNotifyValueChanged(10); // 10 for a return } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JIcon.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JIcon.cpp index 8895b60e3..a4ff8d376 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JIcon.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JIcon.cpp @@ -3,7 +3,7 @@ HRESULT CXuiCtrl4JIcon::OnInit(XUIMessageInit *pInitData, BOOL& bHandled) { - m_hBrush=NULL; + m_hBrush=nullptr; return S_OK; } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp index 4c615979c..7523c523f 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp @@ -7,7 +7,7 @@ HRESULT CXuiCtrl4JList::OnInit(XUIMessageInit *pInitData, BOOL& bHandled) { InitializeCriticalSection(&m_AccessListData); - m_hSelectionChangedHandlerObj = NULL; + m_hSelectionChangedHandlerObj = nullptr; return S_OK; } @@ -22,13 +22,13 @@ void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFrom if(ItemInfo.pwszText) { - dwLen1=(int)wcslen(ItemInfo.pwszText)*sizeof(WCHAR); + dwLen1=static_cast(wcslen(ItemInfo.pwszText))*sizeof(WCHAR); dwBytes+=dwLen1+sizeof(WCHAR); } if(ItemInfo.pwszImage) { - dwLen2=(int)(wcslen(ItemInfo.pwszImage))*sizeof(WCHAR); + dwLen2=static_cast(wcslen(ItemInfo.pwszImage))*sizeof(WCHAR); dwBytes+=dwLen2+sizeof(WCHAR); } @@ -59,11 +59,11 @@ void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFrom // need to remember the original index of this addition before it gets sorted - this will get used to load the game if(iSortListFromIndex!=-1) { - pItemInfo->iIndex=(int)m_vListData.size()-iSortListFromIndex; + pItemInfo->iIndex=static_cast(m_vListData.size())-iSortListFromIndex; } else { - pItemInfo->iIndex=(int)m_vListData.size(); + pItemInfo->iIndex=static_cast(m_vListData.size()); } // added to force a sort order for DLC @@ -110,7 +110,7 @@ void CXuiCtrl4JList::RemoveAllData( ) { EnterCriticalSection(&m_AccessListData); - int iSize=(int)m_vListData.size(); + int iSize=static_cast(m_vListData.size()); for(int i=0;icItems = (int)m_vListData.size(); + pGetItemCountData->cItems = static_cast(m_vListData.size()); bHandled = TRUE; return S_OK; } @@ -315,7 +315,7 @@ HRESULT CXuiCtrl4JList::OnGetSourceDataImage(XUIMessageGetSourceImage *pGetSourc { // Check for a brush EnterCriticalSection(&m_AccessListData); - if(GetData(pGetSourceImageData->iItem).hXuiBrush!=NULL) + if(GetData(pGetSourceImageData->iItem).hXuiBrush!=nullptr) { pGetSourceImageData->hBrush=GetData(pGetSourceImageData->iItem).hXuiBrush; } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_BrewProgress.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_BrewProgress.cpp index 074b7300b..e74b92b4b 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_BrewProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_BrewProgress.cpp @@ -10,9 +10,9 @@ int CXuiCtrlBrewProgress::GetValue() void* pvUserData; this->GetUserData( &pvUserData ); - if( pvUserData != NULL ) + if( pvUserData != nullptr ) { - BrewingStandTileEntity *pBrewingStandTileEntity = (BrewingStandTileEntity *)pvUserData; + BrewingStandTileEntity *pBrewingStandTileEntity = static_cast(pvUserData); return pBrewingStandTileEntity->getBrewTime(); } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_BubblesProgress.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_BubblesProgress.cpp index cc5d996f3..48a130c42 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_BubblesProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_BubblesProgress.cpp @@ -8,9 +8,9 @@ int CXuiCtrlBubblesProgress::GetValue() void* pvUserData; this->GetUserData( &pvUserData ); - if( pvUserData != NULL ) + if( pvUserData != nullptr ) { - BrewingStandTileEntity *pBrewingStandTileEntity = (BrewingStandTileEntity *)pvUserData; + BrewingStandTileEntity *pBrewingStandTileEntity = static_cast(pvUserData); int value = 0; int bubbleStep = (pBrewingStandTileEntity->getBrewTime() / 2) % 7; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_BurnProgress.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_BurnProgress.cpp index 8e514094c..5a1a36743 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_BurnProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_BurnProgress.cpp @@ -10,9 +10,9 @@ int CXuiCtrlBurnProgress::GetValue() void* pvUserData; this->GetUserData( &pvUserData ); - if( pvUserData != NULL ) + if( pvUserData != nullptr ) { - FurnaceTileEntity *pFurnaceTileEntity = (FurnaceTileEntity *)pvUserData; + FurnaceTileEntity *pFurnaceTileEntity = static_cast(pvUserData); // TODO This param is a magic number in Java but we should really define it somewhere with a name // I think it is the number of states of the progress display (ie the max value) diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_CraftIngredientSlot.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_CraftIngredientSlot.cpp index 82b6c3eda..46bcc9831 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_CraftIngredientSlot.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_CraftIngredientSlot.cpp @@ -11,7 +11,7 @@ CXuiCtrlCraftIngredientSlot::CXuiCtrlCraftIngredientSlot() { m_iID=0; - m_Desc=NULL; + m_Desc=nullptr; m_isFoil = false; m_isDirty = false; m_item = nullptr; @@ -29,7 +29,7 @@ HRESULT CXuiCtrlCraftIngredientSlot::OnInit(XUIMessageInit* pInitData, BOOL& rfH //----------------------------------------------------------------------------- HRESULT CXuiCtrlCraftIngredientSlot::OnCustomMessage_GetSlotItem(CustomMessage_GetSlotItem_Struct *pData, BOOL& bHandled) { - if( m_iID != 0 || m_item != NULL ) + if( m_iID != 0 || m_item != nullptr ) { pData->item = m_item; pData->iItemBitField = MAKE_SLOTDISPLAY_ITEM_BITMASK(m_iID,m_iAuxVal,m_isFoil); @@ -94,7 +94,7 @@ void CXuiCtrlCraftIngredientSlot::SetIcon(int iPad, int iId,int iAuxVal, int iCo void CXuiCtrlCraftIngredientSlot::SetIcon(int iPad, shared_ptr item, int iScale, unsigned int uiAlpha,bool bDecorations, BOOL bShow) { - if(item == NULL) SetIcon(iPad, 0,0,0,0,0,false,false,bShow); + if(item == nullptr) SetIcon(iPad, 0,0,0,0,0,false,false,bShow); else { m_item = item; @@ -118,6 +118,6 @@ void CXuiCtrlCraftIngredientSlot::SetDescription(LPCWSTR Desc) hr=GetVisual(&hObj); XuiElementGetChildById(hObj,L"text_name",&hObjChild); XuiControlSetText(hObjChild,Desc); - XuiElementSetShow(hObjChild,Desc==NULL?FALSE:TRUE); + XuiElementSetShow(hObjChild,Desc==nullptr?FALSE:TRUE); m_Desc=Desc; } \ No newline at end of file diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp index 6c7876c9f..9a312287e 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp @@ -15,10 +15,10 @@ HRESULT CXuiCtrlEnchantmentButton::OnInit(XUIMessageInit* pInitData, BOOL& rfHan Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); HXUIOBJ parent = m_hObj; HXUICLASS hcInventoryClass = XuiFindClass( L"CXuiSceneEnchant" ); @@ -28,13 +28,13 @@ HRESULT CXuiCtrlEnchantmentButton::OnInit(XUIMessageInit* pInitData, BOOL& rfHan { XuiElementGetParent(parent,&parent); currentClass = XuiGetObjectClass( parent ); - } while (parent != NULL && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); + } while (parent != nullptr && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); - assert( parent != NULL ); + assert( parent != nullptr ); VOID *pObj; XuiObjectFromHandle( parent, &pObj ); - m_containerScene = (CXuiSceneEnchant *)pObj; + m_containerScene = static_cast(pObj); m_index = 0; m_lastCost = 0; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentBook.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentBook.cpp index 8a56a0ead..a83b7811e 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentBook.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentBook.cpp @@ -30,12 +30,12 @@ CXuiCtrlEnchantmentBook::CXuiCtrlEnchantmentBook() : Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); - model = NULL; + model = nullptr; time = 0; flip = oFlip = flipT = flipA = 0.0f; @@ -44,7 +44,7 @@ CXuiCtrlEnchantmentBook::CXuiCtrlEnchantmentBook() : CXuiCtrlEnchantmentBook::~CXuiCtrlEnchantmentBook() { - //if(model != NULL) delete model; + //if(model != nullptr) delete model; } //----------------------------------------------------------------------------- @@ -60,13 +60,13 @@ HRESULT CXuiCtrlEnchantmentBook::OnInit(XUIMessageInit* pInitData, BOOL& rfHandl { XuiElementGetParent(parent,&parent); currentClass = XuiGetObjectClass( parent ); - } while (parent != NULL && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); + } while (parent != nullptr && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); - assert( parent != NULL ); + assert( parent != nullptr ); VOID *pObj; XuiObjectFromHandle( parent, &pObj ); - m_containerScene = (CXuiSceneEnchant *)pObj; + m_containerScene = static_cast(pObj); last = nullptr; @@ -166,12 +166,12 @@ HRESULT CXuiCtrlEnchantmentBook::OnRender(XUIMessageRender *pRenderData, BOOL &b glEnable(GL_CULL_FACE); - if(model == NULL) + if(model == nullptr) { // Share the model the the EnchantTableRenderer EnchantTableRenderer *etr = (EnchantTableRenderer*)TileEntityRenderDispatcher::instance->getRenderer(eTYPE_ENCHANTMENTTABLEENTITY); - if(etr != NULL) + if(etr != nullptr) { model = etr->bookModel; } @@ -181,7 +181,7 @@ HRESULT CXuiCtrlEnchantmentBook::OnRender(XUIMessageRender *pRenderData, BOOL &b } } - model->render(NULL, 0, ff1, ff2, o, 0, 1 / 16.0f,true); + model->render(nullptr, 0, ff1, ff2, o, 0, 1 / 16.0f,true); glDisable(GL_CULL_FACE); glPopMatrix(); @@ -281,7 +281,7 @@ HRESULT CXuiCtrlEnchantmentBook::OnRender(XUIMessageRender *pRenderData, BOOL &b // // glEnable(GL_RESCALE_NORMAL); // -// model.render(NULL, 0, ff1, ff2, o, 0, 1 / 16.0f,true); +// model.render(nullptr, 0, ff1, ff2, o, 0, 1 / 16.0f,true); // // glDisable(GL_RESCALE_NORMAL); // Lighting::turnOff(); diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp index 60156a0af..ecb6132d7 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp @@ -25,10 +25,10 @@ HRESULT CXuiCtrlEnchantmentButtonText::OnInit(XUIMessageInit* pInitData, BOOL& r Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); HXUIOBJ parent = m_hObj; HXUICLASS hcInventoryClass = XuiFindClass( L"CXuiCtrlEnchantmentButton" ); @@ -38,13 +38,13 @@ HRESULT CXuiCtrlEnchantmentButtonText::OnInit(XUIMessageInit* pInitData, BOOL& r { XuiElementGetParent(parent,&parent); currentClass = XuiGetObjectClass( parent ); - } while (parent != NULL && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); + } while (parent != nullptr && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); - assert( parent != NULL ); + assert( parent != nullptr ); VOID *pObj; XuiObjectFromHandle( parent, &pObj ); - m_parentControl = (CXuiCtrlEnchantmentButton *)pObj; + m_parentControl = static_cast(pObj); m_lastCost = 0; m_enchantmentString = L""; @@ -75,10 +75,10 @@ HRESULT CXuiCtrlEnchantmentButtonText::OnRender(XUIMessageRender *pRenderData, B // 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; - clearRect.x1 = (int)(matrix._41) - 2; - clearRect.y1 = (int)(matrix._42) - 2; - clearRect.x2 = (int)(matrix._41 + ( bwidth * matrix._11 )) + 2; - clearRect.y2 = (int)(matrix._42 + ( bheight * matrix._22 )) + 2; + clearRect.x1 = static_cast(matrix._41) - 2; + clearRect.y1 = static_cast(matrix._42) - 2; + clearRect.x2 = static_cast(matrix._41 + (bwidth * matrix._11)) + 2; + clearRect.y2 = static_cast(matrix._42 + (bheight * matrix._22)) + 2; RenderManager.Clear(GL_DEPTH_BUFFER_BIT, &clearRect); // glClear(GL_DEPTH_BUFFER_BIT); diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_FireProgress.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_FireProgress.cpp index b125af39c..3d55db197 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_FireProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_FireProgress.cpp @@ -10,9 +10,9 @@ int CXuiCtrlFireProgress::GetValue() void* pvUserData; this->GetUserData( &pvUserData ); - if( pvUserData != NULL ) + if( pvUserData != nullptr ) { - FurnaceTileEntity *pFurnaceTileEntity = (FurnaceTileEntity *)pvUserData; + FurnaceTileEntity *pFurnaceTileEntity = static_cast(pvUserData); // TODO This param is a magic number in Java but we should really define it somewhere with a name // I think it is the number of states of the progress display (ie the max value) diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftPlayer.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftPlayer.cpp index 02ee7c938..98ff1c267 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftPlayer.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftPlayer.cpp @@ -22,10 +22,10 @@ CXuiCtrlMinecraftPlayer::CXuiCtrlMinecraftPlayer() : Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); } //----------------------------------------------------------------------------- @@ -41,13 +41,13 @@ HRESULT CXuiCtrlMinecraftPlayer::OnInit(XUIMessageInit* pInitData, BOOL& rfHandl { XuiElementGetParent(parent,&parent); currentClass = XuiGetObjectClass( parent ); - } while (parent != NULL && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); + } while (parent != nullptr && !XuiClassDerivesFrom( currentClass, hcInventoryClass ) ); - assert( parent != NULL ); + assert( parent != nullptr ); VOID *pObj; XuiObjectFromHandle( parent, &pObj ); - m_containerScene = (CXuiSceneInventory *)pObj; + m_containerScene = static_cast(pObj); m_iPad = m_containerScene->getPad(); @@ -116,7 +116,7 @@ HRESULT CXuiCtrlMinecraftPlayer::OnRender(XUIMessageRender *pRenderData, BOOL &b // // for(int i=0;ilocalplayers[i] != NULL) +// if(pMinecraft->localplayers[i] != nullptr) // { // iPlayerC++; // } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp index 0acd250f2..1fa44d3f7 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp @@ -30,10 +30,10 @@ CXuiCtrlMinecraftSkinPreview::CXuiCtrlMinecraftSkinPreview() : Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); m_customTextureUrl = L"default"; m_backupTexture = TN_MOB_CHAR; @@ -62,7 +62,7 @@ CXuiCtrlMinecraftSkinPreview::CXuiCtrlMinecraftSkinPreview() : m_fOriginalRotation = 0.0f; m_framesAnimatingRotation = 0; m_bAnimatingToFacing = false; - m_pvAdditionalModelParts=NULL; + m_pvAdditionalModelParts=nullptr; m_uiAnimOverrideBitmask=0L; } @@ -137,7 +137,7 @@ void CXuiCtrlMinecraftSkinPreview::SetFacing(ESkinPreviewFacing facing, bool bAn void CXuiCtrlMinecraftSkinPreview::CycleNextAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation + 1); + m_currentAnimation = static_cast(m_currentAnimation + 1); if(m_currentAnimation >= e_SkinPreviewAnimation_Count) m_currentAnimation = e_SkinPreviewAnimation_Walking; m_swingTime = 0.0f; @@ -145,8 +145,8 @@ void CXuiCtrlMinecraftSkinPreview::CycleNextAnimation() void CXuiCtrlMinecraftSkinPreview::CyclePreviousAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); - if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = (ESkinPreviewAnimations)(e_SkinPreviewAnimation_Count - 1); + m_currentAnimation = static_cast(m_currentAnimation - 1); + if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = static_cast(e_SkinPreviewAnimation_Count - 1); m_swingTime = 0.0f; } @@ -241,7 +241,7 @@ HRESULT CXuiCtrlMinecraftSkinPreview::OnRender(XUIMessageRender *pRenderData, BO Lighting::turnOn(); //glRotatef(-45 - 90, 0, 1, 0); - glRotatef(-(float)m_xRot, 1, 0, 0); + glRotatef(-static_cast(m_xRot), 1, 0, 0); // 4J Stu - Turning on hideGui while we do this stops the name rendering in split-screen bool wasHidingGui = pMinecraft->options->hideGui; @@ -249,7 +249,7 @@ HRESULT CXuiCtrlMinecraftSkinPreview::OnRender(XUIMessageRender *pRenderData, BO //EntityRenderDispatcher::instance->render(pMinecraft->localplayers[0], 0, 0, 0, 0, 1); EntityRenderer *renderer = EntityRenderDispatcher::instance->getRenderer(eTYPE_PLAYER); - if (renderer != NULL) + if (renderer != nullptr) { // 4J-PB - any additional parts to turn on for this player (skin dependent) //vector *pAdditionalModelParts=mob->GetAdditionalModelParts(); @@ -294,12 +294,12 @@ void CXuiCtrlMinecraftSkinPreview::render(EntityRenderer *renderer, double x, do glPushMatrix(); glDisable(GL_CULL_FACE); - HumanoidModel *model = (HumanoidModel *)renderer->getModel(); + HumanoidModel *model = static_cast(renderer->getModel()); //getAttackAnim(mob, a); - //if (armor != NULL) armor->attackTime = model->attackTime; + //if (armor != nullptr) armor->attackTime = model->attackTime; //model->riding = mob->isRiding(); - //if (armor != NULL) armor->riding = model->riding; + //if (armor != nullptr) armor->riding = model->riding; // 4J Stu - Remember to reset these values once the rendering is done if you add another one model->attackTime = 0; @@ -329,7 +329,7 @@ void CXuiCtrlMinecraftSkinPreview::render(EntityRenderer *renderer, double x, do { m_swingTime = 0; } - model->attackTime = m_swingTime / (float) (Player::SWING_DURATION * 3); + model->attackTime = m_swingTime / static_cast(Player::SWING_DURATION * 3); break; default: break; @@ -343,7 +343,7 @@ void CXuiCtrlMinecraftSkinPreview::render(EntityRenderer *renderer, double x, do //setupPosition(mob, x, y, z); // is equivalent to - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); //float bob = getBob(mob, a); #ifdef SKIN_PREVIEW_BOB_ANIM @@ -415,11 +415,11 @@ void CXuiCtrlMinecraftSkinPreview::render(EntityRenderer *renderer, double x, do double xa = sin(yr * PI / 180); double za = -cos(yr * PI / 180); - float flap = (float) yd * 10; + float flap = static_cast(yd) * 10; if (flap < -6) flap = -6; if (flap > 32) flap = 32; - float lean = (float) (xd * xa + zd * za) * 100; - float lean2 = (float) (xd * za - zd * xa) * 100; + float lean = static_cast(xd * xa + zd * za) * 100; + float lean2 = static_cast(xd * za - zd * xa) * 100; if (lean < 0) lean = 0; //float pow = 1;//mob->oBob + (bob - mob->oBob) * a; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSlot.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSlot.cpp index 84273eb57..9b64dbcb5 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSlot.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSlot.cpp @@ -40,7 +40,7 @@ LPCWSTR CXuiCtrlMinecraftSlot::xzpIcons[15]= //----------------------------------------------------------------------------- CXuiCtrlMinecraftSlot::CXuiCtrlMinecraftSlot() : - //m_hBrush(NULL), + //m_hBrush(nullptr), m_bDirty(FALSE), m_iPassThroughDataAssociation(0), m_iPassThroughIdAssociation(0), @@ -60,10 +60,10 @@ CXuiCtrlMinecraftSlot::CXuiCtrlMinecraftSlot() : Minecraft *pMinecraft=Minecraft::GetInstance(); - if(pMinecraft != NULL) + if(pMinecraft != nullptr) { - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fScreenHeight=(float)pMinecraft->height_phys; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fScreenHeight=static_cast(pMinecraft->height_phys); m_bScreenWidthSetup = true; } } @@ -109,14 +109,14 @@ HRESULT CXuiCtrlMinecraftSlot::OnGetSourceImage(XUIMessageGetSourceImage* pData, pData->szPath = MsgGetSlotItem.szPath; pData->bDirty = MsgGetSlotItem.bDirty; - if(MsgGetSlotItem.item != NULL) + if(MsgGetSlotItem.item != nullptr) { m_item = MsgGetSlotItem.item; m_iID = m_item->id; m_iPad = GET_SLOTDISPLAY_USERINDEX_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); - m_fAlpha = ((float)GET_SLOTDISPLAY_ALPHA_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/31.0f; + m_fAlpha = static_cast(GET_SLOTDISPLAY_ALPHA_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/31.0f; m_bDecorations = GET_SLOTDISPLAY_DECORATIONS_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); - m_fScale = ((float)GET_SLOTDISPLAY_SCALE_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/10.0f; + m_fScale = static_cast(GET_SLOTDISPLAY_SCALE_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/10.0f; } else { @@ -128,10 +128,10 @@ HRESULT CXuiCtrlMinecraftSlot::OnGetSourceImage(XUIMessageGetSourceImage* pData, // 4J Stu - Some parent controls may overide this, others will leave it as what we passed in m_iPad = GET_SLOTDISPLAY_USERINDEX_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); - m_fAlpha = ((float)GET_SLOTDISPLAY_ALPHA_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/31.0f; + m_fAlpha = static_cast(GET_SLOTDISPLAY_ALPHA_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/31.0f; m_bDecorations = GET_SLOTDISPLAY_DECORATIONS_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); m_iCount = GET_SLOTDISPLAY_COUNT_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); - m_fScale = ((float)GET_SLOTDISPLAY_SCALE_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/10.0f; + m_fScale = static_cast(GET_SLOTDISPLAY_SCALE_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField))/10.0f; m_popTime = GET_SLOTDISPLAY_POPTIME_FROM_DATA_BITMASK(MsgGetSlotItem.iDataBitField); m_iAuxVal = GET_SLOTDISPLAY_AUXVAL_FROM_ITEM_BITMASK(MsgGetSlotItem.iItemBitField); @@ -145,7 +145,7 @@ HRESULT CXuiCtrlMinecraftSlot::OnGetSourceImage(XUIMessageGetSourceImage* pData, pData->szPath = xzpIcons[m_iID-32000]; } - if(m_item != NULL && (m_item->id != m_iID || m_item->getAuxValue() != m_iAuxVal || m_item->GetCount() != m_iCount) ) m_item = nullptr; + if(m_item != nullptr && (m_item->id != m_iID || m_item->getAuxValue() != m_iAuxVal || m_item->GetCount() != m_iCount) ) m_item = nullptr; } @@ -184,11 +184,11 @@ HRESULT CXuiCtrlMinecraftSlot::OnRender(XUIMessageRender *pRenderData, BOOL &bHa hr = XuiSendMessage(m_hObj, &Message); // We cannot have an Item with id 0 - if(m_item != NULL || (m_iID > 0 && m_iID<32000) ) + if(m_item != nullptr || (m_iID > 0 && m_iID<32000) ) { HXUIDC hDC = pRenderData->hDC; CXuiControl xuiControl(m_hObj); - if(m_item == NULL) m_item = shared_ptr( new ItemInstance(m_iID, m_iCount, m_iAuxVal) ); + if(m_item == nullptr) m_item = std::make_shared(m_iID, m_iCount, m_iAuxVal); // build and render with the game call @@ -217,18 +217,18 @@ HRESULT CXuiCtrlMinecraftSlot::OnRender(XUIMessageRender *pRenderData, BOOL &bHa // 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; - clearRect.x1 = (int)(matrix._41) - 2; - clearRect.y1 = (int)(matrix._42) - 2; - clearRect.x2 = (int)(matrix._41 + ( bwidth * matrix._11 )) + 2; - clearRect.y2 = (int)(matrix._42 + ( bheight * matrix._22 )) + 2; + clearRect.x1 = static_cast(matrix._41) - 2; + clearRect.y1 = static_cast(matrix._42) - 2; + clearRect.x2 = static_cast(matrix._41 + (bwidth * matrix._11)) + 2; + clearRect.y2 = static_cast(matrix._42 + (bheight * matrix._22)) + 2; if(!m_bScreenWidthSetup) { Minecraft *pMinecraft=Minecraft::GetInstance(); - if(pMinecraft != NULL) + if(pMinecraft != nullptr) { - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fScreenHeight=(float)pMinecraft->height_phys; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fScreenHeight=static_cast(pMinecraft->height_phys); m_bScreenWidthSetup = true; } } @@ -261,14 +261,14 @@ HRESULT CXuiCtrlMinecraftSlot::OnRender(XUIMessageRender *pRenderData, BOOL &bHa if (pop > 0) { glPushMatrix(); - float squeeze = 1 + pop / (float) Inventory::POP_TIME_DURATION; + float squeeze = 1 + pop / static_cast(Inventory::POP_TIME_DURATION); float sx = x; float sy = y; float sxoffs = 8 * scaleX; float syoffs = 12 * scaleY; - glTranslatef((float)(sx + sxoffs), (float)(sy + syoffs), 0); + glTranslatef(static_cast(sx + sxoffs), static_cast(sy + syoffs), 0); glScalef(1 / squeeze, (squeeze + 1) / 2, 1); - glTranslatef((float)-(sx + sxoffs), (float)-(sy + syoffs), 0); + glTranslatef(static_cast(-(sx + sxoffs)), static_cast(-(sy + syoffs)), 0); } m_pItemRenderer->renderAndDecorateItem(pMinecraft->font, pMinecraft->textures, m_item, x, y,scaleX,scaleY,m_fAlpha,m_isFoil,false); @@ -284,15 +284,15 @@ HRESULT CXuiCtrlMinecraftSlot::OnRender(XUIMessageRender *pRenderData, BOOL &bHa { glPushMatrix(); glScalef(scaleX, scaleY, 1.0f); - int iX= (int)(0.5f+((float)x)/scaleX); - int iY= (int)(0.5f+((float)y)/scaleY); + int iX= static_cast(0.5f + ((float)x) / scaleX); + int iY= static_cast(0.5f + ((float)y) / scaleY); m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, m_item, iX, iY, m_fAlpha); glPopMatrix(); } else { - m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, m_item, (int)x, (int)y, m_fAlpha); + m_pItemRenderer->renderGuiItemDecorations(pMinecraft->font, pMinecraft->textures, m_item, static_cast(x), static_cast(y), m_fAlpha); } } @@ -329,9 +329,9 @@ void CXuiCtrlMinecraftSlot::SetIcon(int iPad, int iId,int iAuxVal, int iCount, i m_iAuxVal = 0; m_iCount=iCount; - m_fScale = (float)(iScale)/10.0f; + m_fScale = static_cast(iScale)/10.0f; //m_uiAlpha=uiAlpha; - m_fAlpha =((float)(uiAlpha)) / 255.0f; + m_fAlpha =static_cast(uiAlpha) / 255.0f; m_bDecorations = bDecorations; // mif(bDecorations) m_iDecorations=1; // else m_iDecorations=0; @@ -348,8 +348,8 @@ void CXuiCtrlMinecraftSlot::SetIcon(int iPad, shared_ptr item, int m_item = item; m_isFoil = item->isFoil(); m_iPad = iPad; - m_fScale = (float)(iScale)/10.0f; - m_fAlpha =((float)(uiAlpha)) / 31; + m_fScale = static_cast(iScale)/10.0f; + m_fAlpha =static_cast(uiAlpha) / 31; m_bDecorations = bDecorations; m_bDirty = TRUE; XuiElementSetShow(m_hObj,bShow); diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_MobEffect.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_MobEffect.cpp index 23b225738..6a76980dd 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_MobEffect.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_MobEffect.cpp @@ -38,9 +38,9 @@ HRESULT CXuiCtrlMobEffect::OnGetSourceDataText(XUIMessageGetSourceText *pGetSour pGetSourceTextData->szText = m_name.c_str(); pGetSourceTextData->bDisplay = TRUE; - if(FAILED(PlayVisualRange(iconFrameNames[m_icon],NULL,iconFrameNames[m_icon]))) + if(FAILED(PlayVisualRange(iconFrameNames[m_icon],nullptr,iconFrameNames[m_icon]))) { - PlayVisualRange(L"Normal",NULL,L"Normal"); + PlayVisualRange(L"Normal",nullptr,L"Normal"); } bHandled = TRUE; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SliderWrapper.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_SliderWrapper.cpp index a4e9f6be3..18995854c 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SliderWrapper.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SliderWrapper.cpp @@ -10,11 +10,11 @@ HRESULT CXuiCtrlSliderWrapper::OnInit( XUIMessageInit* pInitData, BOOL& bHandled XuiElementGetChildById(m_hObj,L"FocusSink",&hObjChild); XuiObjectFromHandle( hObjChild, &pObj ); - m_pFocusSink = (CXuiControl *)pObj; + m_pFocusSink = static_cast(pObj); XuiElementGetChildById(m_hObj,L"XuiSlider",&hObjChild); XuiObjectFromHandle( hObjChild, &pObj ); - m_pSlider = (CXuiSlider *)pObj; + m_pSlider = static_cast(pObj); m_sliderActive = false; m_bDisplayVal=true; @@ -119,7 +119,7 @@ HRESULT CXuiCtrlSliderWrapper::SetValueDisplay( BOOL bShow ) hr=XuiControlGetVisual(pThis->m_pSlider->m_hObj,&hVisual); hr=XuiElementGetChildById(hVisual,L"Text_Value",&hText); - if(hText!=NULL) + if(hText!=nullptr) { XuiElementSetShow(hText,bShow); } @@ -132,7 +132,7 @@ LPCWSTR CXuiCtrlSliderWrapper::GetText( ) CXuiCtrlSliderWrapper *pThis; HRESULT hr = XuiObjectFromHandle(m_hObj, (void **) &pThis); if (FAILED(hr)) - return NULL; + return nullptr; return pThis->m_pSlider->GetText(); //return S_OK; } @@ -159,7 +159,7 @@ HXUIOBJ CXuiCtrlSliderWrapper::GetSlider() CXuiCtrlSliderWrapper *pThis; HRESULT hr = XuiObjectFromHandle(m_hObj, (void **) &pThis); if (FAILED(hr)) - return NULL; + return nullptr; return pThis->m_pSlider->m_hObj; } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp index f8ceeb69d..8a45d6fcb 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp @@ -12,7 +12,7 @@ HRESULT CXuiCtrlSlotItemCtrlBase::OnInit( HXUIOBJ hObj, XUIMessageInit* pInitDat { HRESULT hr = S_OK; SlotControlUserDataContainer* pvUserData = new SlotControlUserDataContainer(); - hr = XuiElementSetUserData(hObj, (void *)pvUserData ); + hr = XuiElementSetUserData(hObj, static_cast(pvUserData) ); // 4J WESTY : Pointer Prototype : Added to support prototype only. m_bSkipDefaultNavigation = false; @@ -26,7 +26,7 @@ HRESULT CXuiCtrlSlotItemCtrlBase::OnDestroy( HXUIOBJ hObj ) void* pvUserData; hr = XuiElementGetUserData( hObj, &pvUserData ); - if( pvUserData != NULL ) + if( pvUserData != nullptr ) { delete pvUserData; } @@ -41,19 +41,19 @@ HRESULT CXuiCtrlSlotItemCtrlBase::OnCustomMessage_GetSlotItem(HXUIOBJ hObj, Cust void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); - if( pUserDataContainer->slot != NULL ) + if( pUserDataContainer->slot != nullptr ) { item = pUserDataContainer->slot->getItem(); } else if(pUserDataContainer->m_iPad >= 0 && pUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad] ); - if(player != NULL) item = player->inventory->getCarried(); + if(player != nullptr) item = player->inventory->getCarried(); } - if( item != NULL ) + if( item != nullptr ) { pData->item = item; pData->iItemBitField = MAKE_SLOTDISPLAY_ITEM_BITMASK(item->id,item->getAuxValue(),item->isFoil()); @@ -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, static_cast(31 * pUserDataContainer->m_fAlpha),true,item->GetCount(),7,item->popTime); } else { @@ -82,7 +82,7 @@ void CXuiCtrlSlotItemCtrlBase::SetSlot( HXUIOBJ hObj, Slot* slot ) void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); pUserDataContainer->slot = slot; } @@ -92,7 +92,7 @@ void CXuiCtrlSlotItemCtrlBase::SetUserIndex( HXUIOBJ hObj, int iPad ) void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); pUserDataContainer->m_iPad = iPad; } @@ -102,7 +102,7 @@ void CXuiCtrlSlotItemCtrlBase::SetAlpha( HXUIOBJ hObj, float fAlpha ) void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); pUserDataContainer->m_fAlpha = fAlpha; } @@ -111,16 +111,16 @@ bool CXuiCtrlSlotItemCtrlBase::isEmpty( HXUIOBJ hObj ) { void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); - if(pUserDataContainer->slot != NULL) + if(pUserDataContainer->slot != nullptr) { return !pUserDataContainer->slot->hasItem(); } else if(pUserDataContainer->m_iPad >= 0 && pUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad] ); - if(player != NULL) return player->inventory->getCarried() == NULL; + if(player != nullptr) return player->inventory->getCarried() == nullptr; } return true; @@ -130,9 +130,9 @@ wstring CXuiCtrlSlotItemCtrlBase::GetItemDescription( HXUIOBJ hObj, vector(pvUserData); - if(pUserDataContainer->slot != NULL) + if(pUserDataContainer->slot != nullptr) { wstring desc = L""; vector *strings = pUserDataContainer->slot->getItem()->getHoverText(Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad], false, unformattedStrings); @@ -167,10 +167,10 @@ wstring CXuiCtrlSlotItemCtrlBase::GetItemDescription( HXUIOBJ hObj, vectorm_iPad >= 0 && pUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad] ); - if(player != NULL) + if(player != nullptr) { shared_ptr item = player->inventory->getCarried(); - if(item != NULL) return app.GetString( item->getDescriptionId() ); + if(item != nullptr) return app.GetString( item->getDescriptionId() ); } } @@ -181,16 +181,16 @@ shared_ptr CXuiCtrlSlotItemCtrlBase::getItemInstance( HXUIOBJ hObj { void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); - if(pUserDataContainer->slot != NULL) + if(pUserDataContainer->slot != nullptr) { return pUserDataContainer->slot->getItem(); } else if(pUserDataContainer->m_iPad >= 0 && pUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad] ); - if(player != NULL) return player->inventory->getCarried(); + if(player != nullptr) return player->inventory->getCarried(); } return nullptr; @@ -200,7 +200,7 @@ Slot *CXuiCtrlSlotItemCtrlBase::getSlot( HXUIOBJ hObj ) { void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); return pUserDataContainer->slot; } @@ -254,11 +254,11 @@ int CXuiCtrlSlotItemCtrlBase::GetObjectCount( HXUIOBJ hObj ) { void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); int iCount = 0; - if(pUserDataContainer->slot != NULL) + if(pUserDataContainer->slot != nullptr) { if ( pUserDataContainer->slot->hasItem() ) { @@ -268,7 +268,7 @@ int CXuiCtrlSlotItemCtrlBase::GetObjectCount( HXUIOBJ hObj ) else if(pUserDataContainer->m_iPad >= 0 && pUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad] ); - if(player != NULL && player->inventory->getCarried() != NULL) + if(player != nullptr && player->inventory->getCarried() != nullptr) { iCount = player->inventory->getCarried()->count; } @@ -294,9 +294,9 @@ bool CXuiCtrlSlotItemCtrlBase::IsSameItemAs( HXUIOBJ hThisObj, HXUIOBJ hOtherObj // Get the info on this item. void* pvThisUserData; XuiElementGetUserData( hThisObj, &pvThisUserData ); - SlotControlUserDataContainer* pThisUserDataContainer = (SlotControlUserDataContainer*)pvThisUserData; + SlotControlUserDataContainer* pThisUserDataContainer = static_cast(pvThisUserData); - if(pThisUserDataContainer->slot != NULL) + if(pThisUserDataContainer->slot != nullptr) { if ( pThisUserDataContainer->slot->hasItem() ) { @@ -309,7 +309,7 @@ bool CXuiCtrlSlotItemCtrlBase::IsSameItemAs( HXUIOBJ hThisObj, HXUIOBJ hOtherObj else if(pThisUserDataContainer->m_iPad >= 0 && pThisUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pThisUserDataContainer->m_iPad] ); - if(player != NULL && player->inventory->getCarried() != NULL) + if(player != nullptr && player->inventory->getCarried() != nullptr) { iThisID = player->inventory->getCarried()->id; iThisAux = player->inventory->getCarried()->getAuxValue(); @@ -322,9 +322,9 @@ bool CXuiCtrlSlotItemCtrlBase::IsSameItemAs( HXUIOBJ hThisObj, HXUIOBJ hOtherObj // Get the info on other item. void* pvOtherUserData; XuiElementGetUserData( hOtherObj, &pvOtherUserData ); - SlotControlUserDataContainer* pOtherUserDataContainer = (SlotControlUserDataContainer*)pvOtherUserData; + SlotControlUserDataContainer* pOtherUserDataContainer = static_cast(pvOtherUserData); - if(pOtherUserDataContainer->slot != NULL) + if(pOtherUserDataContainer->slot != nullptr) { if ( pOtherUserDataContainer->slot->hasItem() ) { @@ -336,7 +336,7 @@ bool CXuiCtrlSlotItemCtrlBase::IsSameItemAs( HXUIOBJ hThisObj, HXUIOBJ hOtherObj else if(pOtherUserDataContainer->m_iPad >= 0 && pOtherUserDataContainer->m_iPad < XUSER_MAX_COUNT) { shared_ptr player = dynamic_pointer_cast( Minecraft::GetInstance()->localplayers[pOtherUserDataContainer->m_iPad] ); - if(player != NULL && player->inventory->getCarried() != NULL) + if(player != nullptr && player->inventory->getCarried() != nullptr) { iOtherID = player->inventory->getCarried()->id; iOtherAux = player->inventory->getCarried()->getAuxValue(); @@ -363,13 +363,13 @@ int CXuiCtrlSlotItemCtrlBase::GetEmptyStackSpace( HXUIOBJ hObj ) void* pvUserData; XuiElementGetUserData( hObj, &pvUserData ); - SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; + SlotControlUserDataContainer* pUserDataContainer = static_cast(pvUserData); int iCount = 0; int iMaxStackSize = 0; bool bStackable = false; - if(pUserDataContainer->slot != NULL) + if(pUserDataContainer->slot != nullptr) { if ( pUserDataContainer->slot->hasItem() ) { diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.h b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.h index 2fd217494..ac237ac92 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.h +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.h @@ -9,7 +9,7 @@ class ItemInstance; class SlotControlUserDataContainer { public: - SlotControlUserDataContainer() : slot( NULL ), hProgressBar( NULL ), m_iPad( -1 ), m_fAlpha(1.0f) {}; + SlotControlUserDataContainer() : slot( nullptr ), hProgressBar( nullptr ), m_iPad( -1 ), m_fAlpha(1.0f) {}; Slot* slot; HXUIOBJ hProgressBar; float m_fAlpha; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotList.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotList.cpp index 7e51c8850..a34f2a7e4 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotList.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotList.cpp @@ -103,7 +103,7 @@ void CXuiCtrlSlotList::SetData(int m_iPad, AbstractContainerMenu* menu, int rows slotControl->SetUserIndex( slotControl->m_hObj, m_iPad ); - slotControl = NULL; + slotControl = nullptr; } } @@ -226,6 +226,6 @@ void CXuiCtrlSlotList::GetCXuiCtrlSlotItem(int itemIndex, CXuiCtrlSlotItemListIt HXUIOBJ itemControl = this->GetItemControl(itemIndex); VOID *pObj; XuiObjectFromHandle( itemControl, &pObj ); - *CXuiCtrlSlotItem = (CXuiCtrlSlotItemListItem *)pObj; + *CXuiCtrlSlotItem = static_cast(pObj); } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SplashPulser.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_SplashPulser.cpp index 2e9717107..874edc6f0 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SplashPulser.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SplashPulser.cpp @@ -20,10 +20,10 @@ CXuiCtrlSplashPulser::CXuiCtrlSplashPulser() : Minecraft *pMinecraft=Minecraft::GetInstance(); ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); - m_fScreenWidth=(float)pMinecraft->width_phys; - m_fRawWidth=(float)ssc.rawWidth; - m_fScreenHeight=(float)pMinecraft->height_phys; - m_fRawHeight=(float)ssc.rawHeight; + m_fScreenWidth=static_cast(pMinecraft->width_phys); + m_fRawWidth=static_cast(ssc.rawWidth); + m_fScreenHeight=static_cast(pMinecraft->height_phys); + m_fRawHeight=static_cast(ssc.rawHeight); } //----------------------------------------------------------------------------- diff --git a/Minecraft.Client/Common/XUI/XUI_CustomMessages.h b/Minecraft.Client/Common/XUI/XUI_CustomMessages.h index 888f8ad00..e16f891c3 100644 --- a/Minecraft.Client/Common/XUI/XUI_CustomMessages.h +++ b/Minecraft.Client/Common/XUI/XUI_CustomMessages.h @@ -39,11 +39,11 @@ CustomMessage_GetSlotItem_Struct; static __declspec(noinline) void CustomMessage_GetSlotItem(XUIMessage *pMsg, CustomMessage_GetSlotItem_Struct* pData, int iDataBitField, int iItemBitField) { XuiMessage(pMsg,XM_GETSLOTITEM_MESSAGE); - _XuiMessageExtra(pMsg,(XUIMessageData*) pData, sizeof(*pData)); + _XuiMessageExtra(pMsg,static_cast(pData), sizeof(*pData)); pData->item = nullptr; pData->iDataBitField = iDataBitField; pData->iItemBitField = iItemBitField; - pData->szPath = NULL; + pData->szPath = nullptr; pData->bDirty = false; } @@ -68,7 +68,7 @@ CustomMessage_Splitscreenplayer_Struct; static __declspec(noinline) void CustomMessage_Splitscreenplayer(XUIMessage *pMsg, CustomMessage_Splitscreenplayer_Struct* pData, bool bJoining) { XuiMessage(pMsg,XM_SPLITSCREENPLAYER_MESSAGE); - _XuiMessageExtra(pMsg,(XUIMessageData*) pData, sizeof(*pData)); + _XuiMessageExtra(pMsg,static_cast(pData), sizeof(*pData)); pData->bJoining = bJoining; } diff --git a/Minecraft.Client/Common/XUI/XUI_DLCOffers.cpp b/Minecraft.Client/Common/XUI/XUI_DLCOffers.cpp index bd05ca146..c5150249a 100644 --- a/Minecraft.Client/Common/XUI/XUI_DLCOffers.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DLCOffers.cpp @@ -24,7 +24,7 @@ HRESULT CScene_DLCMain::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - iPad = *(int *) pInitData->pvInitData; + iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -39,7 +39,7 @@ HRESULT CScene_DLCMain::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) VOID *pObj; XuiObjectFromHandle( xList, &pObj ); - list = (CXuiCtrl4JList *) pObj; + list = static_cast(pObj); ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT, IDS_TOOLTIPS_BACK ); @@ -162,7 +162,7 @@ HRESULT CScene_DLCMain::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* pNo param->iType = iIndex; // promote the DLC content request type - app.AddDLCRequest((eDLCMarketplaceType)iIndex, true); + app.AddDLCRequest(static_cast(iIndex), true); app.NavigateToScene(iPad,eUIScene_DLCOffersMenu, param); } return S_OK; @@ -182,14 +182,14 @@ HRESULT CScene_DLCMain::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) //---------------------------------------------------------------------------------- HRESULT CScene_DLCOffers::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - DLCOffersParam *param = (DLCOffersParam *) pInitData->pvInitData; + DLCOffersParam *param = static_cast(pInitData->pvInitData); m_iPad = param->iPad; m_iType = param->iType; m_iOfferC = app.GetDLCOffersCount(); m_bIsFemale = false; - m_pNoImageFor_DLC=NULL; + m_pNoImageFor_DLC=nullptr; bNoDLCToDisplay=true; - //hCostText=NULL; + //hCostText=nullptr; // 4J JEV: Deleting this here seems simpler. @@ -203,10 +203,10 @@ HRESULT CScene_DLCOffers::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) HRESULT hRes; - hRes=XAvatarInitialize(XAVATAR_COORDINATE_SYSTEM_LEFT_HANDED,0,0,0,NULL); + hRes=XAvatarInitialize(XAVATAR_COORDINATE_SYSTEM_LEFT_HANDED,0,0,0,nullptr); // get the avatar gender - hRes=XAvatarGetMetadataLocalUser(m_iPad,&AvatarMetadata,NULL); + hRes=XAvatarGetMetadataLocalUser(m_iPad,&AvatarMetadata,nullptr); m_bIsFemale= (XAVATAR_BODY_TYPE_FEMALE == XAvatarMetadataGetBodyType(&AvatarMetadata)); // shutdown the avatar system @@ -223,10 +223,10 @@ HRESULT CScene_DLCOffers::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) m_bIgnorePress=true; VOID *pObj; - m_hXuiBrush=NULL; + m_hXuiBrush=nullptr; XuiObjectFromHandle( m_List, &pObj ); - m_pOffersList = (CXuiCtrl4JList *)pObj; + m_pOffersList = static_cast(pObj); m_bAllDLCContentRetrieved=false; XuiElementInitUserFocus(m_hObj,ProfileManager.GetPrimaryPad(),TRUE); @@ -242,7 +242,7 @@ HRESULT CScene_DLCOffers::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) // Is the DLC we're looking for available? if(!m_bDLCRequiredIsRetrieved) { - if(app.DLCContentRetrieved((eDLCMarketplaceType)m_iType)) + if(app.DLCContentRetrieved(static_cast(m_iType))) { m_bDLCRequiredIsRetrieved=true; @@ -259,13 +259,13 @@ HRESULT CScene_DLCOffers::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) { - CXuiCtrl4JList::LIST_ITEM_INFO *pListInfo=NULL; + CXuiCtrl4JList::LIST_ITEM_INFO *pListInfo=nullptr; //XMARKETPLACE_CONTENTOFFER_INFO xOffer; XMARKETPLACE_CURRENCY_CONTENTOFFER_INFO xOffer; const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; ZeroMemory(szResourceLocator,sizeof(WCHAR)*LOCATOR_SIZE); - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); int iCount=0; if(bUpdateOnly) // Just update the info on the current list @@ -275,13 +275,13 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) xOffer = StorageManager.GetOffer(i); // Check that this is in the list of known DLC DLC_INFO *pDLC=app.GetDLCInfoForFullOfferID(xOffer.qwOfferID); - if(pDLC==NULL) + if(pDLC==nullptr) { // try the trial version pDLC=app.GetDLCInfoForTrialOfferID(xOffer.qwOfferID); } - if(pDLC==NULL) + if(pDLC==nullptr) { // skip this one #ifdef _DEBUG @@ -301,7 +301,7 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // can't trust the offer type - partnernet is giving avatar items the CONTENT type //if(Offer.dwOfferType==app.GetDLCContentType((eDLCContentType)m_iType)) - if(pDLC->eDLCType==(eDLCContentType)m_iType) + if(pDLC->eDLCType==static_cast(m_iType)) { if(xOffer.fUserHasPurchased) { @@ -343,13 +343,13 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // Check that this is in the list of known DLC DLC_INFO *pDLC=app.GetDLCInfoForFullOfferID(xOffer.qwOfferID); - if(pDLC==NULL) + if(pDLC==nullptr) { // try the trial version pDLC=app.GetDLCInfoForTrialOfferID(xOffer.qwOfferID); } - if(pDLC==NULL) + if(pDLC==nullptr) { // skip this one #ifdef _DEBUG @@ -362,7 +362,7 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // can't trust the offer type - partnernet is giving avatar items the CONTENT type //if(Offer.dwOfferType==app.GetDLCContentType((eDLCContentType)m_iType)) - if(pDLC->eDLCType==(eDLCContentType)m_iType) + if(pDLC->eDLCType==static_cast(m_iType)) { wstring wstrTemp=xOffer.wszOfferName; @@ -395,7 +395,7 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) // store the offer index pListInfo[iCount].iData=i; - pListInfo[iCount].iSortIndex=(int)pDLC->uiSortIndex; + pListInfo[iCount].iSortIndex=static_cast(pDLC->uiSortIndex); #ifdef _DEBUG app.DebugPrintf("Adding "); OutputDebugStringW(pListInfo[iCount].pwszText); @@ -447,9 +447,9 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) m_pOffersList->SetCurSelVisible(0); DLC_INFO *dlc = app.GetDLCInfoForFullOfferID(xOffer.qwOfferID); - if (dlc != NULL) + if (dlc != nullptr) { - BYTE *pData=NULL; + BYTE *pData=nullptr; UINT uiSize=0; DWORD dwSize=0; @@ -460,7 +460,7 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) if(iIndex!=-1) { // it's in the xzp - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory @@ -480,7 +480,7 @@ HRESULT CScene_DLCOffers::GetDLCInfo( int iOfferC, bool bUpdateOnly ) } else { - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory @@ -568,7 +568,7 @@ HRESULT CScene_DLCOffers::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* p // if it's already been purchased, we need to let the user download it anyway { ullIndexA[0]=StorageManager.GetOffer(ItemInfo.iData).qwOfferID; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } @@ -662,7 +662,7 @@ HRESULT CScene_DLCOffers::OnNotifySelChanged(HXUIOBJ hObjSource, XUINotifySelCha // reset the image monitor, but not for the first selection if(pNotifySelChangedData->iOldItem!=-1) { - m_pNoImageFor_DLC=NULL; + m_pNoImageFor_DLC=nullptr; } if (m_List.TreeHasFocus())// && offerIndexes.size() > index) @@ -695,14 +695,14 @@ HRESULT CScene_DLCOffers::OnNotifySelChanged(HXUIOBJ hObjSource, XUINotifySelCha m_PriceTag.SetText(xOffer.wszCurrencyPrice); DLC_INFO *dlc = app.GetDLCInfoForTrialOfferID(xOffer.qwOfferID); - if(dlc==NULL) + if(dlc==nullptr) { dlc = app.GetDLCInfoForFullOfferID(xOffer.qwOfferID); } - if (dlc != NULL) + if (dlc != nullptr) { - BYTE *pImage=NULL; + BYTE *pImage=nullptr; UINT uiSize=0; DWORD dwSize=0; @@ -713,7 +713,7 @@ HRESULT CScene_DLCOffers::OnNotifySelChanged(HXUIOBJ hObjSource, XUINotifySelCha if(iIndex!=-1) { // it's in the xzp - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory @@ -737,7 +737,7 @@ HRESULT CScene_DLCOffers::OnNotifySelChanged(HXUIOBJ hObjSource, XUINotifySelCha } else { - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory @@ -750,13 +750,13 @@ HRESULT CScene_DLCOffers::OnNotifySelChanged(HXUIOBJ hObjSource, XUINotifySelCha } else { - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory //app.FreeLocalTMSFiles(); - m_hXuiBrush=NULL; + m_hXuiBrush=nullptr; } } @@ -791,7 +791,7 @@ HRESULT CScene_DLCOffers::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) // Is the DLC we're looking for available? if(!m_bDLCRequiredIsRetrieved) { - if(app.DLCContentRetrieved((eDLCMarketplaceType)m_iType)) + if(app.DLCContentRetrieved(static_cast(m_iType))) { m_bDLCRequiredIsRetrieved=true; @@ -802,7 +802,7 @@ HRESULT CScene_DLCOffers::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) } // Check for any TMS image we're waiting for - if(m_pNoImageFor_DLC!=NULL) + if(m_pNoImageFor_DLC!=nullptr) { // Is it present now? WCHAR *cString = m_pNoImageFor_DLC->wchBanner; @@ -811,10 +811,10 @@ HRESULT CScene_DLCOffers::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) if(bPresent) { - BYTE *pImage=NULL; + BYTE *pImage=nullptr; DWORD dwSize=0; - if(m_hXuiBrush!=NULL) + if(m_hXuiBrush!=nullptr) { XuiDestroyBrush(m_hXuiBrush); // clear the TMS XZP vector memory @@ -822,7 +822,7 @@ HRESULT CScene_DLCOffers::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) } app.GetMemFileDetails(cString,&pImage,&dwSize); XuiCreateTextureBrushFromMemory(pImage,dwSize,&m_hXuiBrush); - m_pNoImageFor_DLC=NULL; + m_pNoImageFor_DLC=nullptr; } } diff --git a/Minecraft.Client/Common/XUI/XUI_Death.cpp b/Minecraft.Client/Common/XUI/XUI_Death.cpp index 83275c14c..1788ceffd 100644 --- a/Minecraft.Client/Common/XUI/XUI_Death.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Death.cpp @@ -26,7 +26,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_Death::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); m_bIgnoreInput = false; @@ -59,7 +59,7 @@ HRESULT CScene_Death::OnNotifySelChanged( HXUIOBJ hObjSource, XUINotifySelChange XuiSetLocale( Languages[curSel].pszLanguagePath ); // Apply the locale to the main scene. - XuiApplyLocale( m_hObj, NULL ); + XuiApplyLocale( m_hObj, nullptr ); // Update the text for the current value. m_Value.SetText( m_List.GetText( curSel ) );*/ @@ -105,9 +105,9 @@ HRESULT CScene_Death::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* pNoti if(pNotifyPressData->UserIndex==ProfileManager.GetPrimaryPad()) { int playTime = -1; - if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != NULL ) + if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != nullptr ) { - playTime = (int)pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer()); } TelemetryManager->RecordLevelExit(pNotifyPressData->UserIndex, eSen_LevelExitStatus_Failed); diff --git a/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp b/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp index 6b96a4e31..d8c06ae14 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp @@ -14,13 +14,13 @@ HRESULT CScene_DebugItemEditor::OnInit( XUIMessageInit *pInitData, BOOL &bHandle { MapChildControls(); - ItemEditorInput *initData = (ItemEditorInput *)pInitData->pvInitData; + ItemEditorInput *initData = static_cast(pInitData->pvInitData); m_iPad = initData->iPad; m_slot = initData->slot; m_menu = initData->menu; - if(m_slot != NULL) m_item = m_slot->getItem(); + if(m_slot != nullptr) m_item = m_slot->getItem(); - if(m_item!=NULL) + if(m_item!=nullptr) { 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) ) ); @@ -54,13 +54,13 @@ HRESULT CScene_DebugItemEditor::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfH case VK_PAD_START: case VK_PAD_BACK: // We need to send a packet to the server to update it's representation of this item - if(m_slot != NULL && m_menu != NULL) + if(m_slot != nullptr && m_menu != nullptr) { m_slot->set(m_item); Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player != NULL && player->connection) player->connection->send( shared_ptr( new ContainerSetSlotPacket(m_menu->containerId, m_slot->index, m_item) ) ); + if(player != nullptr && player->connection) player->connection->send(std::make_shared(m_menu->containerId, m_slot->index, m_item)); } // kill the crafting xui app.NavigateBack(m_iPad); @@ -76,7 +76,7 @@ HRESULT CScene_DebugItemEditor::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfH HRESULT CScene_DebugItemEditor::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotifyValueChanged *pNotifyValueChangedData, BOOL &bHandled) { - if(m_item == NULL) m_item = shared_ptr( new ItemInstance(0,1,0) ); + if(m_item == nullptr) m_item = std::make_shared(0, 1, 0); if(hObjSource == m_itemId) { int id = 0; @@ -84,7 +84,7 @@ HRESULT CScene_DebugItemEditor::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINot if(!value.empty()) id = _fromString( value ); // TODO Proper validation of the valid item ids - if(id > 0 && Item::items[id] != NULL) m_item->id = id; + if(id > 0 && Item::items[id] != nullptr) m_item->id = id; } else if(hObjSource == m_itemAuxValue) { diff --git a/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp b/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp index e6db6a805..338eb853c 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp @@ -37,7 +37,7 @@ HRESULT CScene_DebugOverlay::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) for(unsigned int i = 0; i < Item::items.length; ++i) { - if(Item::items[i] != NULL) + if(Item::items[i] != nullptr) { //m_items.InsertItems(m_items.GetItemCount(),1); m_itemIds.push_back(i); @@ -102,7 +102,7 @@ HRESULT CScene_DebugOverlay::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); m_setTime.SetValue( pMinecraft->level->getLevelData()->getTime() % 24000 ); - m_setFov.SetValue( (int)pMinecraft->gameRenderer->GetFovVal()); + m_setFov.SetValue( static_cast(pMinecraft->gameRenderer->GetFovVal())); XuiSetTimer(m_hObj,0,DEBUG_OVERLAY_UPDATE_TIME_PERIOD); @@ -148,7 +148,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress /*else if( hObjPressed == m_saveToDisc ) // 4J-JEV: Doesn't look like we use this debug option anymore. { #ifndef _CONTENT_PACKAGE - pMinecraft->level->save(true, NULL); + pMinecraft->level->save(true, nullptr); int radius; m_chunkRadius.GetValue(&radius); @@ -166,7 +166,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress { #ifndef _CONTENT_PACKAGE // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); HXUIOBJ hScene; HRESULT hr; @@ -175,7 +175,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress WCHAR szResourceLocator[ LOCATOR_SIZE ]; swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); - hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIScene_DebugCreateSchematic,false, false), NULL, &hScene); + hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIScene_DebugCreateSchematic,false, false), nullptr, &hScene); this->NavigateForward(hScene); //app.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugCreateSchematic); #endif @@ -184,7 +184,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress { #ifndef _CONTENT_PACKAGE // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); HXUIOBJ hScene; HRESULT hr; @@ -193,7 +193,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress WCHAR szResourceLocator[ LOCATOR_SIZE ]; swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); - hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIScene_DebugSetCamera, false, false), NULL, &hScene); + hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIScene_DebugSetCamera, false, false), nullptr, &hScene); this->NavigateForward(hScene); //app.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_DebugCreateSchematic); #endif @@ -266,7 +266,7 @@ HRESULT CScene_DebugOverlay::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotify if( hObjSource == m_setFov ) { Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->gameRenderer->SetFovVal((float)pNotifyValueChangedData->nValue); + pMinecraft->gameRenderer->SetFovVal(static_cast(pNotifyValueChangedData->nValue)); } return S_OK; } @@ -274,10 +274,10 @@ HRESULT CScene_DebugOverlay::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotify HRESULT CScene_DebugOverlay::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled ) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->level != NULL) + if(pMinecraft->level != nullptr) { m_setTime.SetValue( pMinecraft->level->getLevelData()->getTime() % 24000 ); - m_setFov.SetValue( (int)pMinecraft->gameRenderer->GetFovVal()); + m_setFov.SetValue( static_cast(pMinecraft->gameRenderer->GetFovVal())); } return S_OK; } @@ -286,9 +286,9 @@ void CScene_DebugOverlay::SetSpawnToPlayerPos() { Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->level->getLevelData()->setXSpawn((int)pMinecraft->player->x); - pMinecraft->level->getLevelData()->setYSpawn((int)pMinecraft->player->y); - pMinecraft->level->getLevelData()->setZSpawn((int)pMinecraft->player->z); + pMinecraft->level->getLevelData()->setXSpawn(static_cast(pMinecraft->player->x)); + pMinecraft->level->getLevelData()->setYSpawn(static_cast(pMinecraft->player->y)); + pMinecraft->level->getLevelData()->setZSpawn(static_cast(pMinecraft->player->z)); } #ifndef _CONTENT_PACKAGE @@ -301,14 +301,14 @@ void CScene_DebugOverlay::SaveLimitedFile(int chunkRadius) ConsoleSaveFile *currentSave = pMinecraft->level->getLevelStorage()->getSaveFile(); // With a size of 0 but a value in the data pointer we should create a new save - ConsoleSaveFileOriginal newSave( currentSave->getFilename(), NULL, 0, true ); + ConsoleSaveFileOriginal newSave( currentSave->getFilename(), nullptr, 0, true ); // TODO Make this only happen for the new save //SetSpawnToPlayerPos(); FileEntry *origFileEntry = currentSave->createFile( wstring( L"level.dat" ) ); byteArray levelData( origFileEntry->getFileSize() ); DWORD bytesRead; - currentSave->setFilePointer(origFileEntry,0,NULL,FILE_BEGIN); + currentSave->setFilePointer(origFileEntry,0,nullptr,FILE_BEGIN); currentSave->readFile( origFileEntry, levelData.data, // data buffer @@ -331,10 +331,10 @@ void CScene_DebugOverlay::SaveLimitedFile(int chunkRadius) { for(int zPos = playerChunkZ - chunkRadius; zPos < playerChunkZ + chunkRadius; ++zPos) { - CompoundTag *chunkData=NULL; + CompoundTag *chunkData=nullptr; DataInputStream *is = RegionFileCache::getChunkDataInputStream(currentSave, L"", xPos, zPos); - if (is != NULL) + if (is != nullptr) { chunkData = NbtIo::read((DataInput *)is); is->deleteChildStream(); @@ -342,7 +342,7 @@ void CScene_DebugOverlay::SaveLimitedFile(int chunkRadius) } app.DebugPrintf("Processing chunk (%d, %d)\n", xPos, zPos); DataOutputStream *os = getChunkDataOutputStream(newFileCache, &newSave, L"", xPos, zPos); - if(os != NULL) + if(os != nullptr) { NbtIo::write(chunkData, os); os->close(); @@ -352,7 +352,7 @@ void CScene_DebugOverlay::SaveLimitedFile(int chunkRadius) os->deleteChildStream(); delete os; } - if(chunkData != NULL) + if(chunkData != nullptr) { delete chunkData; } @@ -367,13 +367,13 @@ RegionFile *CScene_DebugOverlay::getRegionFile(unordered_map>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); - RegionFile *ref = NULL; + RegionFile *ref = nullptr; auto it = newFileCache.find(file); if( it != newFileCache.end() ) ref = it->second; // 4J Jev, put back in. - if (ref != NULL) + if (ref != nullptr) { return ref; } diff --git a/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp b/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp index f6335191b..fb6339ce2 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp @@ -25,7 +25,7 @@ HRESULT CScene_DebugSetCamera::OnInit( XUIMessageInit *pInitData, BOOL &bHandled currentPosition->player = playerNo; Minecraft *pMinecraft = Minecraft::GetInstance(); - if (pMinecraft != NULL) + if (pMinecraft != nullptr) { Vec3 *vec = pMinecraft->localplayers[playerNo]->getPos(1.0); @@ -43,12 +43,12 @@ 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 *) 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_camX.SetText(static_cast(std::to_wstring(currentPosition->m_camX).c_str())); + m_camY.SetText(static_cast(std::to_wstring(currentPosition->m_camY + 1.62).c_str())); + m_camZ.SetText(static_cast(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(static_cast(std::to_wstring(currentPosition->m_yRot).c_str())); + m_elevation.SetText(static_cast(std::to_wstring(currentPosition->m_elev).c_str())); //fpp = new FreezePlayerParam(); //fpp->player = playerNo; @@ -94,7 +94,7 @@ HRESULT CScene_DebugSetCamera::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHa NavigateBack(); //delete currentPosition; - //currentPosition = NULL; + //currentPosition = nullptr; rfHandled = TRUE; break; diff --git a/Minecraft.Client/Common/XUI/XUI_DebugTips.cpp b/Minecraft.Client/Common/XUI/XUI_DebugTips.cpp index aaa3b06f6..e8091bcb3 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugTips.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugTips.cpp @@ -9,7 +9,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_DebugTips::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); m_bIgnoreInput = false; diff --git a/Minecraft.Client/Common/XUI/XUI_FullscreenProgress.cpp b/Minecraft.Client/Common/XUI/XUI_FullscreenProgress.cpp index f66c0d70c..cc2359156 100644 --- a/Minecraft.Client/Common/XUI/XUI_FullscreenProgress.cpp +++ b/Minecraft.Client/Common/XUI/XUI_FullscreenProgress.cpp @@ -18,7 +18,7 @@ HRESULT CScene_FullscreenProgress::OnInit( XUIMessageInit* pInitData, BOOL& bHan m_buttonConfirm.SetText( app.GetString( IDS_CONFIRM_OK ) ); - LoadingInputParams *params = (LoadingInputParams *)pInitData->pvInitData; + LoadingInputParams *params = static_cast(pInitData->pvInitData); m_CompletionData = params->completionData; m_iPad=params->completionData->iPad; @@ -67,10 +67,10 @@ HRESULT CScene_FullscreenProgress::OnInit( XUIMessageInit* pInitData, BOOL& bHan // The framework calls this handler when the object is to be destroyed. HRESULT CScene_FullscreenProgress::OnDestroy() { - if( thread != NULL && thread != INVALID_HANDLE_VALUE ) + if( thread != nullptr && thread != INVALID_HANDLE_VALUE ) delete thread; - if( m_CompletionData != NULL ) + if( m_CompletionData != nullptr ) delete m_CompletionData; return S_OK; @@ -86,7 +86,7 @@ HRESULT CScene_FullscreenProgress::OnKeyDown(XUIMessageInput* pInputData, BOOL& case VK_PAD_B: case VK_ESCAPE: // 4J-JEV: Fix for Xbox360 #162749 - TU17: Save Upload: Content: UI: Player is presented with non-functional Tooltips after the Upload Save For Xbox One is completed. - if( m_cancelFunc != NULL && !m_threadCompleted ) + if( m_cancelFunc != nullptr && !m_threadCompleted ) { m_cancelFunc( m_cancelFuncParam ); m_bWasCancelled=true; @@ -201,7 +201,7 @@ HRESULT CScene_FullscreenProgress::OnTransitionStart( XUIMessageTransition *pTra HRESULT CScene_FullscreenProgress::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled ) { int code = thread->GetExitCode(); - DWORD exitcode = *((DWORD *)&code); + DWORD exitcode = *static_cast(&code); //app.DebugPrintf("CScene_FullscreenProgress Timer %d\n",pTimer->nId); @@ -244,7 +244,7 @@ HRESULT CScene_FullscreenProgress::OnTimer( XUIMessageTimer *pTimer, BOOL& bHand UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, IDS_CONNECTION_LOST_SERVER, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, IDS_CONNECTION_LOST_SERVER, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); app.NavigateToHomeMenu(); ui.UpdatePlayerBasePositions(); @@ -292,7 +292,7 @@ HRESULT CScene_FullscreenProgress::OnTimer( XUIMessageTimer *pTimer, BOOL& bHand CXuiSceneBase::ShowOtherPlayersBaseScene(iPad, true); // This just allows it to be shown Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); + if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); ui.UpdatePlayerBasePositions(); } break; diff --git a/Minecraft.Client/Common/XUI/XUI_HUD.cpp b/Minecraft.Client/Common/XUI/XUI_HUD.cpp index 286f06a70..e188cbf68 100644 --- a/Minecraft.Client/Common/XUI/XUI_HUD.cpp +++ b/Minecraft.Client/Common/XUI/XUI_HUD.cpp @@ -10,7 +10,7 @@ HRESULT CXuiSceneHud::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -33,7 +33,7 @@ HRESULT CXuiSceneHud::OnCustomMessage_Splitscreenplayer(bool bJoining, BOOL& bHa HRESULT CXuiSceneHud::OnCustomMessage_TickScene() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[m_iPad] == NULL || pMinecraft->localgameModes[m_iPad] == NULL) return S_OK; + if(pMinecraft->localplayers[m_iPad] == nullptr || pMinecraft->localgameModes[m_iPad] == nullptr) return S_OK; ++m_tickCount; @@ -145,7 +145,7 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() if (pMinecraft->localgameModes[m_iPad]->canHurtPlayer()) { int xpNeededForNextLevel = pMinecraft->localplayers[m_iPad]->getXpNeededForNextLevel(); - int progress = (int)(pMinecraft->localplayers[m_iPad]->experienceProgress *xpNeededForNextLevel); + int progress = static_cast(pMinecraft->localplayers[m_iPad]->experienceProgress * xpNeededForNextLevel); m_ExperienceProgress.SetShow(TRUE); m_ExperienceProgress.SetRange(0,xpNeededForNextLevel); @@ -196,11 +196,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Full if(bHasPoison) { - m_healthIcon[icon].PlayVisualRange(L"FullPoisonFlash",NULL,L"FullPoisonFlash"); + m_healthIcon[icon].PlayVisualRange(L"FullPoisonFlash",nullptr,L"FullPoisonFlash"); } else { - m_healthIcon[icon].PlayVisualRange(L"FullFlash",NULL,L"FullFlash"); + m_healthIcon[icon].PlayVisualRange(L"FullFlash",nullptr,L"FullFlash"); } } else if (icon * 2 + 1 == iLastHealth || icon * 2 + 1 == iHealth) @@ -208,17 +208,17 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Half if(bHasPoison) { - m_healthIcon[icon].PlayVisualRange(L"HalfPoisonFlash",NULL,L"HalfPoisonFlash"); + m_healthIcon[icon].PlayVisualRange(L"HalfPoisonFlash",nullptr,L"HalfPoisonFlash"); } else { - m_healthIcon[icon].PlayVisualRange(L"HalfFlash",NULL,L"HalfFlash"); + m_healthIcon[icon].PlayVisualRange(L"HalfFlash",nullptr,L"HalfFlash"); } } else { // Empty - m_healthIcon[icon].PlayVisualRange(L"NormalFlash",NULL,L"NormalFlash"); + m_healthIcon[icon].PlayVisualRange(L"NormalFlash",nullptr,L"NormalFlash"); } } else @@ -228,11 +228,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Full if(bHasPoison) { - m_healthIcon[icon].PlayVisualRange(L"FullPoison",NULL,L"FullPoison"); + m_healthIcon[icon].PlayVisualRange(L"FullPoison",nullptr,L"FullPoison"); } else { - m_healthIcon[icon].PlayVisualRange(L"Full",NULL,L"Full"); + m_healthIcon[icon].PlayVisualRange(L"Full",nullptr,L"Full"); } } else if (icon * 2 + 1 == iHealth) @@ -240,24 +240,24 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Half if(bHasPoison) { - m_healthIcon[icon].PlayVisualRange(L"HalfPoison",NULL,L"HalfPoison"); + m_healthIcon[icon].PlayVisualRange(L"HalfPoison",nullptr,L"HalfPoison"); } else { - m_healthIcon[icon].PlayVisualRange(L"Half",NULL,L"Half"); + m_healthIcon[icon].PlayVisualRange(L"Half",nullptr,L"Half"); } } else { // Empty - m_healthIcon[icon].PlayVisualRange(L"Normal",NULL,L"Normal"); + m_healthIcon[icon].PlayVisualRange(L"Normal",nullptr,L"Normal"); } } float yo = 0; if (iHealth <= 4) { - yo = (float)m_random.nextInt(2) * (iGuiScale+1); + yo = static_cast(m_random.nextInt(2)) * (iGuiScale+1); } if (icon == heartOffsetIndex) { @@ -288,11 +288,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Full if(hasHungerEffect) { - m_foodIcon[icon].PlayVisualRange(L"FullPoisonFlash",NULL,L"FullPoisonFlash"); + m_foodIcon[icon].PlayVisualRange(L"FullPoisonFlash",nullptr,L"FullPoisonFlash"); } else { - m_foodIcon[icon].PlayVisualRange(L"FullFlash",NULL,L"FullFlash"); + m_foodIcon[icon].PlayVisualRange(L"FullFlash",nullptr,L"FullFlash"); } } else if (icon * 2 + 1 == oldFood || icon * 2 + 1 == food) @@ -300,17 +300,17 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Half if(hasHungerEffect) { - m_foodIcon[icon].PlayVisualRange(L"HalfPoisonFlash",NULL,L"HalfPoisonFlash"); + m_foodIcon[icon].PlayVisualRange(L"HalfPoisonFlash",nullptr,L"HalfPoisonFlash"); } else { - m_foodIcon[icon].PlayVisualRange(L"HalfFlash",NULL,L"HalfFlash"); + m_foodIcon[icon].PlayVisualRange(L"HalfFlash",nullptr,L"HalfFlash"); } } else { // Empty - m_foodIcon[icon].PlayVisualRange(L"NormalFlash",NULL,L"NormalFlash"); + m_foodIcon[icon].PlayVisualRange(L"NormalFlash",nullptr,L"NormalFlash"); } } else @@ -320,11 +320,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Full if(hasHungerEffect) { - m_foodIcon[icon].PlayVisualRange(L"FullPoison",NULL,L"FullPoison"); + m_foodIcon[icon].PlayVisualRange(L"FullPoison",nullptr,L"FullPoison"); } else { - m_foodIcon[icon].PlayVisualRange(L"Full",NULL,L"Full"); + m_foodIcon[icon].PlayVisualRange(L"Full",nullptr,L"Full"); } } else if (icon * 2 + 1 == food) @@ -332,11 +332,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Half if(hasHungerEffect) { - m_foodIcon[icon].PlayVisualRange(L"HalfPoison",NULL,L"HalfPoison"); + m_foodIcon[icon].PlayVisualRange(L"HalfPoison",nullptr,L"HalfPoison"); } else { - m_foodIcon[icon].PlayVisualRange(L"Half",NULL,L"Half"); + m_foodIcon[icon].PlayVisualRange(L"Half",nullptr,L"Half"); } } else @@ -344,11 +344,11 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() // Empty if(hasHungerEffect) { - m_foodIcon[icon].PlayVisualRange(L"NormalPoison",NULL,L"NormalPoison"); + m_foodIcon[icon].PlayVisualRange(L"NormalPoison",nullptr,L"NormalPoison"); } else { - m_foodIcon[icon].PlayVisualRange(L"Normal",NULL,L"Normal"); + m_foodIcon[icon].PlayVisualRange(L"Normal",nullptr,L"Normal"); } } } @@ -359,7 +359,7 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() { if ((m_tickCount % (food * 3 + 1)) == 0) { - yo = (float)(m_random.nextInt(3) - 1) * (iGuiScale+1); + yo = static_cast(m_random.nextInt(3) - 1) * (iGuiScale+1); } } @@ -377,9 +377,9 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() m_armourGroup.SetShow(TRUE); for (int icon = 0; icon < 10; icon++) { - if (icon * 2 + 1 < armor) m_armourIcon[icon].PlayVisualRange(L"Full",NULL,L"Full"); - else if (icon * 2 + 1 == armor) m_armourIcon[icon].PlayVisualRange(L"Half",NULL,L"Half"); - else if (icon * 2 + 1 > armor) m_armourIcon[icon].PlayVisualRange(L"Normal",NULL,L"Normal"); + if (icon * 2 + 1 < armor) m_armourIcon[icon].PlayVisualRange(L"Full",nullptr,L"Full"); + else if (icon * 2 + 1 == armor) m_armourIcon[icon].PlayVisualRange(L"Half",nullptr,L"Half"); + else if (icon * 2 + 1 > armor) m_armourIcon[icon].PlayVisualRange(L"Normal",nullptr,L"Normal"); } } else @@ -391,20 +391,20 @@ HRESULT CXuiSceneHud::OnCustomMessage_TickScene() if (pMinecraft->localplayers[m_iPad]->isUnderLiquid(Material::water)) { m_airGroup.SetShow(TRUE); - int count = (int) ceil((pMinecraft->localplayers[m_iPad]->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY); - int extra = (int) ceil((pMinecraft->localplayers[m_iPad]->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY) - count; + int count = static_cast(ceil((pMinecraft->localplayers[m_iPad]->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY)); + int extra = static_cast(ceil((pMinecraft->localplayers[m_iPad]->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY)) - count; for (int icon = 0; icon < 10; icon++) { // Air bubbles if (icon < count) { m_airIcon[icon].SetShow(TRUE); - m_airIcon[icon].PlayVisualRange(L"Bubble",NULL,L"Bubble"); + m_airIcon[icon].PlayVisualRange(L"Bubble",nullptr,L"Bubble"); } else if(icon < count + extra) { m_airIcon[icon].SetShow(TRUE); - m_airIcon[icon].PlayVisualRange(L"Pop",NULL,L"Pop"); + m_airIcon[icon].PlayVisualRange(L"Pop",nullptr,L"Pop"); } else m_airIcon[icon].SetShow(FALSE); } @@ -428,7 +428,7 @@ HRESULT CXuiSceneHud::OnCustomMessage_DLCInstalled() { // mounted DLC may have changed bool bPauseMenuDisplayed=false; - bool bInGame=(Minecraft::GetInstance()->level!=NULL); + bool bInGame=(Minecraft::GetInstance()->level!=nullptr); // ignore this if we have menus up - they'll deal with it for(int i=0;ipvInitData; - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + m_iPad = *static_cast(pInitData->pvInitData); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); MapChildControls(); XuiControlSetText(m_Buttons[BUTTON_HAO_CHANGESKIN],app.GetString(IDS_CHANGE_SKIN)); @@ -140,7 +140,7 @@ HRESULT CScene_HelpAndOptions::OnInit( XUIMessageInit* pInitData, BOOL& bHandled /*HRESULT CScene_HelpAndOptions::OnTMSDLCFileRetrieved( ) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_Timer.SetShow(FALSE); m_bIgnoreInput=false; @@ -253,7 +253,7 @@ HRESULT CScene_HelpAndOptions::OnControlNavigate(XUIMessageControlNavigate *pCon { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -344,7 +344,7 @@ HRESULT CScene_HelpAndOptions::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHa HRESULT CScene_HelpAndOptions::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { @@ -414,7 +414,7 @@ HRESULT CScene_HelpAndOptions::OnTransitionStart( XUIMessageTransition *pTransit // 4J-PB - Going to resize buttons if the text is too big to fit on any of them (Br-pt problem with the length of Unlock Full Game) XUIRect xuiRect; - HXUIOBJ visual=NULL; + HXUIOBJ visual=nullptr; HXUIOBJ text; float fMaxTextLen=0.0f; float fTextVisualLen; diff --git a/Minecraft.Client/Common/XUI/XUI_HelpControls.cpp b/Minecraft.Client/Common/XUI/XUI_HelpControls.cpp index e7a8b0ca0..3c4e80a22 100644 --- a/Minecraft.Client/Common/XUI/XUI_HelpControls.cpp +++ b/Minecraft.Client/Common/XUI/XUI_HelpControls.cpp @@ -91,9 +91,9 @@ HRESULT CScene_Controls::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) XuiControlSetText(m_SouthPaw,app.GetString(IDS_SOUTHPAW)); XuiControlSetText(m_InvertLook,app.GetString(IDS_INVERT_LOOK)); - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bSplitscreen=(app.GetLocalPlayerCount()>1); m_iCurrentTextIndex=0; m_bCreativeMode = !bNotInGame && Minecraft::GetInstance()->localplayers[m_iPad] && Minecraft::GetInstance()->localplayers[m_iPad]->abilities.mayfly; @@ -159,20 +159,20 @@ HRESULT CScene_Controls::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) controlDetailsA[i].vPos.y/=2.0f; } m_FigA[i].SetShow(FALSE); - m_TextPresenterA[i] = NULL; + m_TextPresenterA[i] = nullptr; } // fill out the layouts list VOID *pObj; XuiObjectFromHandle( m_SchemeList, &pObj ); - m_pLayoutList = (CXuiCtrl4JList *)pObj; + m_pLayoutList = static_cast(pObj); CXuiCtrl4JList::LIST_ITEM_INFO ListInfo[3]; ZeroMemory(ListInfo,sizeof(CXuiCtrl4JList::LIST_ITEM_INFO)*3); for(int i=0;i<3;i++) { ListInfo[i].pwszText=m_LayoutNameA[i]; - ListInfo[i].hXuiBrush=NULL; + ListInfo[i].hXuiBrush=nullptr; ListInfo[i].fEnabled=TRUE; m_pLayoutList->AddData(ListInfo[i]); } @@ -325,9 +325,9 @@ void CScene_Controls::PositionText(int iPad,int iTextID, unsigned char ucAction) XuiElementGetScale(hFigGroup,&vScale); // check the width of the control with the text set in it - if(m_TextPresenterA[m_iCurrentTextIndex]==NULL) + if(m_TextPresenterA[m_iCurrentTextIndex]==nullptr) { - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; HRESULT hr=XuiControlGetVisual(m_TextA[m_iCurrentTextIndex].m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"Text",&m_TextPresenterA[m_iCurrentTextIndex]); } @@ -452,9 +452,9 @@ void CScene_Controls::PositionTextDirect(int iPad,int iTextID, int iControlDetai XuiElementGetScale(hFigGroup,&vScale); // check the width of the control with the text set in it - if(m_TextPresenterA[m_iCurrentTextIndex]==NULL) + if(m_TextPresenterA[m_iCurrentTextIndex]==nullptr) { - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; HRESULT hr=XuiControlGetVisual(m_TextA[m_iCurrentTextIndex].m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"Text",&m_TextPresenterA[m_iCurrentTextIndex]); } @@ -532,18 +532,18 @@ HRESULT CScene_Controls::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* pN if ( hObjPressed == m_InvertLook.m_hObj ) { BOOL bIsChecked = m_InvertLook.IsChecked(); - app.SetGameSettings(m_iPad,eGameSetting_ControlInvertLook,(unsigned char)( bIsChecked ) ); + app.SetGameSettings(m_iPad,eGameSetting_ControlInvertLook,static_cast(bIsChecked) ); } else if ( hObjPressed == m_SouthPaw.m_hObj ) { BOOL bIsChecked = m_SouthPaw.IsChecked(); - app.SetGameSettings(m_iPad,eGameSetting_ControlSouthPaw,(unsigned char)( bIsChecked ) ); + app.SetGameSettings(m_iPad,eGameSetting_ControlSouthPaw,static_cast(bIsChecked) ); PositionAllText(m_iPad); } else if( hObjPressed == m_SchemeList) { // check what's been selected - app.SetGameSettings(m_iPad,eGameSetting_ControlScheme,(unsigned char)m_SchemeList.GetCurSel()); + app.SetGameSettings(m_iPad,eGameSetting_ControlScheme,static_cast(m_SchemeList.GetCurSel())); LPWSTR layoutString = new wchar_t[ 128 ]; swprintf( layoutString, 128, L"%ls : %ls", app.GetString( IDS_CURRENT_LAYOUT ),app.GetString(m_iSchemeTextA[m_SchemeList.GetCurSel()]) ); diff --git a/Minecraft.Client/Common/XUI/XUI_HelpCredits.cpp b/Minecraft.Client/Common/XUI/XUI_HelpCredits.cpp index 4a6ce55f8..c0584e946 100644 --- a/Minecraft.Client/Common/XUI/XUI_HelpCredits.cpp +++ b/Minecraft.Client/Common/XUI/XUI_HelpCredits.cpp @@ -386,12 +386,12 @@ static const int gs_aNumTextElements[ eNumTextTypes ] = //---------------------------------------------------------------------------------- HRESULT CScene_Credits::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - int iPad = *(int *)pInitData->pvInitData; + int iPad = *static_cast(pInitData->pvInitData); MapChildControls(); // if we're not in the game, we need to use basescene 0 - if(Minecraft::GetInstance()->level==NULL) + if(Minecraft::GetInstance()->level==nullptr) { iPad=0; } @@ -441,7 +441,7 @@ HRESULT CScene_Credits::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) VOID* pTextObj; XuiObjectFromHandle( text, &pTextObj ); - m_aTextTypes[ i ].m_appTextElements[ j ] = (CXuiControl *)pTextObj; + m_aTextTypes[ i ].m_appTextElements[ j ] = static_cast(pTextObj); m_aTextTypes[ i ].m_appTextElements[ j ]->SetShow( false ); } } diff --git a/Minecraft.Client/Common/XUI/XUI_HelpHowToPlay.cpp b/Minecraft.Client/Common/XUI/XUI_HelpHowToPlay.cpp index 5c750d030..cd9e962d0 100644 --- a/Minecraft.Client/Common/XUI/XUI_HelpHowToPlay.cpp +++ b/Minecraft.Client/Common/XUI/XUI_HelpHowToPlay.cpp @@ -39,12 +39,12 @@ static SHowToPlayPageDef gs_aPageDefs[ eHowToPlay_NumPages ] = HRESULT CScene_HowToPlay::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { // Extract pad and required page from init data. We just put the data into the pointer rather than using it as an address. - size_t uiInitData = ( size_t )( pInitData->pvInitData ); + size_t uiInitData = static_cast(pInitData->pvInitData); - m_iPad = ( int )( ( short )( uiInitData & 0xFFFF ) ); - EHowToPlayPage eStartPage = ( EHowToPlayPage )( ( uiInitData >> 16 ) & 0xFFF ); // Ignores MSB which is set to 1! + m_iPad = static_cast((short)(uiInitData & 0xFFFF)); + EHowToPlayPage eStartPage = static_cast((uiInitData >> 16) & 0xFFF); // Ignores MSB which is set to 1! - TelemetryManager->RecordMenuShown(m_iPad, eUIScene_HowToPlay, (ETelemetry_HowToPlay_SubMenuId)eStartPage); + TelemetryManager->RecordMenuShown(m_iPad, eUIScene_HowToPlay, static_cast(eStartPage)); MapChildControls(); @@ -116,10 +116,10 @@ HRESULT CScene_HowToPlay::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled case VK_PAD_A: { // Next page - int iNextPage = ( int )( m_eCurrPage ) + 1; + int iNextPage = static_cast(m_eCurrPage) + 1; if ( iNextPage != eHowToPlay_NumPages ) { - StartPage( ( EHowToPlayPage )( iNextPage ) ); + StartPage( static_cast(iNextPage) ); CXuiSceneBase::PlayUISFX(eSFX_Press); } rfHandled = TRUE; @@ -128,10 +128,10 @@ HRESULT CScene_HowToPlay::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled case VK_PAD_X: { // Next page - int iPrevPage = ( int )( m_eCurrPage ) - 1; + int iPrevPage = static_cast(m_eCurrPage) - 1; if ( iPrevPage >= 0 ) { - StartPage( ( EHowToPlayPage )( iPrevPage ) ); + StartPage( static_cast(iPrevPage) ); CXuiSceneBase::PlayUISFX(eSFX_Press); } rfHandled = TRUE; @@ -146,7 +146,7 @@ void CScene_HowToPlay::StartPage( EHowToPlayPage ePage ) { int iBaseSceneUser; // if we're not in the game, we need to use basescene 0 - if(Minecraft::GetInstance()->level==NULL) + if(Minecraft::GetInstance()->level==nullptr) { iBaseSceneUser=DEFAULT_XUI_MENU_USER; } diff --git a/Minecraft.Client/Common/XUI/XUI_HowToPlayMenu.cpp b/Minecraft.Client/Common/XUI/XUI_HowToPlayMenu.cpp index 14046f203..a99921e06 100644 --- a/Minecraft.Client/Common/XUI/XUI_HowToPlayMenu.cpp +++ b/Minecraft.Client/Common/XUI/XUI_HowToPlayMenu.cpp @@ -65,11 +65,11 @@ unsigned int CScene_HowToPlayMenu::m_uiHTPSceneA[]= //---------------------------------------------------------------------------------- HRESULT CScene_HowToPlayMenu::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bSplitscreen= app.GetLocalPlayerCount()>1; - m_ButtonList=NULL; + m_ButtonList=nullptr; //MapChildControls(); @@ -131,7 +131,7 @@ HRESULT CScene_HowToPlayMenu::OnGetSourceDataText(XUIMessageGetSourceText *pGetS { if( pGetSourceTextData->bItemData ) { - if( pGetSourceTextData->iItem < (int)eHTPButton_Max ) + if( pGetSourceTextData->iItem < static_cast(eHTPButton_Max) ) { pGetSourceTextData->szText = app.GetString(m_uiHTPButtonNameA[pGetSourceTextData->iItem]);//m_Buttons[pGetSourceTextData->iItem].GetText(); pGetSourceTextData->bDisplay = TRUE; @@ -173,7 +173,7 @@ HRESULT CScene_HowToPlayMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPres // 4J-PB - now using a list for all resolutions //if((!RenderManager.IsHiDef() && !RenderManager.IsWidescreen()) || app.GetLocalPlayerCount()>1) { - if(hObjPressed==m_ButtonList && m_ButtonList.TreeHasFocus() && (m_ButtonList.GetItemCount() > 0) && (m_ButtonList.GetCurSel() < (int)eHTPButton_Max) ) + if(hObjPressed==m_ButtonList && m_ButtonList.TreeHasFocus() && (m_ButtonList.GetItemCount() > 0) && (m_ButtonList.GetCurSel() < static_cast(eHTPButton_Max)) ) { uiButtonCounter=m_ButtonList.GetCurSel(); } @@ -186,7 +186,7 @@ HRESULT CScene_HowToPlayMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPres // Determine which button was pressed, // and call the appropriate function. - uiInitData = ( ( 1 << 31 ) | ( m_uiHTPSceneA[uiButtonCounter] << 16 ) | ( short )( m_iPad ) ); + uiInitData = ( ( 1 << 31 ) | ( m_uiHTPSceneA[uiButtonCounter] << 16 ) | static_cast(m_iPad) ); if(app.GetLocalPlayerCount()>1) { app.NavigateToScene(pNotifyPressData->UserIndex,eUIScene_HowToPlay, ( void* )( uiInitData ) ); diff --git a/Minecraft.Client/Common/XUI/XUI_InGameHostOptions.cpp b/Minecraft.Client/Common/XUI/XUI_InGameHostOptions.cpp index f05617451..5030a7923 100644 --- a/Minecraft.Client/Common/XUI/XUI_InGameHostOptions.cpp +++ b/Minecraft.Client/Common/XUI/XUI_InGameHostOptions.cpp @@ -12,7 +12,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_InGameHostOptions::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -76,9 +76,9 @@ HRESULT CScene_InGameHostOptions::OnKeyDown(XUIMessageInput* pInputData, BOOL& r { Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player != NULL && player->connection) + if(player != nullptr && player->connection) { - player->connection->send( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, hostOptions) ) ); + player->connection->send(std::make_shared(ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, hostOptions)); } } diff --git a/Minecraft.Client/Common/XUI/XUI_InGameInfo.cpp b/Minecraft.Client/Common/XUI/XUI_InGameInfo.cpp index 4839013c9..35e083396 100644 --- a/Minecraft.Client/Common/XUI/XUI_InGameInfo.cpp +++ b/Minecraft.Client/Common/XUI/XUI_InGameInfo.cpp @@ -25,7 +25,7 @@ HRESULT CScene_InGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { m_bIgnoreKeyPresses=true; - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -44,7 +44,7 @@ HRESULT CScene_InGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL ) + if( player != nullptr ) { m_players[i] = player->GetSmallId(); ++m_playersCount; @@ -55,7 +55,7 @@ HRESULT CScene_InGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) INetworkPlayer *thisPlayer = g_NetworkManager.GetLocalPlayerByUserIndex( m_iPad ); m_isHostPlayer = false; - if(thisPlayer != NULL) m_isHostPlayer = thisPlayer->IsHost() == TRUE; + if(thisPlayer != nullptr) m_isHostPlayer = thisPlayer->IsHost() == TRUE; Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr localPlayer = pMinecraft->localplayers[m_iPad]; @@ -140,9 +140,9 @@ HRESULT CScene_InGameInfo::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandle if(playersList.TreeHasFocus() && (playersList.GetItemCount() > 0) && (playersList.GetCurSel() < m_playersCount) ) { INetworkPlayer *player = g_NetworkManager.GetPlayerBySmallId(m_players[playersList.GetCurSel()]); - if( player != NULL ) + if( player != nullptr ) { - PlayerUID xuid = ((NetworkPlayerXbox *)player)->GetUID(); + PlayerUID xuid = static_cast(player)->GetUID(); if( xuid != INVALID_XUID ) hr = XShowGamerCardUI(pInputData->UserIndex, xuid); } @@ -189,7 +189,7 @@ HRESULT CScene_InGameInfo::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; bool trust = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; - if( isOp && selectedPlayer != NULL && playersList.TreeHasFocus() && (playersList.GetItemCount() > 0) && (playersList.GetCurSel() < m_playersCount) ) + if( isOp && selectedPlayer != nullptr && playersList.TreeHasFocus() && (playersList.GetItemCount() > 0) && (playersList.GetCurSel() < m_playersCount) ) { bool editingHost = selectedPlayer->IsHost(); if( (cheats && (m_isHostPlayer || !editingHost ) ) @@ -268,7 +268,7 @@ HRESULT CScene_InGameInfo::OnNotifySetFocus( HXUIOBJ hObjSource, XUINotifyFocus void CScene_InGameInfo::OnPlayerChanged(void *callbackParam, INetworkPlayer *pPlayer, bool leaving) { - CScene_InGameInfo *scene = (CScene_InGameInfo *)callbackParam; + CScene_InGameInfo *scene = static_cast(callbackParam); bool playerFound = false; for(int i = 0; i < scene->m_playersCount; ++i) @@ -311,7 +311,7 @@ HRESULT CScene_InGameInfo::OnGetSourceDataText(XUIMessageGetSourceText *pGetSour if( pGetSourceTextData->iItem < m_playersCount ) { INetworkPlayer *player = g_NetworkManager.GetPlayerBySmallId( m_players[pGetSourceTextData->iItem] ); - if( player != NULL ) + if( player != nullptr ) { #ifndef _CONTENT_PACKAGE if(app.DebugSettingsOn() && (app.GetGameSettingsDebugMask()&(1L<HasVoice() ) + if(player != nullptr && player->HasVoice() ) { if( player->IsMutedByLocalUser(m_iPad) ) { @@ -477,7 +477,7 @@ void CScene_InGameInfo::updateTooltips() { keyA = IDS_TOOLTIPS_SELECT; } - else if( selectedPlayer != NULL) + else if( selectedPlayer != nullptr) { bool editingHost = selectedPlayer->IsHost(); if( (cheats && (m_isHostPlayer || !editingHost ) ) || (!trust && (m_isHostPlayer || !editingHost)) @@ -499,7 +499,7 @@ void CScene_InGameInfo::updateTooltips() if(!m_gameOptionsButton.HasFocus()) { // if the player is me, then view gamer profile - if(selectedPlayer != NULL && selectedPlayer->IsLocal() && selectedPlayer->GetUserIndex()==m_iPad) + if(selectedPlayer != nullptr && selectedPlayer->IsLocal() && selectedPlayer->GetUserIndex()==m_iPad) { ikeyY = IDS_TOOLTIPS_VIEW_GAMERPROFILE; } @@ -520,16 +520,16 @@ HRESULT CScene_InGameInfo::OnCustomMessage_Splitscreenplayer(bool bJoining, BOOL int CScene_InGameInfo::KickPlayerReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - BYTE smallId = *(BYTE *)pParam; + BYTE smallId = *static_cast(pParam); delete pParam; if(result==C4JStorage::EMessage_ResultAccept) { Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr localPlayer = pMinecraft->localplayers[iPad]; - if(localPlayer != NULL && localPlayer->connection) + if(localPlayer != nullptr && localPlayer->connection) { - localPlayer->connection->send( shared_ptr( new KickPlayerPacket(smallId) ) ); + localPlayer->connection->send(std::make_shared(smallId)); } } diff --git a/Minecraft.Client/Common/XUI/XUI_InGamePlayerOptions.cpp b/Minecraft.Client/Common/XUI/XUI_InGamePlayerOptions.cpp index 156cd0925..4ab2a54a2 100644 --- a/Minecraft.Client/Common/XUI/XUI_InGamePlayerOptions.cpp +++ b/Minecraft.Client/Common/XUI/XUI_InGamePlayerOptions.cpp @@ -16,9 +16,9 @@ //---------------------------------------------------------------------------------- HRESULT CScene_InGamePlayerOptions::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); - InGamePlayerOptionsInitData *initData = (InGamePlayerOptionsInitData *)pInitData->pvInitData; + InGamePlayerOptionsInitData *initData = static_cast(pInitData->pvInitData); m_iPad = initData->iPad; m_networkSmallId = initData->networkSmallId; m_playerPrivileges = initData->playerPrivileges; @@ -32,14 +32,14 @@ HRESULT CScene_InGamePlayerOptions::OnInit( XUIMessageInit* pInitData, BOOL& bHa INetworkPlayer *localPlayer = g_NetworkManager.GetLocalPlayerByUserIndex( m_iPad ); INetworkPlayer *editingPlayer = g_NetworkManager.GetPlayerBySmallId(m_networkSmallId); - if(editingPlayer != NULL) + if(editingPlayer != nullptr) { m_Gamertag.SetText(editingPlayer->GetOnlineName()); } bool trustPlayers = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; - m_editingSelf = (localPlayer != NULL && localPlayer == editingPlayer); + m_editingSelf = (localPlayer != nullptr && localPlayer == editingPlayer); if( m_editingSelf || trustPlayers || editingPlayer->IsHost()) { @@ -247,7 +247,7 @@ HRESULT CScene_InGamePlayerOptions::OnKeyDown(XUIMessageInput* pInputData, BOOL& else { INetworkPlayer *editingPlayer = g_NetworkManager.GetPlayerBySmallId(m_networkSmallId); - if(!trustPlayers && (editingPlayer != NULL && !editingPlayer->IsHost() ) ) + if(!trustPlayers && (editingPlayer != nullptr && !editingPlayer->IsHost() ) ) { Player::setPlayerGamePrivilege(m_playerPrivileges,Player::ePlayerGamePrivilege_CannotMine,!m_checkboxes[eControl_BuildAndMine].IsChecked()); Player::setPlayerGamePrivilege(m_playerPrivileges,Player::ePlayerGamePrivilege_CannotBuild,!m_checkboxes[eControl_BuildAndMine].IsChecked()); @@ -278,9 +278,9 @@ HRESULT CScene_InGamePlayerOptions::OnKeyDown(XUIMessageInput* pInputData, BOOL& // Send update settings packet to server Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player != NULL && player->connection) + if(player != nullptr && player->connection) { - player->connection->send( shared_ptr( new PlayerInfoPacket( m_networkSmallId, -1, m_playerPrivileges) ) ); + player->connection->send(std::make_shared(m_networkSmallId, -1, m_playerPrivileges)); } } @@ -320,7 +320,7 @@ HRESULT CScene_InGamePlayerOptions::OnControlNavigate(XUIMessageControlNavigate { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -330,16 +330,16 @@ HRESULT CScene_InGamePlayerOptions::OnControlNavigate(XUIMessageControlNavigate int CScene_InGamePlayerOptions::KickPlayerReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - BYTE smallId = *(BYTE *)pParam; + BYTE smallId = *static_cast(pParam); delete pParam; if(result==C4JStorage::EMessage_ResultAccept) { Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr localPlayer = pMinecraft->localplayers[iPad]; - if(localPlayer != NULL && localPlayer->connection) + if(localPlayer != nullptr && localPlayer->connection) { - localPlayer->connection->send( shared_ptr( new KickPlayerPacket(smallId) ) ); + localPlayer->connection->send(std::make_shared(smallId)); } // Fix for #61494 - [CRASH]: TU7: Code: Multiplayer: Title may crash while kicking a player from an online game. @@ -353,16 +353,16 @@ int CScene_InGamePlayerOptions::KickPlayerReturned(void *pParam,int iPad,C4JStor void CScene_InGamePlayerOptions::OnPlayerChanged(void *callbackParam, INetworkPlayer *pPlayer, bool leaving) { - CScene_InGamePlayerOptions *scene = (CScene_InGamePlayerOptions *)callbackParam; + CScene_InGamePlayerOptions *scene = static_cast(callbackParam); HXUIOBJ hBackScene = scene->GetBackScene(); CScene_InGameInfo* infoScene; VOID *pObj; XuiObjectFromHandle( hBackScene, &pObj ); - infoScene = (CScene_InGameInfo *)pObj; - if(infoScene != NULL) CScene_InGameInfo::OnPlayerChanged(infoScene,pPlayer,leaving); + infoScene = static_cast(pObj); + if(infoScene != nullptr) CScene_InGameInfo::OnPlayerChanged(infoScene,pPlayer,leaving); - if(leaving && pPlayer != NULL && pPlayer->GetSmallId() == scene->m_networkSmallId) + if(leaving && pPlayer != nullptr && pPlayer->GetSmallId() == scene->m_networkSmallId) { app.NavigateBack(scene->m_iPad); } @@ -373,59 +373,59 @@ HRESULT CScene_InGamePlayerOptions::OnTransitionStart( XUIMessageTransition *pTr if(pTransition->dwTransType == XUI_TRANSITION_TO || pTransition->dwTransType == XUI_TRANSITION_BACKTO) { INetworkPlayer *editingPlayer = g_NetworkManager.GetPlayerBySmallId(m_networkSmallId); - if(editingPlayer != NULL) + if(editingPlayer != nullptr) { short colourIndex = app.GetPlayerColour( m_networkSmallId ); switch(colourIndex) { case 1: - m_Icon.PlayVisualRange(L"P1",NULL,L"P1"); + m_Icon.PlayVisualRange(L"P1",nullptr,L"P1"); break; case 2: - m_Icon.PlayVisualRange(L"P2",NULL,L"P2"); + m_Icon.PlayVisualRange(L"P2",nullptr,L"P2"); break; case 3: - m_Icon.PlayVisualRange(L"P3",NULL,L"P3"); + m_Icon.PlayVisualRange(L"P3",nullptr,L"P3"); break; case 4: - m_Icon.PlayVisualRange(L"P4",NULL,L"P4"); + m_Icon.PlayVisualRange(L"P4",nullptr,L"P4"); break; case 5: - m_Icon.PlayVisualRange(L"P5",NULL,L"P5"); + m_Icon.PlayVisualRange(L"P5",nullptr,L"P5"); break; case 6: - m_Icon.PlayVisualRange(L"P6",NULL,L"P6"); + m_Icon.PlayVisualRange(L"P6",nullptr,L"P6"); break; case 7: - m_Icon.PlayVisualRange(L"P7",NULL,L"P7"); + m_Icon.PlayVisualRange(L"P7",nullptr,L"P7"); break; case 8: - m_Icon.PlayVisualRange(L"P8",NULL,L"P8"); + m_Icon.PlayVisualRange(L"P8",nullptr,L"P8"); break; case 9: - m_Icon.PlayVisualRange(L"P9",NULL,L"P9"); + m_Icon.PlayVisualRange(L"P9",nullptr,L"P9"); break; case 10: - m_Icon.PlayVisualRange(L"P10",NULL,L"P10"); + m_Icon.PlayVisualRange(L"P10",nullptr,L"P10"); break; case 11: - m_Icon.PlayVisualRange(L"P11",NULL,L"P11"); + m_Icon.PlayVisualRange(L"P11",nullptr,L"P11"); break; case 12: - m_Icon.PlayVisualRange(L"P12",NULL,L"P12"); + m_Icon.PlayVisualRange(L"P12",nullptr,L"P12"); break; case 13: - m_Icon.PlayVisualRange(L"P13",NULL,L"P13"); + m_Icon.PlayVisualRange(L"P13",nullptr,L"P13"); break; case 14: - m_Icon.PlayVisualRange(L"P14",NULL,L"P14"); + m_Icon.PlayVisualRange(L"P14",nullptr,L"P14"); break; case 15: - m_Icon.PlayVisualRange(L"P15",NULL,L"P15"); + m_Icon.PlayVisualRange(L"P15",nullptr,L"P15"); break; case 0: default: - m_Icon.PlayVisualRange(L"P0",NULL,L"P0"); + m_Icon.PlayVisualRange(L"P0",nullptr,L"P0"); break; }; } diff --git a/Minecraft.Client/Common/XUI/XUI_Leaderboards.cpp b/Minecraft.Client/Common/XUI/XUI_Leaderboards.cpp index 428b3e88a..7fde530bf 100644 --- a/Minecraft.Client/Common/XUI/XUI_Leaderboards.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Leaderboards.cpp @@ -33,9 +33,9 @@ LPCWSTR CScene_Leaderboards::m_TextColumnNameA[7]= // if the value is greater than 511, it's an xzp icon that needs displayed, rather than the game icon const int CScene_Leaderboards::TitleIcons[CScene_Leaderboards::NUM_LEADERBOARDS][7] = { - { XZP_ICON_WALKED, XZP_ICON_FALLEN, Item::minecart_Id, Item::boat_Id, NULL }, + { XZP_ICON_WALKED, XZP_ICON_FALLEN, Item::minecart_Id, Item::boat_Id, nullptr }, { Tile::dirt_Id, Tile::stoneBrick_Id, Tile::sand_Id, Tile::rock_Id, Tile::gravel_Id, Tile::clay_Id, Tile::obsidian_Id }, - { Item::egg_Id, Item::wheat_Id, Tile::mushroom1_Id, Tile::reeds_Id, Item::milk_Id, Tile::pumpkin_Id, NULL }, + { Item::egg_Id, Item::wheat_Id, Tile::mushroom1_Id, Tile::reeds_Id, Item::milk_Id, Tile::pumpkin_Id, nullptr }, { XZP_ICON_ZOMBIE, XZP_ICON_SKELETON, XZP_ICON_CREEPER, XZP_ICON_SPIDER, XZP_ICON_SPIDERJOCKEY, XZP_ICON_ZOMBIEPIGMAN, XZP_ICON_SLIME }, }; @@ -43,44 +43,44 @@ const int CScene_Leaderboards::LEADERBOARD_HEADERS[CScene_Leaderboards::NUM_LEAD { SPASTRING_LB_TRAVELLING_PEACEFUL_NAME, SPASTRING_LB_TRAVELLING_EASY_NAME, SPASTRING_LB_TRAVELLING_NORMAL_NAME, SPASTRING_LB_TRAVELLING_HARD_NAME }, { SPASTRING_LB_MINING_BLOCKS_PEACEFUL_NAME, SPASTRING_LB_MINING_BLOCKS_EASY_NAME, SPASTRING_LB_MINING_BLOCKS_NORMAL_NAME, SPASTRING_LB_MINING_BLOCKS_HARD_NAME }, { SPASTRING_LB_FARMING_PEACEFUL_NAME, SPASTRING_LB_FARMING_EASY_NAME, SPASTRING_LB_FARMING_NORMAL_NAME, SPASTRING_LB_FARMING_HARD_NAME }, - { NULL, SPASTRING_LB_KILLS_EASY_NAME, SPASTRING_LB_KILLS_NORMAL_NAME, SPASTRING_LB_KILLS_HARD_NAME }, + { nullptr, SPASTRING_LB_KILLS_EASY_NAME, SPASTRING_LB_KILLS_NORMAL_NAME, SPASTRING_LB_KILLS_HARD_NAME }, }; const CScene_Leaderboards::LeaderboardDescriptor CScene_Leaderboards::LEADERBOARD_DESCRIPTORS[CScene_Leaderboards::NUM_LEADERBOARDS][4] = { { - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_PEACEFUL, 4, STATS_COLUMN_TRAVELLING_PEACEFUL_WALKED, STATS_COLUMN_TRAVELLING_PEACEFUL_FALLEN, STATS_COLUMN_TRAVELLING_PEACEFUL_MINECART, STATS_COLUMN_TRAVELLING_PEACEFUL_BOAT, NULL, NULL, NULL,NULL), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_EASY, 4, STATS_COLUMN_TRAVELLING_EASY_WALKED, STATS_COLUMN_TRAVELLING_EASY_FALLEN, STATS_COLUMN_TRAVELLING_EASY_MINECART, STATS_COLUMN_TRAVELLING_EASY_BOAT, NULL, NULL, NULL,NULL), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_NORMAL, 4, STATS_COLUMN_TRAVELLING_NORMAL_WALKED, STATS_COLUMN_TRAVELLING_NORMAL_FALLEN, STATS_COLUMN_TRAVELLING_NORMAL_MINECART, STATS_COLUMN_TRAVELLING_NORMAL_BOAT, NULL, NULL, NULL,NULL), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_HARD, 4, STATS_COLUMN_TRAVELLING_HARD_WALKED, STATS_COLUMN_TRAVELLING_HARD_FALLEN, STATS_COLUMN_TRAVELLING_HARD_MINECART, STATS_COLUMN_TRAVELLING_HARD_BOAT, NULL, NULL, NULL,NULL), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_PEACEFUL, 4, STATS_COLUMN_TRAVELLING_PEACEFUL_WALKED, STATS_COLUMN_TRAVELLING_PEACEFUL_FALLEN, STATS_COLUMN_TRAVELLING_PEACEFUL_MINECART, STATS_COLUMN_TRAVELLING_PEACEFUL_BOAT, nullptr, nullptr, nullptr,nullptr), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_EASY, 4, STATS_COLUMN_TRAVELLING_EASY_WALKED, STATS_COLUMN_TRAVELLING_EASY_FALLEN, STATS_COLUMN_TRAVELLING_EASY_MINECART, STATS_COLUMN_TRAVELLING_EASY_BOAT, nullptr, nullptr, nullptr,nullptr), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_NORMAL, 4, STATS_COLUMN_TRAVELLING_NORMAL_WALKED, STATS_COLUMN_TRAVELLING_NORMAL_FALLEN, STATS_COLUMN_TRAVELLING_NORMAL_MINECART, STATS_COLUMN_TRAVELLING_NORMAL_BOAT, nullptr, nullptr, nullptr,nullptr), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_HARD, 4, STATS_COLUMN_TRAVELLING_HARD_WALKED, STATS_COLUMN_TRAVELLING_HARD_FALLEN, STATS_COLUMN_TRAVELLING_HARD_MINECART, STATS_COLUMN_TRAVELLING_HARD_BOAT, nullptr, nullptr, nullptr,nullptr), }, { - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_PEACEFUL, 7, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_DIRT, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_STONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_SAND, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_CLAY, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_OBSIDIAN,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_EASY, 7, STATS_COLUMN_MINING_BLOCKS_EASY_DIRT, STATS_COLUMN_MINING_BLOCKS_EASY_STONE, STATS_COLUMN_MINING_BLOCKS_EASY_SAND, STATS_COLUMN_MINING_BLOCKS_EASY_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_EASY_GRAVEL, STATS_COLUMN_MINING_BLOCKS_EASY_CLAY, STATS_COLUMN_MINING_BLOCKS_EASY_OBSIDIAN,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_NORMAL, 7, STATS_COLUMN_MINING_BLOCKS_NORMAL_DIRT, STATS_COLUMN_MINING_BLOCKS_NORMAL_STONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_SAND, STATS_COLUMN_MINING_BLOCKS_NORMAL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_NORMAL_CLAY, STATS_COLUMN_MINING_BLOCKS_NORMAL_OBSIDIAN,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_HARD, 7, STATS_COLUMN_MINING_BLOCKS_HARD_DIRT, STATS_COLUMN_MINING_BLOCKS_HARD_STONE, STATS_COLUMN_MINING_BLOCKS_HARD_SAND, STATS_COLUMN_MINING_BLOCKS_HARD_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_HARD_GRAVEL, STATS_COLUMN_MINING_BLOCKS_HARD_CLAY, STATS_COLUMN_MINING_BLOCKS_HARD_OBSIDIAN,NULL ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_PEACEFUL, 7, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_DIRT, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_STONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_SAND, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_CLAY, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_OBSIDIAN,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_EASY, 7, STATS_COLUMN_MINING_BLOCKS_EASY_DIRT, STATS_COLUMN_MINING_BLOCKS_EASY_STONE, STATS_COLUMN_MINING_BLOCKS_EASY_SAND, STATS_COLUMN_MINING_BLOCKS_EASY_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_EASY_GRAVEL, STATS_COLUMN_MINING_BLOCKS_EASY_CLAY, STATS_COLUMN_MINING_BLOCKS_EASY_OBSIDIAN,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_NORMAL, 7, STATS_COLUMN_MINING_BLOCKS_NORMAL_DIRT, STATS_COLUMN_MINING_BLOCKS_NORMAL_STONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_SAND, STATS_COLUMN_MINING_BLOCKS_NORMAL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_NORMAL_CLAY, STATS_COLUMN_MINING_BLOCKS_NORMAL_OBSIDIAN,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_HARD, 7, STATS_COLUMN_MINING_BLOCKS_HARD_DIRT, STATS_COLUMN_MINING_BLOCKS_HARD_STONE, STATS_COLUMN_MINING_BLOCKS_HARD_SAND, STATS_COLUMN_MINING_BLOCKS_HARD_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_HARD_GRAVEL, STATS_COLUMN_MINING_BLOCKS_HARD_CLAY, STATS_COLUMN_MINING_BLOCKS_HARD_OBSIDIAN,nullptr ), }, { - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_PEACEFUL, 6, STATS_COLUMN_FARMING_PEACEFUL_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_PEACEFUL_MUSHROOMS, STATS_COLUMN_FARMING_PEACEFUL_SUGARCANE, STATS_COLUMN_FARMING_PEACEFUL_MILK, STATS_COLUMN_FARMING_PEACEFUL_PUMPKINS, NULL,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_EASY, 6, STATS_COLUMN_FARMING_EASY_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_EASY_MUSHROOMS, STATS_COLUMN_FARMING_EASY_SUGARCANE, STATS_COLUMN_FARMING_EASY_MILK, STATS_COLUMN_FARMING_EASY_PUMPKINS, NULL,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_NORMAL, 6, STATS_COLUMN_FARMING_NORMAL_EGGS, STATS_COLUMN_FARMING_NORMAL_WHEAT, STATS_COLUMN_FARMING_NORMAL_MUSHROOMS, STATS_COLUMN_FARMING_NORMAL_SUGARCANE, STATS_COLUMN_FARMING_NORMAL_MILK, STATS_COLUMN_FARMING_NORMAL_PUMPKINS, NULL,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_HARD, 6, STATS_COLUMN_FARMING_HARD_EGGS, STATS_COLUMN_FARMING_HARD_WHEAT, STATS_COLUMN_FARMING_HARD_MUSHROOMS, STATS_COLUMN_FARMING_HARD_SUGARCANE, STATS_COLUMN_FARMING_HARD_MILK, STATS_COLUMN_FARMING_HARD_PUMPKINS, NULL,NULL ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_PEACEFUL, 6, STATS_COLUMN_FARMING_PEACEFUL_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_PEACEFUL_MUSHROOMS, STATS_COLUMN_FARMING_PEACEFUL_SUGARCANE, STATS_COLUMN_FARMING_PEACEFUL_MILK, STATS_COLUMN_FARMING_PEACEFUL_PUMPKINS, nullptr,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_EASY, 6, STATS_COLUMN_FARMING_EASY_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_EASY_MUSHROOMS, STATS_COLUMN_FARMING_EASY_SUGARCANE, STATS_COLUMN_FARMING_EASY_MILK, STATS_COLUMN_FARMING_EASY_PUMPKINS, nullptr,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_NORMAL, 6, STATS_COLUMN_FARMING_NORMAL_EGGS, STATS_COLUMN_FARMING_NORMAL_WHEAT, STATS_COLUMN_FARMING_NORMAL_MUSHROOMS, STATS_COLUMN_FARMING_NORMAL_SUGARCANE, STATS_COLUMN_FARMING_NORMAL_MILK, STATS_COLUMN_FARMING_NORMAL_PUMPKINS, nullptr,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_FARMING_HARD, 6, STATS_COLUMN_FARMING_HARD_EGGS, STATS_COLUMN_FARMING_HARD_WHEAT, STATS_COLUMN_FARMING_HARD_MUSHROOMS, STATS_COLUMN_FARMING_HARD_SUGARCANE, STATS_COLUMN_FARMING_HARD_MILK, STATS_COLUMN_FARMING_HARD_PUMPKINS, nullptr,nullptr ), }, { - CScene_Leaderboards::LeaderboardDescriptor( NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_EASY, 7, STATS_COLUMN_KILLS_EASY_ZOMBIES, STATS_COLUMN_KILLS_EASY_SKELETONS, STATS_COLUMN_KILLS_EASY_CREEPERS, STATS_COLUMN_KILLS_EASY_SPIDERS, STATS_COLUMN_KILLS_EASY_SPIDERJOCKEYS, STATS_COLUMN_KILLS_EASY_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_EASY_SLIME,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_NORMAL, 7, STATS_COLUMN_KILLS_NORMAL_ZOMBIES, STATS_COLUMN_KILLS_NORMAL_SKELETONS, STATS_COLUMN_KILLS_NORMAL_CREEPERS, STATS_COLUMN_KILLS_NORMAL_SPIDERS, STATS_COLUMN_KILLS_NORMAL_SPIDERJOCKEYS, STATS_COLUMN_KILLS_NORMAL_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_NORMAL_SLIME,NULL ), - CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_HARD, 7, STATS_COLUMN_KILLS_HARD_ZOMBIES, STATS_COLUMN_KILLS_HARD_SKELETONS, STATS_COLUMN_KILLS_HARD_CREEPERS, STATS_COLUMN_KILLS_HARD_SPIDERS, STATS_COLUMN_KILLS_HARD_SPIDERJOCKEYS, STATS_COLUMN_KILLS_HARD_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_HARD_SLIME,NULL ), + CScene_Leaderboards::LeaderboardDescriptor( nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_EASY, 7, STATS_COLUMN_KILLS_EASY_ZOMBIES, STATS_COLUMN_KILLS_EASY_SKELETONS, STATS_COLUMN_KILLS_EASY_CREEPERS, STATS_COLUMN_KILLS_EASY_SPIDERS, STATS_COLUMN_KILLS_EASY_SPIDERJOCKEYS, STATS_COLUMN_KILLS_EASY_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_EASY_SLIME,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_NORMAL, 7, STATS_COLUMN_KILLS_NORMAL_ZOMBIES, STATS_COLUMN_KILLS_NORMAL_SKELETONS, STATS_COLUMN_KILLS_NORMAL_CREEPERS, STATS_COLUMN_KILLS_NORMAL_SPIDERS, STATS_COLUMN_KILLS_NORMAL_SPIDERJOCKEYS, STATS_COLUMN_KILLS_NORMAL_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_NORMAL_SLIME,nullptr ), + CScene_Leaderboards::LeaderboardDescriptor( STATS_VIEW_KILLS_HARD, 7, STATS_COLUMN_KILLS_HARD_ZOMBIES, STATS_COLUMN_KILLS_HARD_SKELETONS, STATS_COLUMN_KILLS_HARD_CREEPERS, STATS_COLUMN_KILLS_HARD_SPIDERS, STATS_COLUMN_KILLS_HARD_SPIDERJOCKEYS, STATS_COLUMN_KILLS_HARD_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_HARD_SLIME,nullptr ), }, }; HRESULT CScene_Leaderboards::OnInit(XUIMessageInit *pInitData, BOOL &bHandled) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); m_bReady=false; // if we're not in the game, we need to use basescene 0 - if(Minecraft::GetInstance()->level==NULL) + if(Minecraft::GetInstance()->level==nullptr) { m_iPad=DEFAULT_XUI_MENU_USER; } @@ -90,9 +90,9 @@ HRESULT CScene_Leaderboards::OnInit(XUIMessageInit *pInitData, BOOL &bHandled) ui.SetTooltips(m_iPad,-1, IDS_TOOLTIPS_BACK, IDS_TOOLTIPS_CHANGE_FILTER, -1); CXuiSceneBase::ShowLogo( m_iPad, FALSE ); - m_friends = NULL; + m_friends = nullptr; m_numFriends = 0; - m_filteredFriends = NULL; + m_filteredFriends = nullptr; m_numFilteredFriends = 0; m_newTop = m_newSel = -1; @@ -124,10 +124,10 @@ HRESULT CScene_Leaderboards::OnInit(XUIMessageInit *pInitData, BOOL &bHandled) // title icons for(int i=0;i<7;i++) { - m_pHTitleIconSlots[i]=NULL; + m_pHTitleIconSlots[i]=nullptr; m_fTitleIconXPositions[i]=0.0f; m_fTextXPositions[i]=0.0f; - m_hTextEntryA[i]=NULL; + m_hTextEntryA[i]=nullptr; } @@ -143,13 +143,13 @@ void CScene_Leaderboards::Reposition(int iNumber) D3DXVECTOR3 vPos; fIconSize=(m_fTitleIconXPositions[6]-m_fTitleIconXPositions[0])/6.0f; - fNewIconIncrement=(fIconSize*7.0f)/(float)iNumber; + fNewIconIncrement=(fIconSize*7.0f)/static_cast(iNumber); // reposition the title icons based on the number there are for(int i=0;iGetPosition(&vPos); - vPos.x=m_fTitleIconXPositions[0]+(((float)i)*fNewIconIncrement)+(fNewIconIncrement-fIconSize)/2.0f; + vPos.x=m_fTitleIconXPositions[0]+(static_cast(i)*fNewIconIncrement)+(fNewIconIncrement-fIconSize)/2.0f; m_pHTitleIconSlots[i]->SetPosition(&vPos); } } @@ -161,14 +161,14 @@ void CScene_Leaderboards::RepositionText(int iNumber) D3DXVECTOR3 vPos; fTextSize=(m_fTextXPositions[6]-m_fTextXPositions[0])/6.0f; - fNewTextIncrement=(fTextSize*7.0f)/(float)iNumber; + fNewTextIncrement=(fTextSize*7.0f)/static_cast(iNumber); // reposition the title icons based on the number there are for(int i=0;i(i)*fNewTextIncrement); XuiElementSetPosition(m_hTextEntryA[i],&vPos); // and change the size float fWidth,fHeight; @@ -190,10 +190,10 @@ HRESULT CScene_Leaderboards::OnDestroy() Sleep( 10 ); } - if( m_friends != NULL ) + if( m_friends != nullptr ) delete [] m_friends; - if( m_filteredFriends != NULL ) + if( m_filteredFriends != nullptr ) delete [] m_filteredFriends; return S_OK; @@ -222,7 +222,7 @@ void CScene_Leaderboards::UpdateTooltips() int iTooltipGamerCardOrProfile=-1; if( m_leaderboard.m_currentEntryCount > 0 ) { - unsigned int selection = (unsigned int)m_listGamers.GetCurSel(); + unsigned int selection = static_cast(m_listGamers.GetCurSel()); // if the selected user is me, don't show Send Friend Request, and show the gamer profile, not the gamer card @@ -368,7 +368,7 @@ HRESULT CScene_Leaderboards::OnKeyDown(XUIMessageInput* pInputData, BOOL& bHandl else { m_newTop = m_listGamers.GetTopItem() + 10; - if( m_newTop+10 > (int)m_leaderboard.m_totalEntryCount ) + if( m_newTop+10 > static_cast(m_leaderboard.m_totalEntryCount) ) { m_newTop = m_leaderboard.m_totalEntryCount - 10; if( m_newTop < 0 ) @@ -426,7 +426,7 @@ HRESULT CScene_Leaderboards::OnKeyDown(XUIMessageInput* pInputData, BOOL& bHandl //Show gamercard if( m_leaderboard.m_currentEntryCount > 0 ) { - unsigned int selection = (unsigned int)m_listGamers.GetCurSel(); + unsigned int selection = static_cast(m_listGamers.GetCurSel()); if( selection >= m_leaderboard.m_entryStartIndex-1 && selection < (m_leaderboard.m_entryStartIndex+m_leaderboard.m_currentEntryCount-1) ) { @@ -448,7 +448,7 @@ HRESULT CScene_Leaderboards::OnKeyDown(XUIMessageInput* pInputData, BOOL& bHandl { if( m_leaderboard.m_currentEntryCount > 0 ) { - unsigned int selection = (unsigned int)m_listGamers.GetCurSel(); + unsigned int selection = static_cast(m_listGamers.GetCurSel()); if( selection >= m_leaderboard.m_entryStartIndex-1 && selection < (m_leaderboard.m_entryStartIndex+m_leaderboard.m_currentEntryCount-1) ) { @@ -511,7 +511,7 @@ void CScene_Leaderboards::GetFriends() m_friends, resultsSize, &numFriends, - NULL ); + nullptr ); if( ret != ERROR_SUCCESS ) numFriends = 0; @@ -547,7 +547,7 @@ void CScene_Leaderboards::ReadStats(int startIndex) } else { - m_newEntryIndex = (unsigned int)startIndex; + m_newEntryIndex = static_cast(startIndex); m_newReadSize = min((int)READ_SIZE, (int)m_leaderboard.m_totalEntryCount-(startIndex-1)); } @@ -574,20 +574,20 @@ void CScene_Leaderboards::ReadStats(int startIndex) { case LeaderboardManager::eFM_TopRank: LeaderboardManager::Instance()->ReadStats_TopRank( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), m_newEntryIndex, m_newReadSize ); break; case LeaderboardManager::eFM_MyScore: LeaderboardManager::Instance()->ReadStats_MyScore( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), INVALID_XUID/*ignored*/, m_newReadSize ); break; case LeaderboardManager::eFM_Friends: LeaderboardManager::Instance()->ReadStats_Friends( this, - m_currentDifficulty, (LeaderboardManager::EStatsType) m_currentLeaderboard, + m_currentDifficulty, static_cast(m_currentLeaderboard), INVALID_XUID /*ignored*/, 0 /*ignored*/, 0 /*ignored*/ ); @@ -660,7 +660,7 @@ bool CScene_Leaderboards::RetrieveStats() else { m_leaderboard.m_entries[entryIndex].m_columns[i] = UINT_MAX; - swprintf(m_leaderboard.m_entries[entryIndex].m_wcColumns[i], 12, L"%.1fkm", ((float)m_leaderboard.m_entries[entryIndex].m_columns[i])/100.f/1000.f); + swprintf(m_leaderboard.m_entries[entryIndex].m_wcColumns[i], 12, L"%.1fkm", static_cast(m_leaderboard.m_entries[entryIndex].m_columns[i])/100.f/1000.f); } } @@ -675,7 +675,7 @@ bool CScene_Leaderboards::RetrieveStats() return true; } - //assert( LeaderboardManager::Instance()->GetStats() != NULL ); + //assert( LeaderboardManager::Instance()->GetStats() != nullptr ); //PXUSER_STATS_READ_RESULTS stats = LeaderboardManager::Instance()->GetStats(); //if( m_currentFilter == LeaderboardManager::eFM_Friends ) LeaderboardManager::Instance()->SortFriendStats(); @@ -822,7 +822,7 @@ HRESULT CScene_Leaderboards::OnGetSourceDataText(XUIMessageGetSourceText *pGetSo int readIndex = m_leaderboard.m_entryStartIndex - READ_SIZE; if( readIndex <= 0 ) readIndex = 1; - assert( readIndex >= 1 && readIndex <= (int)m_leaderboard.m_totalEntryCount ); + assert( readIndex >= 1 && readIndex <= static_cast(m_leaderboard.m_totalEntryCount)); ReadStats(readIndex); } } @@ -831,7 +831,7 @@ HRESULT CScene_Leaderboards::OnGetSourceDataText(XUIMessageGetSourceText *pGetSo if( LeaderboardManager::Instance()->isIdle() ) { int readIndex = m_leaderboard.m_entryStartIndex + m_leaderboard.m_currentEntryCount; - assert( readIndex >= 1 && readIndex <= (int)m_leaderboard.m_totalEntryCount ); + assert( readIndex >= 1 && readIndex <= static_cast(m_leaderboard.m_totalEntryCount)); ReadStats(readIndex); } } @@ -850,7 +850,7 @@ HRESULT CScene_Leaderboards::OnGetSourceDataText(XUIMessageGetSourceText *pGetSo } else if( pGetSourceTextData->iData >= 3 && pGetSourceTextData->iData <= 9 ) { - if( m_leaderboard.m_numColumns <= (unsigned int)(pGetSourceTextData->iData-3) ) + if( m_leaderboard.m_numColumns <= static_cast(pGetSourceTextData->iData - 3) ) pGetSourceTextData->szText = L""; else pGetSourceTextData->szText = m_leaderboard.m_entries[index].m_wcColumns[pGetSourceTextData->iData-3]; @@ -898,11 +898,11 @@ HRESULT CScene_Leaderboards::OnGetSourceDataImage(XUIMessageGetSourceImage* pGet void CScene_Leaderboards::PopulateLeaderboard(bool noResults) { HRESULT hr; - HXUIOBJ visual=NULL; - HXUIOBJ hTemp=NULL; + HXUIOBJ visual=nullptr; + HXUIOBJ hTemp=nullptr; hr=XuiControlGetVisual(m_listGamers.m_hObj,&visual); - if(m_pHTitleIconSlots[0]==NULL) + if(m_pHTitleIconSlots[0]==nullptr) { VOID *pObj; HXUIOBJ button; @@ -914,7 +914,7 @@ void CScene_Leaderboards::PopulateLeaderboard(bool noResults) hr=XuiElementGetChildById(visual,m_TitleIconNameA[i],&button); XuiObjectFromHandle( button, &pObj ); - m_pHTitleIconSlots[i] = (CXuiCtrlCraftIngredientSlot *)pObj; + m_pHTitleIconSlots[i] = static_cast(pObj); // store the default position, since we'll be repositioning these depending on how many are valid for each board m_pHTitleIconSlots[i]->GetPosition(&vPos); @@ -964,7 +964,7 @@ void CScene_Leaderboards::PopulateLeaderboard(bool noResults) // Really only the newly updated rows need changed, but this shouldn't cause any performance issues for(DWORD i = m_leaderboard.m_entryStartIndex - 1; i < (m_leaderboard.m_entryStartIndex - 1) + m_leaderboard.m_currentEntryCount; ++i) { - HXUIOBJ visual=NULL; + HXUIOBJ visual=nullptr; HXUIOBJ button; D3DXVECTOR3 vPos; // 4J-PB - fix for #13768 - Leaderboards: Player scores appear misaligned when viewed under the "My Score" leaderboard filter @@ -1088,24 +1088,24 @@ void CScene_Leaderboards::CopyLeaderboardEntry(PXUSER_STATS_ROW statsRow, Leader else if(iDigitC<8) { // km with a .X - swprintf_s(leaderboardEntry->m_wcColumns[i], 12, L"%.1fkm", ((float)leaderboardEntry->m_columns[i])/1000.f); + swprintf_s(leaderboardEntry->m_wcColumns[i], 12, L"%.1fkm", static_cast(leaderboardEntry->m_columns[i])/1000.f); #ifdef _DEBUG - app.DebugPrintf("Display - %.1fkm\n", ((float)leaderboardEntry->m_columns[i])/1000.f); + app.DebugPrintf("Display - %.1fkm\n", static_cast(leaderboardEntry->m_columns[i])/1000.f); #endif } else { // bigger than that, so no decimal point - swprintf_s(leaderboardEntry->m_wcColumns[i], 12, L"%.0fkm", ((float)leaderboardEntry->m_columns[i])/1000.f); + swprintf_s(leaderboardEntry->m_wcColumns[i], 12, L"%.0fkm", static_cast(leaderboardEntry->m_columns[i])/1000.f); #ifdef _DEBUG - app.DebugPrintf("Display - %.0fkm\n", ((float)leaderboardEntry->m_columns[i])/1000.f); + app.DebugPrintf("Display - %.0fkm\n", static_cast(leaderboardEntry->m_columns[i])/1000.f); #endif } } } //Is the player - if( statsRow->xuid == ((XboxLeaderboardManager*)LeaderboardManager::Instance())->GetMyXUID() ) + if( statsRow->xuid == static_cast(LeaderboardManager::Instance())->GetMyXUID() ) { leaderboardEntry->m_bPlayer = true; leaderboardEntry->m_bOnline = false; @@ -1150,7 +1150,7 @@ void CScene_Leaderboards::SetLeaderboardHeader() WCHAR buffer[40]; DWORD bufferLength = 40; - DWORD ret = XResourceGetString(LEADERBOARD_HEADERS[m_currentLeaderboard][m_currentDifficulty], buffer, &bufferLength, NULL); + DWORD ret = XResourceGetString(LEADERBOARD_HEADERS[m_currentLeaderboard][m_currentDifficulty], buffer, &bufferLength, nullptr); if( ret == ERROR_SUCCESS ) m_textLeaderboard.SetText(buffer); @@ -1184,8 +1184,8 @@ void CScene_Leaderboards::ClearLeaderboardTitlebar() m_pHTitleIconSlots[i]->SetShow(FALSE); } - HXUIOBJ visual=NULL; - HXUIOBJ hTemp=NULL; + HXUIOBJ visual=nullptr; + HXUIOBJ hTemp=nullptr; HRESULT hr; hr=XuiControlGetVisual(m_listGamers.m_hObj,&visual); diff --git a/Minecraft.Client/Common/XUI/XUI_LoadSettings.cpp b/Minecraft.Client/Common/XUI/XUI_LoadSettings.cpp index 7f32ff89e..e12957959 100644 --- a/Minecraft.Client/Common/XUI/XUI_LoadSettings.cpp +++ b/Minecraft.Client/Common/XUI/XUI_LoadSettings.cpp @@ -42,14 +42,14 @@ int CScene_LoadGameSettings::m_iDifficultyTitleSettingA[4]= HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_hXuiBrush = NULL; + m_hXuiBrush = nullptr; m_bSetup = false; m_texturePackDescDisplayed = false; - m_iConfigA=NULL; + m_iConfigA=nullptr; WCHAR TempString[256]; - m_params = (LoadMenuInitData *)pInitData->pvInitData; + m_params = static_cast(pInitData->pvInitData); m_MoreOptionsParams.bGenerateOptions=FALSE; m_MoreOptionsParams.bPVP = TRUE; @@ -146,7 +146,7 @@ HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandl else { // set the save icon - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; DWORD dwImageBytes=0; StorageManager.GetSaveCacheFileInfo(m_params->iSaveGameInfoIndex,m_XContentData); @@ -156,13 +156,13 @@ HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandl // Don't delete the image data after creating the xuibrush, since we'll use it in the rename of the save bool bHostOptionsRead = false; unsigned int uiHostOptions = 0; - if(pbImageData==NULL) + if(pbImageData==nullptr) { - DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&m_XContentData,NULL,&dwImageBytes,NULL); + DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&m_XContentData,nullptr,&dwImageBytes,nullptr); if(dwResult==ERROR_SUCCESS) { pbImageData = new BYTE[dwImageBytes]; - XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&m_XContentData,pbImageData,&dwImageBytes,NULL); + XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&m_XContentData,pbImageData,&dwImageBytes,nullptr); XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&m_hXuiBrush); } } @@ -175,9 +175,9 @@ HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandl // #ifdef _DEBUG // // dump out the thumbnail -// HANDLE hThumbnail = CreateFile("GAME:\\thumbnail.png", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, NULL); +// HANDLE hThumbnail = CreateFile("GAME:\\thumbnail.png", GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, nullptr); // DWORD dwBytes; -// WriteFile(hThumbnail,pbImageData,dwImageBytes,&dwBytes,NULL); +// WriteFile(hThumbnail,pbImageData,dwImageBytes,&dwBytes,nullptr); // XCloseHandle(hThumbnail); // #endif @@ -276,7 +276,7 @@ HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandl if(dwImageBytes > 0 && pbImageData) { ListInfo.fEnabled = TRUE; - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tp; + DLCTexturePack *pDLCTexPack=static_cast(tp); if(pDLCTexPack) { int id=pDLCTexPack->getDLCParentPackId(); @@ -310,7 +310,7 @@ HRESULT CScene_LoadGameSettings::OnInit( XUIMessageInit* pInitData, BOOL& bHandl // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -376,7 +376,7 @@ HRESULT CScene_LoadGameSettings::OnControlNavigate(XUIMessageControlNavigate *pC { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -411,7 +411,7 @@ HRESULT CScene_LoadGameSettings::LaunchGame(void) // inform them that leaderboard writes and achievements will be disabled //StorageManager.RequestMessageBox(IDS_TITLE_START_GAME, IDS_CONFIRM_START_SAVEDINCREATIVE_CONTINUE, uiIDA, 1, m_iPad,&CScene_LoadGameSettings::ConfirmLoadReturned,this,app.GetStringTable()); - if(m_levelGen != NULL) + if(m_levelGen != nullptr) { LoadLevelGen(m_levelGen); } @@ -445,7 +445,7 @@ HRESULT CScene_LoadGameSettings::LaunchGame(void) } else { - if(m_levelGen != NULL) + if(m_levelGen != nullptr) { LoadLevelGen(m_levelGen); } @@ -469,7 +469,7 @@ HRESULT CScene_LoadGameSettings::LaunchGame(void) int CScene_LoadGameSettings::CheckResetNetherReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -503,7 +503,7 @@ HRESULT CScene_LoadGameSettings::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyP // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack==nullptr) { // They've selected a texture pack they don't have yet // upsell @@ -572,7 +572,7 @@ HRESULT CScene_LoadGameSettings::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyP // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack==nullptr) { // DLC corrupt, so use the default textures m_MoreOptionsParams.dwTexturePack=0; @@ -600,7 +600,7 @@ HRESULT CScene_LoadGameSettings::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyP DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_pDLCPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -703,11 +703,11 @@ HRESULT CScene_LoadGameSettings::OnFontRendererChange() int CScene_LoadGameSettings::ConfirmLoadReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { - if(pClass->m_levelGen != NULL) + if(pClass->m_levelGen != nullptr) { pClass->LoadLevelGen(pClass->m_levelGen); } @@ -784,14 +784,14 @@ HRESULT CScene_LoadGameSettings::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandle if(m_iConfigA[i]!=-1) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; app.GetTPD(m_iConfigA[i],&pbData,&dwBytes); ZeroMemory(&ListInfo,sizeof(CXuiCtrl4JList::LIST_ITEM_INFO)); if(dwBytes > 0 && pbData) { DWORD dwImageBytes=0; - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; app.GetFileFromTPD(eTPDFileType_Icon,pbData,dwBytes,&pbImageData,&dwImageBytes ); ListInfo.fEnabled = TRUE; @@ -840,7 +840,7 @@ int CScene_LoadGameSettings::Progress(void *pParam,float fProgress) int CScene_LoadGameSettings::LoadSaveDataReturned(void *pParam,bool bContinue) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); if(bContinue==true) { @@ -868,7 +868,7 @@ int CScene_LoadGameSettings::LoadSaveDataReturned(void *pParam,bool bContinue) pClass->m_bIgnoreInput=false; UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -903,7 +903,7 @@ int CScene_LoadGameSettings::LoadSaveDataReturned(void *pParam,bool bContinue) int CScene_LoadGameSettings::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -921,7 +921,7 @@ int CScene_LoadGameSettings::DeleteSaveDialogReturned(void *pParam,int iPad,C4JS int CScene_LoadGameSettings::DeleteSaveDataReturned(void *pParam,bool bSuccess) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); app.SetCorruptSaveDeleted(true); app.NavigateBack(pClass->m_iPad); @@ -951,7 +951,7 @@ void CScene_LoadGameSettings::StartGameFromSave(CScene_LoadGameSettings* pClass, NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->texturePackId = pClass->m_MoreOptionsParams.dwTexturePack; Minecraft *pMinecraft = Minecraft::GetInstance(); @@ -983,7 +983,7 @@ void CScene_LoadGameSettings::StartGameFromSave(CScene_LoadGameSettings* pClass, LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave timer app.SetAutosaveTimerTime(); @@ -1000,7 +1000,7 @@ void CScene_LoadGameSettings::StartGameFromSave(CScene_LoadGameSettings* pClass, int CScene_LoadGameSettings::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - CScene_LoadGameSettings* pClass = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pClass = static_cast(pParam); if(bContinue==true) { @@ -1036,7 +1036,7 @@ int CScene_LoadGameSettings::StartGame_SignInReturned(void *pParam,bool bContinu //pClass->m_bAbortSearch=false; UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -1045,7 +1045,7 @@ int CScene_LoadGameSettings::StartGame_SignInReturned(void *pParam,bool bContinu //pClass->m_bAbortSearch=false; UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } } else @@ -1082,7 +1082,7 @@ HRESULT CScene_LoadGameSettings::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINo if(hObjSource==m_SliderDifficulty.GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Difficulty,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pNotifyValueChanged->nValue])); + swprintf( static_cast(TempString), 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pNotifyValueChanged->nValue])); m_SliderDifficulty.SetText(TempString); } return S_OK; @@ -1150,7 +1150,7 @@ HRESULT CScene_LoadGameSettings::OnTransitionEnd( XUIMessageTransition *pTransit int CScene_LoadGameSettings::UnlockTexturePackReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_LoadGameSettings* pScene = (CScene_LoadGameSettings*)pParam; + CScene_LoadGameSettings* pScene = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -1159,7 +1159,7 @@ int CScene_LoadGameSettings::UnlockTexturePackReturned(void *pParam,int iPad,C4J ULONGLONG ullIndexA[1]; DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(pScene->m_pDLCPack->getPurchaseOfferId()); - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullIndexA[0]=pDLCInfo->ullOfferID_Full; } @@ -1168,7 +1168,7 @@ int CScene_LoadGameSettings::UnlockTexturePackReturned(void *pParam,int iPad,C4J ullIndexA[0]=pScene->m_pDLCPack->getPurchaseOfferId(); } - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } @@ -1238,11 +1238,11 @@ void CScene_LoadGameSettings::UpdateTexturePackDescription(int index) int iTexPackId=m_pTexturePacksList->GetData(index).iData; TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackById(iTexPackId); - if(tp==NULL) + if(tp==nullptr) { // this is probably a texture pack icon added from TMS DWORD dwBytes=0,dwFileBytes=0; - PBYTE pbData=NULL,pbFileData=NULL; + PBYTE pbData=nullptr,pbFileData=nullptr; CXuiCtrl4JList::LIST_ITEM_INFO ListItem; // get the current index of the list, and then get the data @@ -1272,7 +1272,7 @@ void CScene_LoadGameSettings::UpdateTexturePackDescription(int index) } else { - m_texturePackComparison->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); } } else @@ -1290,7 +1290,7 @@ void CScene_LoadGameSettings::UpdateTexturePackDescription(int index) } else { - m_texturePackIcon->UseBrush(NULL); + m_texturePackIcon->UseBrush(nullptr); } pbImageData = tp->getPackComparison(dwImageBytes); @@ -1302,7 +1302,7 @@ void CScene_LoadGameSettings::UpdateTexturePackDescription(int index) } else { - m_texturePackComparison->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); } } } @@ -1311,8 +1311,8 @@ void CScene_LoadGameSettings::ClearTexturePackDescription() { m_texturePackTitle.SetText(L" "); m_texturePackDescription.SetText(L" "); - m_texturePackComparison->UseBrush(NULL); - m_texturePackIcon->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); + m_texturePackIcon->UseBrush(nullptr); } void CScene_LoadGameSettings::UpdateCurrentTexturePack() @@ -1322,7 +1322,7 @@ void CScene_LoadGameSettings::UpdateCurrentTexturePack() TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackById(iTexPackId); // if the texture pack is null, you don't have it yet - if(tp==NULL) + if(tp==nullptr) { // Upsell @@ -1416,7 +1416,7 @@ void CScene_LoadGameSettings::LoadLevelGen(LevelGenerationOptions *levelGen) m_bIgnoreInput=false; UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); return; } } @@ -1438,7 +1438,7 @@ void CScene_LoadGameSettings::LoadLevelGen(LevelGenerationOptions *levelGen) NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->levelGen = levelGen; if(levelGen->requiresTexturePack()) @@ -1482,7 +1482,7 @@ void CScene_LoadGameSettings::LoadLevelGen(LevelGenerationOptions *levelGen) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave timer app.SetAutosaveTimerTime(); @@ -1540,7 +1540,7 @@ HRESULT CScene_LoadGameSettings::OnCustomMessage_DLCMountingComplete() ListInfo.fEnabled = TRUE; hr=XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&ListInfo.hXuiBrush); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tp; + DLCTexturePack *pDLCTexPack=static_cast(tp); if(pDLCTexPack) { int id=pDLCTexPack->getDLCParentPackId(); @@ -1566,7 +1566,7 @@ HRESULT CScene_LoadGameSettings::OnCustomMessage_DLCMountingComplete() m_iTexturePacksNotInstalled=0; // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -1599,7 +1599,7 @@ HRESULT CScene_LoadGameSettings::OnCustomMessage_DLCMountingComplete() // add a TMS request for them app.DebugPrintf("+++ Adding TMSPP request for texture pack data\n"); app.AddTMSPPFileTypeRequest(e_DLC_TexturePackData); - if(m_iConfigA!=NULL) + if(m_iConfigA!=nullptr) { delete m_iConfigA; } @@ -1635,7 +1635,7 @@ HRESULT CScene_LoadGameSettings::OnCustomMessage_DLCMountingComplete() int CScene_LoadGameSettings::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_LoadGameSettings *pClass = (CScene_LoadGameSettings *)pParam; + CScene_LoadGameSettings *pClass = static_cast(pParam); #ifdef _XBOX pClass->m_currentTexturePackIndex = pClass->m_pTexturePacksList->GetCurSel(); // Exit with or without saving @@ -1655,7 +1655,7 @@ int CScene_LoadGameSettings::TexturePackDialogReturned(void *pParam,int iPad,C4J if( result==C4JStorage::EMessage_ResultAccept ) // Full version { ullIndexA[0]=ullOfferID_Full; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } else // trial version @@ -1665,7 +1665,7 @@ int CScene_LoadGameSettings::TexturePackDialogReturned(void *pParam,int iPad,C4J if(pDLCInfo->ullOfferID_Trial!=0LL) { ullIndexA[0]=pDLCInfo->ullOfferID_Trial; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } } diff --git a/Minecraft.Client/Common/XUI/XUI_MainMenu.cpp b/Minecraft.Client/Common/XUI/XUI_MainMenu.cpp index 7b9c1a56e..4126c5591 100644 --- a/Minecraft.Client/Common/XUI/XUI_MainMenu.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MainMenu.cpp @@ -72,7 +72,7 @@ HRESULT CScene_Main::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) WCHAR szResourceLocator[ LOCATOR_SIZE ]; // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/splashes.txt"); BYTE *splashesData; @@ -119,7 +119,7 @@ HRESULT CScene_Main::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) m_bIgnorePress=false; // 4J Stu - Clear out any loaded game rules - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // Fix for #45154 - Frontend: DLC: Content can only be downloaded from the frontend if you have not joined/exited multiplayer XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); @@ -325,7 +325,7 @@ HRESULT CScene_Main::OnTransitionStart( XUIMessageTransition *pTransition, BOOL& if(pTransition->dwTransType == XUI_TRANSITION_TO || pTransition->dwTransType == XUI_TRANSITION_BACKTO) { // 4J-PB - remove the "hobo humping" message legal (Sony) say we can't have - pretty sure Microsoft would say the same if they noticed it. - int splashIndex = eSplashRandomStart + 1 + random->nextInt( (int)m_splashes.size() - (eSplashRandomStart + 1) ); + int splashIndex = eSplashRandomStart + 1 + random->nextInt( static_cast(m_splashes.size()) - (eSplashRandomStart + 1) ); // Override splash text on certain dates SYSTEMTIME LocalSysTime; @@ -359,7 +359,7 @@ HRESULT CScene_Main::OnTransitionStart( XUIMessageTransition *pTransition, BOOL& HRESULT hr=S_OK; float fWidth,fHeight; - HXUIOBJ visual=NULL; + HXUIOBJ visual=nullptr; HXUIOBJ pulser, subtitle, text; hr=XuiControlGetVisual(m_Subtitle.m_hObj,&visual); hr=XuiElementGetChildById(visual,L"Pulser",&pulser); @@ -436,7 +436,7 @@ HRESULT CScene_Main::OnControlNavigate(XUIMessageControlNavigate *pControlNaviga // added so we can skip greyed out items for Minecon pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -457,7 +457,7 @@ HRESULT CScene_Main::OnKeyDown(XUIMessageInput *pInputData, BOOL& bHandled) int CScene_Main::SignInReturned(void *pParam,bool bContinue) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(bContinue==true) { @@ -470,7 +470,7 @@ int CScene_Main::SignInReturned(void *pParam,bool bContinue) int CScene_Main::DeviceSelectReturned(void *pParam,bool bContinue) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); //HRESULT hr; if(bContinue==true) @@ -506,7 +506,7 @@ int CScene_Main::DeviceSelectReturned(void *pParam,bool bContinue) int CScene_Main::CreateLoad_OfflineProfileReturned(void *pParam,bool bContinue, int iPad) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(bContinue==true) { @@ -555,7 +555,7 @@ int CScene_Main::CreateLoad_OfflineProfileReturned(void *pParam,bool bContinue, int CScene_Main::CreateLoad_SignInReturned(void *pParam,bool bContinue, int iPad) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(bContinue==true) { @@ -662,7 +662,7 @@ int CScene_Main::CreateLoad_SignInReturned(void *pParam,bool bContinue, int iPad int CScene_Main::MustSignInReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -787,7 +787,7 @@ int CScene_Main::Achievements_SignInReturned(void *pParam,bool bContinue,int iPa } int CScene_Main::HelpAndOptions_SignInReturned(void *pParam,bool bContinue,int iPad) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(bContinue==true) { @@ -834,7 +834,7 @@ int CScene_Main::HelpAndOptions_SignInReturned(void *pParam,bool bContinue,int i int CScene_Main::UnlockFullGame_SignInReturned(void *pParam,bool bContinue,int iPad) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); if(bContinue==true) { @@ -907,7 +907,7 @@ void CScene_Main::LoadTrial(void) NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->settings = app.GetGameHostOption( eGameHostOption_Tutorial ); vector *generators = app.getLevelGenerators(); @@ -915,7 +915,7 @@ void CScene_Main::LoadTrial(void) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1228,7 +1228,7 @@ void CScene_Main::RunUnlockOrDLC(int iPad) int CScene_Main::TMSReadFileListReturned(void *pParam,int iPad,C4JStorage::PTMSPP_FILE_LIST pTmsFileList) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); // push the file details in to a unordered map if they are not already in there // for(int i=0;iiCount;i++) @@ -1240,7 +1240,7 @@ int CScene_Main::TMSReadFileListReturned(void *pParam,int iPad,C4JStorage::PTMSP int CScene_Main::TMSFileWriteReturned(void *pParam,int iPad,int iResult) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); // push the file details in to a unordered map if they are not already in there // for(int i=0;iiCount;i++) @@ -1252,7 +1252,7 @@ int CScene_Main::TMSFileWriteReturned(void *pParam,int iPad,int iResult) int CScene_Main::TMSFileReadReturned(void *pParam,int iPad,C4JStorage::PTMSPP_FILEDATA pData) { - CScene_Main* pClass = (CScene_Main*)pParam; + CScene_Main* pClass = static_cast(pParam); // push the file details in to a unordered map if they are not already in there // for(int i=0;iiCount;i++) diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameCreate.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameCreate.cpp index b949aafab..b73f93051 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameCreate.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameCreate.cpp @@ -38,7 +38,7 @@ HRESULT CScene_MultiGameCreate::OnInit( XUIMessageInit* pInitData, BOOL& bHandle { m_bSetup = false; m_texturePackDescDisplayed = false; - m_iConfigA=NULL; + m_iConfigA=nullptr; WCHAR TempString[256]; MapChildControls(); @@ -52,7 +52,7 @@ HRESULT CScene_MultiGameCreate::OnInit( XUIMessageInit* pInitData, BOOL& bHandle XuiControlSetText(m_labelRandomSeed,app.GetString(IDS_CREATE_NEW_WORLD_RANDOM_SEED)); XuiControlSetText(m_pTexturePacksList->m_hObj,app.GetString(IDS_DLC_MENU_TEXTUREPACKS)); - CreateWorldMenuInitData *params = (CreateWorldMenuInitData *)pInitData->pvInitData; + CreateWorldMenuInitData *params = static_cast(pInitData->pvInitData); m_MoreOptionsParams.bGenerateOptions=TRUE; m_MoreOptionsParams.bStructures=TRUE; @@ -139,7 +139,7 @@ HRESULT CScene_MultiGameCreate::OnInit( XUIMessageInit* pInitData, BOOL& bHandle wstring wWorldName = m_EditWorldName.GetText(); // set the caret to the end of the default text - m_EditWorldName.SetCaretPosition((int)wWorldName.length()); + m_EditWorldName.SetCaretPosition(static_cast(wWorldName.length())); // In the dashboard, there's room for about 30 W characters on two lines before they go over the top of things m_EditWorldName.SetTextLimit(25); @@ -189,8 +189,8 @@ HRESULT CScene_MultiGameCreate::OnInit( XUIMessageInit* pInitData, BOOL& bHandle if(dwImageBytes > 0 && pbImageData) { - ListInfo.fEnabled = TRUE; - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tp; + ListInfo.fEnabled = true; + DLCTexturePack *pDLCTexPack=static_cast(tp); if(pDLCTexPack) { int id=pDLCTexPack->getDLCParentPackId(); @@ -222,7 +222,7 @@ HRESULT CScene_MultiGameCreate::OnInit( XUIMessageInit* pInitData, BOOL& bHandle // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -322,7 +322,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPr // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack==nullptr) { // They've selected a texture pack they don't have yet // upsell @@ -391,7 +391,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPr // texture pack hasn't been set yet, so check what it will be TexturePack *pTexturePack = pMinecraft->skins->getTexturePackById(m_MoreOptionsParams.dwTexturePack); - if(pTexturePack==NULL) + if(pTexturePack== nullptr) { // corrupt DLC so set it to the default textures m_MoreOptionsParams.dwTexturePack=0; @@ -419,7 +419,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPr DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_pDLCPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -485,7 +485,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPr SetShow( TRUE ); UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -522,7 +522,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPr int CScene_MultiGameCreate::UnlockTexturePackReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameCreate* pScene = (CScene_MultiGameCreate*)pParam; + CScene_MultiGameCreate* pScene = static_cast(pParam); #ifdef _XBOX if(result==C4JStorage::EMessage_ResultAccept) { @@ -531,7 +531,7 @@ int CScene_MultiGameCreate::UnlockTexturePackReturned(void *pParam,int iPad,C4JS ULONGLONG ullIndexA[1]; DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(pScene->m_pDLCPack->getPurchaseOfferId()); - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullIndexA[0]=pDLCInfo->ullOfferID_Full; } @@ -540,7 +540,7 @@ int CScene_MultiGameCreate::UnlockTexturePackReturned(void *pParam,int iPad,C4JS ullIndexA[0]=pScene->m_pDLCPack->getPurchaseOfferId(); } - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } @@ -558,7 +558,7 @@ int CScene_MultiGameCreate::UnlockTexturePackReturned(void *pParam,int iPad,C4JS int CScene_MultiGameCreate::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameCreate* pScene = (CScene_MultiGameCreate*)pParam; + CScene_MultiGameCreate* pScene = static_cast(pParam); pScene->m_bIgnoreInput = false; pScene->SetShow( TRUE ); bool isClientSide = ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()) && pScene->m_MoreOptionsParams.bOnlineGame; @@ -588,7 +588,7 @@ int CScene_MultiGameCreate::WarningTrialTexturePackReturned(void *pParam,int iPa { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -634,7 +634,7 @@ HRESULT CScene_MultiGameCreate::OnNotifyValueChanged (HXUIOBJ hObjSource, XUINot else if(hObjSource==m_SliderDifficulty.GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Difficulty,pValueChangedData->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pValueChangedData->nValue])); + swprintf( static_cast(TempString), 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pValueChangedData->nValue])); m_SliderDifficulty.SetText(TempString); } @@ -645,7 +645,7 @@ HRESULT CScene_MultiGameCreate::OnControlNavigate(XUIMessageControlNavigate *pCo { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest==NULL) + if(pControlNavigateData->hObjDest==nullptr) { pControlNavigateData->hObjDest=pControlNavigateData->hObjSource; } @@ -706,7 +706,7 @@ HRESULT CScene_MultiGameCreate::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled if(m_iConfigA[i]!=-1) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; //app.DebugPrintf("Retrieving iConfig %d from TPD\n",m_iConfigA[i]); app.GetTPD(m_iConfigA[i],&pbData,&dwBytes); @@ -715,7 +715,7 @@ HRESULT CScene_MultiGameCreate::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled if(dwBytes > 0 && pbData) { DWORD dwImageBytes=0; - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; app.GetFileFromTPD(eTPDFileType_Icon,pbData,dwBytes,&pbImageData,&dwImageBytes ); ListInfo.fEnabled = TRUE; @@ -754,7 +754,7 @@ HRESULT CScene_MultiGameCreate::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled int CScene_MultiGameCreate::ConfirmCreateReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameCreate* pClass = (CScene_MultiGameCreate*)pParam; + CScene_MultiGameCreate* pClass = static_cast(pParam); if(result==C4JStorage::EMessage_ResultAccept) { @@ -787,7 +787,7 @@ int CScene_MultiGameCreate::ConfirmCreateReturned(void *pParam,int iPad,C4JStora pClass->SetShow( TRUE ); UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -808,7 +808,7 @@ int CScene_MultiGameCreate::ConfirmCreateReturned(void *pParam,int iPad,C4JStora int CScene_MultiGameCreate::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - CScene_MultiGameCreate* pClass = (CScene_MultiGameCreate*)pParam; + CScene_MultiGameCreate* pClass = static_cast(pParam); if(bContinue==true) { @@ -844,7 +844,7 @@ int CScene_MultiGameCreate::StartGame_SignInReturned(void *pParam,bool bContinue pClass->SetShow( TRUE ); UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_FAILED_TO_CREATE_GAME_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -852,7 +852,7 @@ int CScene_MultiGameCreate::StartGame_SignInReturned(void *pParam,bool bContinue pClass->SetShow( TRUE ); UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } } else @@ -889,7 +889,7 @@ void CScene_MultiGameCreate::CreateGame(CScene_MultiGameCreate* pClass, DWORD dw // Make our next save default to the name of the level StorageManager.SetSaveTitle((wchar_t *)wWorldName.c_str()); - BOOL bHasSeed = (pClass->m_EditSeed.GetText() != NULL); + BOOL bHasSeed = (pClass->m_EditSeed.GetText() != nullptr); wstring wSeed; if(bHasSeed) @@ -909,7 +909,7 @@ void CScene_MultiGameCreate::CreateGame(CScene_MultiGameCreate* pClass, DWORD dw if (wSeed.length() != 0) { int64_t value = 0; - unsigned int len = (unsigned int)wSeed.length(); + const unsigned int len = static_cast(wSeed.length()); //Check if the input string contains a numerical value bool isNumber = true; @@ -946,7 +946,7 @@ void CScene_MultiGameCreate::CreateGame(CScene_MultiGameCreate* pClass, DWORD dw NetworkGameInitData *param = new NetworkGameInitData(); param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; param->texturePackId = pClass->m_MoreOptionsParams.dwTexturePack; Minecraft *pMinecraft = Minecraft::GetInstance(); @@ -979,7 +979,7 @@ void CScene_MultiGameCreate::CreateGame(CScene_MultiGameCreate* pClass, DWORD dw LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave time app.SetAutosaveTimerTime(); @@ -1095,12 +1095,12 @@ void CScene_MultiGameCreate::UpdateTexturePackDescription(int index) int iTexPackId=m_pTexturePacksList->GetData(index).iData; TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackById(iTexPackId); - if(tp==NULL) + if(tp==nullptr) { // this is probably a texture pack icon added from TMS DWORD dwBytes=0,dwFileBytes=0; - PBYTE pbData=NULL,pbFileData=NULL; + PBYTE pbData=nullptr,pbFileData=nullptr; CXuiCtrl4JList::LIST_ITEM_INFO ListItem; // get the current index of the list, and then get the data @@ -1130,7 +1130,7 @@ void CScene_MultiGameCreate::UpdateTexturePackDescription(int index) } else { - m_texturePackComparison->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); } } else @@ -1156,7 +1156,7 @@ void CScene_MultiGameCreate::UpdateTexturePackDescription(int index) } else { - m_texturePackComparison->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); } } } @@ -1168,7 +1168,7 @@ void CScene_MultiGameCreate::UpdateCurrentTexturePack() TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackById(iTexPackId); // if the texture pack is null, you don't have it yet - if(tp==NULL) + if(tp==nullptr) { // Upsell @@ -1217,7 +1217,7 @@ void CScene_MultiGameCreate::UpdateCurrentTexturePack() int CScene_MultiGameCreate::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameCreate *pClass = (CScene_MultiGameCreate *)pParam; + CScene_MultiGameCreate *pClass = static_cast(pParam); pClass->m_currentTexturePackIndex = pClass->m_pTexturePacksList->GetCurSel(); // Exit with or without saving // Decline means install full version of the texture pack in this dialog @@ -1236,7 +1236,7 @@ int CScene_MultiGameCreate::TexturePackDialogReturned(void *pParam,int iPad,C4JS if( result==C4JStorage::EMessage_ResultAccept ) // Full version { ullIndexA[0]=ullOfferID_Full; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } else // trial version @@ -1246,7 +1246,7 @@ int CScene_MultiGameCreate::TexturePackDialogReturned(void *pParam,int iPad,C4JS if(pDLCInfo->ullOfferID_Trial!=0LL) { ullIndexA[0]=pDLCInfo->ullOfferID_Trial; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } } @@ -1295,7 +1295,7 @@ HRESULT CScene_MultiGameCreate::OnCustomMessage_DLCMountingComplete() ListInfo.fEnabled = TRUE; hr=XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&ListInfo.hXuiBrush); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tp; + DLCTexturePack *pDLCTexPack=static_cast(tp); if(pDLCTexPack) { int id=pDLCTexPack->getDLCParentPackId(); @@ -1319,7 +1319,7 @@ HRESULT CScene_MultiGameCreate::OnCustomMessage_DLCMountingComplete() // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this // REMOVE UNTIL WORKING - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -1352,7 +1352,7 @@ HRESULT CScene_MultiGameCreate::OnCustomMessage_DLCMountingComplete() // add a TMS request for them app.DebugPrintf("+++ Adding TMSPP request for texture pack data\n"); app.AddTMSPPFileTypeRequest(e_DLC_TexturePackData); - if(m_iConfigA!=NULL) + if(m_iConfigA!=nullptr) { delete m_iConfigA; } @@ -1392,6 +1392,6 @@ void CScene_MultiGameCreate::ClearTexturePackDescription() { m_texturePackTitle.SetText(L" "); m_texturePackDescription.SetText(L" "); - m_texturePackComparison->UseBrush(NULL); - m_texturePackIcon->UseBrush(NULL); + m_texturePackComparison->UseBrush(nullptr); + m_texturePackIcon->UseBrush(nullptr); } \ No newline at end of file diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameInfo.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameInfo.cpp index bbfa243b2..c1dba2829 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameInfo.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameInfo.cpp @@ -31,7 +31,7 @@ HRESULT CScene_MultiGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled XuiControlSetText(m_labelTNTOn,app.GetString(IDS_LABEL_TNT)); XuiControlSetText(m_labelFireOn,app.GetString(IDS_LABEL_FIRE_SPREADS)); - JoinMenuInitData *initData = (JoinMenuInitData *)pInitData->pvInitData; + JoinMenuInitData *initData = static_cast(pInitData->pvInitData); m_selectedSession = initData->selectedSession; m_iPad = initData->iPad; // 4J-PB - don't delete this - it's part of the joinload structure @@ -39,7 +39,7 @@ HRESULT CScene_MultiGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { - if( m_selectedSession->data.players[i] != NULL ) + if( m_selectedSession->data.players[i] != nullptr ) { playersList.InsertItems(i,1); #ifndef _CONTENT_PACKAGE @@ -55,7 +55,7 @@ HRESULT CScene_MultiGameInfo::OnInit( XUIMessageInit* pInitData, BOOL& bHandled } else { - // Leave the loop when we hit the first NULL player + // Leave the loop when we hit the first nullptr player break; } } @@ -185,7 +185,7 @@ HRESULT CScene_MultiGameInfo::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHan rfHandled = TRUE; break; case VK_PAD_Y: - if(m_selectedSession != NULL && playersList.TreeHasFocus() && playersList.GetItemCount() > 0) + if(m_selectedSession != nullptr && playersList.TreeHasFocus() && playersList.GetItemCount() > 0) { PlayerUID xuid = m_selectedSession->data.players[playersList.GetCurSel()]; if( xuid != INVALID_XUID ) @@ -237,7 +237,7 @@ HRESULT CScene_MultiGameInfo::OnNotifyKillFocus(HXUIOBJ hObjSource, XUINotifyFoc int CScene_MultiGameInfo::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - CScene_MultiGameInfo* pClass = (CScene_MultiGameInfo*)pParam; + CScene_MultiGameInfo* pClass = static_cast(pParam); if(bContinue==true) { @@ -302,7 +302,7 @@ void CScene_MultiGameInfo::JoinGame(CScene_MultiGameInfo* pClass) int messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL; if(dwSignedInUsers > 1) messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL; - StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, messageText, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, messageText, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else if(noPrivileges) @@ -311,7 +311,7 @@ void CScene_MultiGameInfo::JoinGame(CScene_MultiGameInfo* pClass) pClass->m_bIgnoreInput=false; UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); } else { @@ -338,7 +338,7 @@ void CScene_MultiGameInfo::JoinGame(CScene_MultiGameInfo* pClass) { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + StorageManager.RequestMessageBox( IDS_CONNECTION_FAILED, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); exitReasonStringId = -1; app.NavigateToHomeMenu(); @@ -361,7 +361,7 @@ HRESULT CScene_MultiGameInfo::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled ) int selectedIndex = 0; for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { - if( m_selectedSession->data.players[i] != NULL ) + if( m_selectedSession->data.players[i] != nullptr ) { if(m_selectedSession->data.players[i] == selectedPlayerXUID) selectedIndex = i; playersList.InsertItems(i,1); @@ -378,7 +378,7 @@ HRESULT CScene_MultiGameInfo::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled ) } else { - // Leave the loop when we hit the first NULL player + // Leave the loop when we hit the first nullptr player break; } } diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp index 5894519d8..fab4a4fd0 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp @@ -36,12 +36,12 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); m_bReady=false; MapChildControls(); m_iTexturePacksNotInstalled=0; - m_iConfigA=NULL; + m_iConfigA=nullptr; XuiControlSetText(m_LabelNoGames,app.GetString(IDS_NO_GAMES_FOUND)); XuiControlSetText(m_GamesList,app.GetString(IDS_JOIN_GAME)); @@ -51,7 +51,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); m_DefaultMinecraftIconSize = 0; @@ -95,10 +95,10 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand VOID *pObj; XuiObjectFromHandle( m_SavesList, &pObj ); - m_pSavesList = (CXuiCtrl4JList *)pObj; + m_pSavesList = static_cast(pObj); XuiObjectFromHandle( m_GamesList, &pObj ); - m_pGamesList = (CXuiCtrl4JList *)pObj; + m_pGamesList = static_cast(pObj); // 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)==true) @@ -185,7 +185,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand // 4J-PB - there may be texture packs we don't have, so use the info from TMS for this - DLC_INFO *pDLCInfo=NULL; + DLC_INFO *pDLCInfo=nullptr; // first pass - look to see if there are any that are not in the list bool bTexturePackAlreadyListed; @@ -326,7 +326,7 @@ HRESULT CScene_MultiGameJoinLoad::GetSaveInfo( ) if( savesDir.exists() ) { m_saves = savesDir.listFiles(); - uiSaveC = (unsigned int)m_saves->size(); + uiSaveC = static_cast(m_saves->size()); } // add the New Game and Tutorial after the saves list is retrieved, if there are any saves @@ -384,7 +384,7 @@ HRESULT CScene_MultiGameJoinLoad::GetSaveInfo( ) HRESULT CScene_MultiGameJoinLoad::OnDestroy() { - g_NetworkManager.SetSessionsUpdatedCallback( NULL, NULL ); + g_NetworkManager.SetSessionsUpdatedCallback( nullptr, nullptr ); for (auto& it : currentSessions ) { @@ -415,7 +415,7 @@ HRESULT CScene_MultiGameJoinLoad::OnDestroy() int CScene_MultiGameJoinLoad::DeviceRemovedDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) @@ -543,7 +543,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify CreateWorldMenuInitData *params = new CreateWorldMenuInitData(); params->iPad = m_iPad; - app.NavigateToScene(pNotifyPressData->UserIndex,eUIScene_CreateWorldMenu,(void *)params); + app.NavigateToScene(pNotifyPressData->UserIndex,eUIScene_CreateWorldMenu,static_cast(params)); } else if(info.iData >= 0) { @@ -594,7 +594,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify // need to get the iIndex from the list item, since the position in the list doesn't correspond to the GetSaveGameInfo list because of sorting params->iSaveGameInfoIndex=m_pSavesList->GetData(iIndex).iIndex-m_iDefaultButtonsC; //params->pbSaveRenamed=&m_bSaveRenamed; - params->levelGen = NULL; + params->levelGen = nullptr; // kill the texture pack timer XuiKillTimer(m_hObj,CHECKFORAVAILABLETEXTUREPACKS_TIMER_ID); @@ -1050,7 +1050,7 @@ bool CScene_MultiGameJoinLoad::DoesSavesListHaveFocus() { HXUIOBJ hParentObj,hObj=TreeGetFocus(); - if(hObj!=NULL) + if(hObj!=nullptr) { // get the parent and see if it's the saves list XuiElementGetParent(hObj,&hParentObj); @@ -1070,7 +1070,7 @@ bool CScene_MultiGameJoinLoad::DoesMashUpWorldHaveFocus() { HXUIOBJ hParentObj,hObj=TreeGetFocus(); - if(hObj!=NULL) + if(hObj!=nullptr) { // get the parent and see if it's the saves list XuiElementGetParent(hObj,&hParentObj); @@ -1097,7 +1097,7 @@ bool CScene_MultiGameJoinLoad::DoesGamesListHaveFocus() { HXUIOBJ hParentObj,hObj=TreeGetFocus(); - if(hObj!=NULL) + if(hObj!=nullptr) { // get the parent and see if it's the saves list XuiElementGetParent(hObj,&hParentObj); @@ -1111,9 +1111,9 @@ bool CScene_MultiGameJoinLoad::DoesGamesListHaveFocus() void CScene_MultiGameJoinLoad::UpdateGamesListCallback(LPVOID lpParam) { - if(lpParam != NULL) + if(lpParam != nullptr) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad *) lpParam; + CScene_MultiGameJoinLoad* pClass = static_cast(lpParam); // check this there's no save transfer in progress if(!pClass->m_bSaveTransferInProgress) { @@ -1133,7 +1133,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() } DWORD nIndex = -1; - FriendSessionInfo *pSelectedSession = NULL; + FriendSessionInfo *pSelectedSession = nullptr; if(m_pGamesList->TreeHasFocus() && m_pGamesList->GetItemCount() > 0) { nIndex = m_pGamesList->GetCurSel(); @@ -1141,8 +1141,8 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() } SessionID selectedSessionId; - if( pSelectedSession != NULL )selectedSessionId = pSelectedSession->sessionId; - pSelectedSession = NULL; + if( pSelectedSession != nullptr )selectedSessionId = pSelectedSession->sessionId; + pSelectedSession = nullptr; for (auto& it : currentSessions ) { @@ -1213,7 +1213,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() // Update the xui list displayed unsigned int xuiListSize = m_pGamesList->GetItemCount(); - unsigned int filteredListSize = (unsigned int)currentSessions.size(); + unsigned int filteredListSize = static_cast(currentSessions.size()); BOOL gamesListHasFocus = m_pGamesList->TreeHasFocus(); @@ -1269,12 +1269,12 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() HRESULT hr; DWORD dwImageBytes=0; - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; - if(tp==NULL) + if(tp==nullptr) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; app.GetTPD(sessionInfo->data.texturePackParentId,&pbData,&dwBytes); // is it in the tpd data ? @@ -1386,7 +1386,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear if(pSearchResult->dwOpenPublicSlots < m_localPlayers) continue; - FriendSessionInfo *sessionInfo = NULL; + FriendSessionInfo *sessionInfo = nullptr; bool foundSession = false; for( auto it = friendsSessions.begin(); it != friendsSessions.end(); ++it) { @@ -1481,8 +1481,8 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear XUIRect xuiRect; HXUIOBJ item = XuiListGetItemControl(m_GamesList,0); - HXUIOBJ hObj=NULL; - HXUIOBJ hTextPres=NULL; + HXUIOBJ hObj=nullptr; + HXUIOBJ hTextPres=nullptr; HRESULT hr=XuiControlGetVisual(item,&hObj); hr=XuiElementGetChildById(hObj,L"text_Label",&hTextPres); @@ -1491,7 +1491,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear { FriendSessionInfo *sessionInfo = currentSessions.at(i); - if(hTextPres != NULL ) + if(hTextPres != nullptr ) { hr=XuiTextPresenterMeasureText(hTextPres, sessionInfo->displayLabel, &xuiRect); @@ -1528,7 +1528,7 @@ void CScene_MultiGameJoinLoad::SearchForGameCallback(void *param, DWORD dwNumRes int CScene_MultiGameJoinLoad::DeviceSelectReturned(void *pParam,bool bContinue) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); //HRESULT hr; if(bContinue==true) @@ -1741,7 +1741,7 @@ HRESULT CScene_MultiGameJoinLoad::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandl if(m_iConfigA[i]!=-1) { DWORD dwBytes=0; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; //app.DebugPrintf("Retrieving iConfig %d from TPD\n",m_iConfigA[i]); app.GetTPD(m_iConfigA[i],&pbData,&dwBytes); @@ -1814,7 +1814,7 @@ int CScene_MultiGameJoinLoad::LoadSaveDataReturned(void *pParam,bool bContinue) int CScene_MultiGameJoinLoad::StartGame_SignInReturned(void *pParam,bool bContinue, int iPad) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); if(bContinue==true) { @@ -1852,7 +1852,7 @@ void CScene_MultiGameJoinLoad::StartGameFromSave(CScene_MultiGameJoinLoad* pClas LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = NULL; + loadingParams->lpParam = nullptr; UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1866,7 +1866,7 @@ void CScene_MultiGameJoinLoad::StartGameFromSave(CScene_MultiGameJoinLoad* pClas int CScene_MultiGameJoinLoad::DeleteSaveDataReturned(void *pParam,bool bSuccess) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); if(bSuccess==true) { @@ -1909,7 +1909,7 @@ void CScene_MultiGameJoinLoad::LoadLevelGen(LevelGenerationOptions *levelGen) NetworkGameInitData *param = new NetworkGameInitData(); param->seed = 0; - param->saveData = NULL; + param->saveData = nullptr; param->settings = app.GetGameHostOption( eGameHostOption_Tutorial ); param->levelGen = levelGen; @@ -1924,7 +1924,7 @@ void CScene_MultiGameJoinLoad::LoadLevelGen(LevelGenerationOptions *levelGen) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1974,7 +1974,7 @@ void CScene_MultiGameJoinLoad::LoadSaveFromDisk(File *saveFile) LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -1988,7 +1988,7 @@ void CScene_MultiGameJoinLoad::LoadSaveFromDisk(File *saveFile) int CScene_MultiGameJoinLoad::DeleteSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultDecline) { @@ -2013,7 +2013,7 @@ int CScene_MultiGameJoinLoad::DeleteSaveDialogReturned(void *pParam,int iPad,C4J int CScene_MultiGameJoinLoad::SaveTransferDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); // results switched for this dialog if(result==C4JStorage::EMessage_ResultAccept) { @@ -2039,7 +2039,7 @@ int CScene_MultiGameJoinLoad::SaveTransferDialogReturned(void *pParam,int iPad,C int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter ) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad *) lpParameter; + CScene_MultiGameJoinLoad* pClass = static_cast(lpParameter); Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->progressRenderer->progressStart(IDS_SAVE_TRANSFER_TITLE); @@ -2083,7 +2083,7 @@ int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter { // set the save icon - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; DWORD dwImageBytes=0; XCONTENT_DATA XContentData; int iIndex=pClass->m_pSavesList->GetData(pClass->m_pSavesList->GetCurSel()).iIndex-pClass->m_iDefaultButtonsC; @@ -2092,14 +2092,14 @@ int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter // 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) + if(pbImageData==nullptr) { - DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,NULL,&dwImageBytes,NULL); + DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,nullptr,&dwImageBytes,nullptr); if(dwResult==ERROR_SUCCESS) { pClass->m_pbSaveTransferData = new BYTE[dwImageBytes]; pbImageData = pClass->m_pbSaveTransferData; // Copy pointer so that we can use the same name as the library owned one, but m_pbSaveTransferData will get deleted when done - XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,pbImageData,&dwImageBytes,NULL); + XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,pbImageData,&dwImageBytes,nullptr); } } @@ -2159,7 +2159,7 @@ void CScene_MultiGameJoinLoad::DeleteFile(CScene_MultiGameJoinLoad *pClass, char C4JStorage::TMS_FILETYPE_BINARY, &CScene_MultiGameJoinLoad::DeleteComplete, pClass, - NULL); + nullptr); if(result != C4JStorage::ETMSStatus_DeleteInProgress) { @@ -2178,7 +2178,7 @@ void CScene_MultiGameJoinLoad::UploadFile(CScene_MultiGameJoinLoad *pClass, char C4JStorage::TMS_FILETYPE_BINARY, C4JStorage::TMS_UGCTYPE_NONE, filename, - (CHAR *)data, + static_cast(data), size, &CScene_MultiGameJoinLoad::TransferComplete,pClass, 0, &CScene_MultiGameJoinLoad::Progress,pClass); @@ -2189,10 +2189,10 @@ void CScene_MultiGameJoinLoad::UploadFile(CScene_MultiGameJoinLoad *pClass, char File targetFileDir(L"GAME:\\FakeTMSPP"); if(!targetFileDir.exists()) targetFileDir.mkdir(); string path = string( wstringtofilename( targetFileDir.getPath() ) ).append("\\").append(filename); - HANDLE hSaveFile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, NULL); + HANDLE hSaveFile = CreateFile( path.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, nullptr); DWORD numberOfBytesWritten = 0; - WriteFile( hSaveFile,data,size,&numberOfBytesWritten,NULL); + WriteFile( hSaveFile,data,size,&numberOfBytesWritten,nullptr); assert(numberOfBytesWritten == size); CloseHandle(hSaveFile); @@ -2219,7 +2219,7 @@ bool CScene_MultiGameJoinLoad::WaitForTransferComplete( CScene_MultiGameJoinLoad } Sleep(50); // update the progress - pMinecraft->progressRenderer->progressStagePercentage((unsigned int)(pClass->m_fProgress*100.0f)); + pMinecraft->progressRenderer->progressStagePercentage(static_cast(pClass->m_fProgress * 100.0f)); } // was there a transfer error? @@ -2229,7 +2229,7 @@ bool CScene_MultiGameJoinLoad::WaitForTransferComplete( CScene_MultiGameJoinLoad int CScene_MultiGameJoinLoad::SaveOptionsDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); // results switched for this dialog // EMessage_ResultAccept means cancel @@ -2261,7 +2261,7 @@ int CScene_MultiGameJoinLoad::SaveOptionsDialogReturned(void *pParam,int iPad,C4 int CScene_MultiGameJoinLoad::LoadSaveDataReturned(void *pParam,bool bContinue) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); if(bContinue==true) { @@ -2310,7 +2310,7 @@ int CScene_MultiGameJoinLoad::LoadSaveDataReturned(void *pParam,bool bContinue) int CScene_MultiGameJoinLoad::Progress(void *pParam,float fProgress) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); app.DebugPrintf("Progress - %f\n",fProgress); pClass->m_fProgress=fProgress; @@ -2319,17 +2319,17 @@ int CScene_MultiGameJoinLoad::Progress(void *pParam,float fProgress) int CScene_MultiGameJoinLoad::TransferComplete(void *pParam,int iPad, int iResult) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); delete [] pClass->m_pbSaveTransferData; - pClass->m_pbSaveTransferData = NULL; + pClass->m_pbSaveTransferData = nullptr; if(iResult!=0) { // There was a transfer fail // Display a dialog UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox(IDS_SAVE_TRANSFER_TITLE, IDS_SAVE_TRANSFER_UPLOADFAILED, uiIDA, 1, ProfileManager.GetPrimaryPad(),NULL,NULL,app.GetStringTable()); + StorageManager.RequestMessageBox(IDS_SAVE_TRANSFER_TITLE, IDS_SAVE_TRANSFER_UPLOADFAILED, uiIDA, 1, ProfileManager.GetPrimaryPad(),nullptr,nullptr,app.GetStringTable()); pClass->m_bTransferFail=true; } else @@ -2343,14 +2343,14 @@ int CScene_MultiGameJoinLoad::TransferComplete(void *pParam,int iPad, int iResul int CScene_MultiGameJoinLoad::DeleteComplete(void *pParam,int iPad, int iResult) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); pClass->m_bTransferComplete=true; return 0; } int CScene_MultiGameJoinLoad::KeyboardReturned(void *pParam,bool bSet) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); HRESULT hr = S_OK; // if the user has left the name empty, treat this as backing out @@ -2386,12 +2386,12 @@ int CScene_MultiGameJoinLoad::KeyboardReturned(void *pParam,bool bSet) int CScene_MultiGameJoinLoad::LoadSaveDataForRenameReturned(void *pParam,bool bContinue) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); #ifdef _XBOX if(bContinue==true) { // set the save icon - PBYTE pbImageData=NULL; + PBYTE pbImageData=nullptr; DWORD dwImageBytes=0; HXUIBRUSH hXuiBrush; XCONTENT_DATA XContentData; @@ -2400,13 +2400,13 @@ int CScene_MultiGameJoinLoad::LoadSaveDataForRenameReturned(void *pParam,bool bC // 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) + if(pbImageData==nullptr) { - DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,NULL,&dwImageBytes,NULL); + DWORD dwResult=XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,nullptr,&dwImageBytes,nullptr); if(dwResult==ERROR_SUCCESS) { pbImageData = new BYTE[dwImageBytes]; - XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,pbImageData,&dwImageBytes,NULL); + XContentGetThumbnail(ProfileManager.GetPrimaryPad(),&XContentData,pbImageData,&dwImageBytes,nullptr); XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&hXuiBrush); } } @@ -2428,7 +2428,7 @@ int CScene_MultiGameJoinLoad::LoadSaveDataForRenameReturned(void *pParam,bool bC int CScene_MultiGameJoinLoad::CopySaveReturned(void *pParam,bool bResult) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; + CScene_MultiGameJoinLoad* pClass = static_cast(pParam); #ifdef _XBOX if(bResult) { @@ -2450,7 +2450,7 @@ int CScene_MultiGameJoinLoad::CopySaveReturned(void *pParam,bool bResult) int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_MultiGameJoinLoad *pClass = (CScene_MultiGameJoinLoad *)pParam; + CScene_MultiGameJoinLoad *pClass = static_cast(pParam); // Exit with or without saving // Decline means install full version of the texture pack in this dialog @@ -2466,7 +2466,7 @@ int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4 if( result==C4JStorage::EMessage_ResultAccept ) // Full version { ullIndexA[0]=ullOfferID_Full; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } else // trial version @@ -2476,7 +2476,7 @@ int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4 if(pDLCInfo->ullOfferID_Trial!=0LL) { ullIndexA[0]=pDLCInfo->ullOfferID_Trial; - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } } @@ -2510,7 +2510,7 @@ HRESULT CScene_MultiGameJoinLoad::OnCustomMessage_DLCMountingComplete() VOID *pObj; XuiObjectFromHandle( m_SavesList, &pObj ); - m_pSavesList = (CXuiCtrl4JList *)pObj; + m_pSavesList = static_cast(pObj); m_iChangingSaveGameInfoIndex = 0; @@ -2698,7 +2698,7 @@ bool CScene_MultiGameJoinLoad::GetSavesInfoCallback(LPVOID pParam,int iTotalSave // we could put in a damaged save icon here 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/MinecraftBrokenIcon.png"); @@ -2738,7 +2738,7 @@ int CScene_MultiGameJoinLoad::GetSavesInfoCallback(LPVOID lpParam,const bool) void CScene_MultiGameJoinLoad::CancelSaveUploadCallback(LPVOID lpParam) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad *) lpParam; + CScene_MultiGameJoinLoad* pClass = static_cast(lpParam); StorageManager.TMSPP_CancelWriteFileWithProgress(pClass->m_iPad); @@ -2750,12 +2750,12 @@ void CScene_MultiGameJoinLoad::CancelSaveUploadCallback(LPVOID lpParam) // pClass->m_eSaveUploadState = eSaveUpload_Idle; UINT uiIDA[1] = { IDS_CONFIRM_OK }; - ui.RequestMessageBox(IDS_XBONE_CANCEL_UPLOAD_TITLE, IDS_XBONE_CANCEL_UPLOAD_TEXT, uiIDA, 1, pClass->m_iPad, NULL, NULL, app.GetStringTable()); + ui.RequestMessageBox(IDS_XBONE_CANCEL_UPLOAD_TITLE, IDS_XBONE_CANCEL_UPLOAD_TEXT, uiIDA, 1, pClass->m_iPad, nullptr, nullptr, app.GetStringTable()); } void CScene_MultiGameJoinLoad::SaveUploadCompleteCallback(LPVOID lpParam) { - CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad *) lpParam; + CScene_MultiGameJoinLoad* pClass = static_cast(lpParam); pClass->m_bSaveTransferInProgress=false; // change back to the normal title group id diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameLaunchMoreOptions.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameLaunchMoreOptions.cpp index 086561110..63d28498f 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameLaunchMoreOptions.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameLaunchMoreOptions.cpp @@ -28,7 +28,7 @@ HRESULT CScene_MultiGameLaunchMoreOptions::OnInit( XUIMessageInit* pInitData, BO XuiControlSetText(m_CheckboxFlatWorld,app.GetString(IDS_SUPERFLAT_WORLD)); XuiControlSetText(m_CheckboxBonusChest,app.GetString(IDS_BONUS_CHEST)); - m_params = (LaunchMoreOptionsMenuInitData *)pInitData->pvInitData; + m_params = static_cast(pInitData->pvInitData); if(m_params->bGenerateOptions) { @@ -231,7 +231,7 @@ HRESULT CScene_MultiGameLaunchMoreOptions::OnControlNavigate(XUIMessageControlNa { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } diff --git a/Minecraft.Client/Common/XUI/XUI_NewUpdateMessage.cpp b/Minecraft.Client/Common/XUI/XUI_NewUpdateMessage.cpp index 49b524ffe..fa6da21e0 100644 --- a/Minecraft.Client/Common/XUI/XUI_NewUpdateMessage.cpp +++ b/Minecraft.Client/Common/XUI/XUI_NewUpdateMessage.cpp @@ -8,7 +8,7 @@ HRESULT CScene_NewUpdateMessage::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *) pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); m_bIsSD=!RenderManager.IsHiDef() && !RenderManager.IsWidescreen(); MapChildControls(); diff --git a/Minecraft.Client/Common/XUI/XUI_PauseMenu.cpp b/Minecraft.Client/Common/XUI/XUI_PauseMenu.cpp index 4de74d1f2..0879ba278 100644 --- a/Minecraft.Client/Common/XUI/XUI_PauseMenu.cpp +++ b/Minecraft.Client/Common/XUI/XUI_PauseMenu.cpp @@ -31,7 +31,7 @@ HRESULT UIScene_PauseMenu::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { m_bIgnoreInput=true; - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); bool bUserisClientSide = ProfileManager.IsSignedInLive(m_iPad); app.DebugPrintf("PAUSE PRESS PROCESSING - ipad = %d, UIScene_PauseMenu::OnInit\n",m_iPad); @@ -247,7 +247,7 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); m_pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); @@ -256,7 +256,7 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* // upsell ULONGLONG ullOfferID_Full; // get the dlc texture pack - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); app.GetDLCFullOfferIDForPackID(pDLCTexPack->getDLCParentPackId(),&ullOfferID_Full); @@ -317,9 +317,9 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* if(pNotifyPressData->UserIndex==ProfileManager.GetPrimaryPad()) { int playTime = -1; - if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != NULL ) + if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != nullptr ) { - playTime = (int)pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer()); } if(StorageManager.GetSaveDisabled()) @@ -357,9 +357,9 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* else { int playTime = -1; - if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != NULL ) + if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != nullptr ) { - playTime = (int)pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer()); } TelemetryManager->RecordLevelExit(pNotifyPressData->UserIndex, eSen_LevelExitStatus_Exited); @@ -375,9 +375,9 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* if(pNotifyPressData->UserIndex==ProfileManager.GetPrimaryPad()) { int playTime = -1; - if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != NULL ) + if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != nullptr ) { - playTime = (int)pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer()); } // adjust the trial time played @@ -392,9 +392,9 @@ HRESULT UIScene_PauseMenu::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* else { int playTime = -1; - if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != NULL ) + if( pMinecraft->localplayers[pNotifyPressData->UserIndex] != nullptr ) { - playTime = (int)pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer(); + playTime = static_cast(pMinecraft->localplayers[pNotifyPressData->UserIndex]->getSessionTimer()); } TelemetryManager->RecordLevelExit(pNotifyPressData->UserIndex, eSen_LevelExitStatus_Exited); @@ -596,7 +596,7 @@ HRESULT UIScene_PauseMenu::OnControlNavigate(XUIMessageControlNavigate *pControl { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -623,7 +623,7 @@ int UIScene_PauseMenu::DeviceSelectReturned(void *pParam,bool bContinue) return 0; } - UIScene_PauseMenu* pClass = (UIScene_PauseMenu*)pParam; + UIScene_PauseMenu* pClass = static_cast(pParam); bool bIsisPrimaryHost=g_NetworkManager.IsHost() && (ProfileManager.GetPrimaryPad()==pClass->m_iPad); bool bDisplayBanTip = !g_NetworkManager.IsLocalGame() && !bIsisPrimaryHost && !ProfileManager.IsGuest(pClass->m_iPad); bool bUserisClientSide = ProfileManager.IsSignedInLive(pClass->m_iPad); @@ -721,7 +721,7 @@ int UIScene_PauseMenu::DeviceRemovedDialogReturned(void *pParam,int iPad,C4JStor // Has someone pulled the ethernet cable and caused the pause menu to be closed before this callback returns? if(app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())) { - UIScene_PauseMenu* pClass = (UIScene_PauseMenu*)pParam; + UIScene_PauseMenu* pClass = static_cast(pParam); // use the device select returned function to wipe the saves list and change the tooltip pClass->DeviceSelectReturned(pClass,true); @@ -732,7 +732,7 @@ int UIScene_PauseMenu::DeviceRemovedDialogReturned(void *pParam,int iPad,C4JStor // Change device if(app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())) { - UIScene_PauseMenu* pClass = (UIScene_PauseMenu*)pParam; + UIScene_PauseMenu* pClass = static_cast(pParam); StorageManager.SetSaveDevice(&UIScene_PauseMenu::DeviceSelectReturned,pClass,true); } } @@ -770,7 +770,7 @@ void UIScene_PauseMenu::ShowScene(bool show) int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_PauseMenu* pScene = (UIScene_PauseMenu*)pParam; + UIScene_PauseMenu* pScene = static_cast(pParam); //pScene->m_bIgnoreInput = false; pScene->ShowScene( true ); @@ -782,7 +782,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); // get the dlc texture pack - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); // Need to get the parent packs id, since this may be one of many child packs with their own ids app.GetDLCFullOfferIDForPackID(pDLCTexPack->getDLCParentPackId(),&ullIndexA[0]); @@ -790,7 +790,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J // need to allow downloads here, or the player would need to quit the game to let the download of a texture pack happen. This might affect the network traffic, since the download could take all the bandwidth... XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); } } else @@ -804,7 +804,7 @@ int UIScene_PauseMenu::WarningTrialTexturePackReturned(void *pParam,int iPad,C4J int UIScene_PauseMenu::ExitGameSaveDialogReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - UIScene_PauseMenu *pClass = (UIScene_PauseMenu *)pParam; + UIScene_PauseMenu *pClass = static_cast(pParam); // Exit with or without saving // Decline means save in this dialog if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultThirdOption) @@ -815,7 +815,7 @@ int UIScene_PauseMenu::ExitGameSaveDialogReturned(void *pParam,int iPad,C4JStora if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) @@ -890,7 +890,7 @@ int UIScene_PauseMenu::ExitGameDeclineSaveReturned(void *pParam,int iPad,C4JStor // has someone disconnected the ethernet here, causing the pause menu to shut? if(ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())) { - IUIScene_PauseMenu* pClass = (IUIScene_PauseMenu*)pParam; + IUIScene_PauseMenu* pClass = static_cast(pParam); UINT uiIDA[3]; // you cancelled the save on exit after choosing exit and save? You go back to the Exit choices then. uiIDA[0]=IDS_CONFIRM_CANCEL; @@ -927,7 +927,7 @@ int UIScene_PauseMenu::ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage: // has someone disconnected the ethernet here, causing the pause menu to shut? if(ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())) { - UIScene_PauseMenu* pClass = (UIScene_PauseMenu*)pParam; + UIScene_PauseMenu* pClass = static_cast(pParam); UINT uiIDA[3]; // you cancelled the save on exit after choosing exit and save? You go back to the Exit choices then. uiIDA[0]=IDS_CONFIRM_CANCEL; @@ -971,7 +971,7 @@ int UIScene_PauseMenu::ExitGameDialogReturned(void *pParam,int iPad,C4JStorage:: int UIScene_PauseMenu::SaveWorldThreadProc( LPVOID lpParameter ) { - bool bAutosave=(bool)lpParameter; + bool bAutosave=static_cast(lpParameter); if(bAutosave) { app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_AutoSaveGame); @@ -1036,7 +1036,7 @@ void UIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) bool saveStats = true; if (pMinecraft->isClientSide() || g_NetworkManager.IsInSession()) { - if(lpParameter != NULL ) + if(lpParameter != nullptr ) { // 4J-PB - check if we have lost connection to Live if(ProfileManager.GetLiveConnectionStatus()!=XONLINE_S_LOGON_CONNECTION_ESTABLISHED ) @@ -1104,21 +1104,21 @@ void UIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) uiIDA[0]=IDS_CONFIRM_OK; // 4J Stu - Fix for #48669 - TU5: Code: Compliance: TCR #15: Incorrect/misleading messages after signing out a profile during online game session. // If the primary player is signed out, then that is most likely the cause of the disconnection so don't display a message box. This will allow the message box requested by the libraries to be brought up - if( ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) ui.RequestMessageBox( exitReasonTitleId, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + if( ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) ui.RequestMessageBox( exitReasonTitleId, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); exitReasonStringId = -1; // 4J - Force a disconnection, this handles the situation that the server has already disconnected - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(false); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(false); - if( pMinecraft->levels[2] != NULL ) pMinecraft->levels[2]->disconnect(false); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(false); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(false); + if( pMinecraft->levels[2] != nullptr ) pMinecraft->levels[2]->disconnect(false); } else { exitReasonStringId = IDS_EXITING_GAME; pMinecraft->progressRenderer->progressStartNoAbort( IDS_EXITING_GAME ); - if( pMinecraft->levels[0] != NULL ) pMinecraft->levels[0]->disconnect(); - if( pMinecraft->levels[1] != NULL ) pMinecraft->levels[1]->disconnect(); - if( pMinecraft->levels[2] != NULL ) pMinecraft->levels[2]->disconnect(); + if( pMinecraft->levels[0] != nullptr ) pMinecraft->levels[0]->disconnect(); + if( pMinecraft->levels[1] != nullptr ) pMinecraft->levels[1]->disconnect(); + if( pMinecraft->levels[2] != nullptr ) pMinecraft->levels[2]->disconnect(); } // 4J Stu - This only does something if we actually have a server, so don't need to do any other checks @@ -1134,7 +1134,7 @@ void UIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) } else { - if(lpParameter != NULL && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad()) ) + if(lpParameter != nullptr && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad()) ) { switch( app.GetDisconnectReason() ) { @@ -1180,7 +1180,7 @@ void UIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox( exitReasonTitleId, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); + ui.RequestMessageBox( exitReasonTitleId, exitReasonStringId, uiIDA,1,ProfileManager.GetPrimaryPad(),nullptr,nullptr, app.GetStringTable()); exitReasonStringId = -1; } } @@ -1189,7 +1189,7 @@ void UIScene_PauseMenu::_ExitWorld(LPVOID lpParameter) { Sleep(1); } - pMinecraft->setLevel(NULL,exitReasonStringId,nullptr,saveStats); + pMinecraft->setLevel(nullptr,exitReasonStringId,nullptr,saveStats); TelemetryManager->Flush(); diff --git a/Minecraft.Client/Common/XUI/XUI_Reinstall.cpp b/Minecraft.Client/Common/XUI/XUI_Reinstall.cpp index c1e06c0d1..c0650335c 100644 --- a/Minecraft.Client/Common/XUI/XUI_Reinstall.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Reinstall.cpp @@ -26,7 +26,7 @@ HRESULT CScene_Reinstall::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { // We'll only be in this menu from the main menu, not in game - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); m_bIgnoreInput=false; MapChildControls(); @@ -224,7 +224,7 @@ HRESULT CScene_Reinstall::OnControlNavigate(XUIMessageControlNavigate *pControlN { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -241,7 +241,7 @@ HRESULT CScene_Reinstall::OnTransitionStart( XUIMessageTransition *pTransition, // 4J-PB - Going to resize buttons if the text is too big to fit on any of them (Br-pt problem with the length of Unlock Full Game) XUIRect xuiRect; - HXUIOBJ visual=NULL; + HXUIOBJ visual=nullptr; HXUIOBJ text; float fMaxTextLen=0.0f; float fTextVisualLen; @@ -283,7 +283,7 @@ HRESULT CScene_Reinstall::OnTransitionStart( XUIMessageTransition *pTransition, int CScene_Reinstall::DeviceSelectReturned(void *pParam,bool bContinue) { - CScene_Reinstall* pClass = (CScene_Reinstall*)pParam; + CScene_Reinstall* pClass = static_cast(pParam); if(!StorageManager.GetSaveDeviceSelected(pClass->m_iPad)) { @@ -300,7 +300,7 @@ int CScene_Reinstall::DeviceSelectReturned(void *pParam,bool bContinue) int CScene_Reinstall::DeviceSelectReturned_AndReinstall(void *pParam,bool bContinue) { - CScene_Reinstall* pClass = (CScene_Reinstall*)pParam; + CScene_Reinstall* pClass = static_cast(pParam); if(!StorageManager.GetSaveDeviceSelected(pClass->m_iPad)) { diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp index 03e783f42..2692c8f1c 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp @@ -71,8 +71,8 @@ void CXuiSceneAbstractContainer::PlatformInitialize(int iPad, int startIndex) m_fPointerMaxX = fPanelWidth + fPointerWidth; m_fPointerMaxY = fPanelHeight + (fPointerHeight/2); -// m_hPointerText=NULL; -// m_hPointerTextBkg=NULL; +// m_hPointerText=nullptr; +// m_hPointerTextBkg=nullptr; UIVec2D itemPos; UIVec2D itemSize; @@ -113,7 +113,7 @@ void CXuiSceneAbstractContainer::PlatformInitialize(int iPad, int startIndex) // Disable the default navigation behaviour for all slot lsit items (prevent old style cursor navigation). for ( int iSection = m_eFirstSection; iSection < m_eMaxSection; ++iSection ) { - ESceneSection eSection = ( ESceneSection )( iSection ); + ESceneSection eSection = static_cast(iSection); if(!IsSectionSlotList(eSection)) continue; @@ -170,7 +170,7 @@ HRESULT CXuiSceneAbstractContainer::OnTransitionStart( XUIMessageTransition *pTr InitDataAssociations(m_iPad, m_menu); } - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; HRESULT hr=XuiControlGetVisual(m_pointerControl->m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"text_measurer",&m_hPointerTextMeasurer); hr=XuiElementGetChildById(hObj,L"text_name",&m_hPointerText); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Anvil.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Anvil.cpp index 4a8617b47..36a12757c 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Anvil.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Anvil.cpp @@ -28,7 +28,7 @@ HRESULT CXuiSceneAnvil::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - AnvilScreenInput* initData = (AnvilScreenInput*)pInitData->pvInitData; + AnvilScreenInput* initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; m_inventory = initData->inventory; @@ -40,9 +40,9 @@ HRESULT CXuiSceneAnvil::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); } - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Anvil_Menu, this); } @@ -67,15 +67,15 @@ HRESULT CXuiSceneAnvil::OnDestroy() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -89,8 +89,8 @@ HRESULT CXuiSceneAnvil::OnNotifyValueChanged (HXUIOBJ hObjSource, XUINotifyValue // strip leading spaces wstring b; - int start = (int)newValue.find_first_not_of(L" "); - int end = (int)newValue.find_last_not_of(L" "); + size_t start = newValue.find_first_not_of(L" "); + size_t end = newValue.find_last_not_of(L" "); if( start == wstring::npos ) { @@ -99,7 +99,7 @@ HRESULT CXuiSceneAnvil::OnNotifyValueChanged (HXUIOBJ hObjSource, XUINotifyValue } else { - if( end == wstring::npos ) end = (int)newValue.size()-1; + if( end == wstring::npos ) end = newValue.size() - 1; b = newValue.substr(start,(end-start)+1); newValue=b; } @@ -158,7 +158,7 @@ CXuiControl* CXuiSceneAnvil::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneAnvil::GetSectionSlotList( ESceneSection eSection ) @@ -184,7 +184,7 @@ CXuiCtrlSlotList* CXuiSceneAnvil::GetSectionSlotList( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Base.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Base.cpp index 1a679f586..c9a57f214 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Base.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Base.cpp @@ -22,14 +22,14 @@ #define PRESS_START_TIMER 0 -CXuiSceneBase *CXuiSceneBase::Instance = NULL; +CXuiSceneBase *CXuiSceneBase::Instance = nullptr; DWORD CXuiSceneBase::m_dwTrialTimerLimitSecs=DYNAMIC_CONFIG_DEFAULT_TRIAL_TIME; //---------------------------------------------------------------------------------- // Performs initialization tasks - retrieves controls. //---------------------------------------------------------------------------------- HRESULT CXuiSceneBase::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - ASSERT( CXuiSceneBase::Instance == NULL ); + ASSERT( CXuiSceneBase::Instance == nullptr ); CXuiSceneBase::Instance = this; m_iWrongTexturePackTickC=20*5; // default 5 seconds before bringing up the upsell for not having the texture pack @@ -41,7 +41,7 @@ HRESULT CXuiSceneBase::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) HXUIOBJ hTemp; - m_hEmptyQuadrantLogo=NULL; + m_hEmptyQuadrantLogo=nullptr; XuiElementGetChildById(m_hObj,L"EmptyQuadrantLogo",&m_hEmptyQuadrantLogo); D3DXVECTOR3 lastPos; @@ -51,8 +51,8 @@ HRESULT CXuiSceneBase::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { m_visible[idx][ i ] = FALSE; m_iCurrentTooltipTextID[idx][i]=-1; - hTooltipText[idx][i]=NULL; - hTooltipTextSmall[idx][i]=NULL; + hTooltipText[idx][i]=nullptr; + hTooltipTextSmall[idx][i]=nullptr; // set all tooltips to shown FALSE by default m_Buttons[idx][i].SetShow( FALSE ); m_ButtonsSmall[idx][i].SetShow( FALSE ); @@ -106,7 +106,7 @@ HRESULT CXuiSceneBase::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) // clear the quadrants m_iQuadrantsMask=0; - HXUIOBJ hObj=NULL,hQuadrant; + HXUIOBJ hObj=nullptr,hQuadrant; HRESULT hr=XuiControlGetVisual(m_PressStart.m_hObj,&hObj); @@ -144,8 +144,8 @@ HRESULT CXuiSceneBase::OnSkinChanged(BOOL& bHandled) { for( unsigned int i = 0; i < BUTTONS_TOOLTIP_MAX; ++i ) { - hTooltipText[idx][i]=NULL; - hTooltipTextSmall[idx][i]=NULL; + hTooltipText[idx][i]=nullptr; + hTooltipTextSmall[idx][i]=nullptr; } } @@ -178,7 +178,7 @@ void CXuiSceneBase::_TickAllBaseScenes() //Is it available? TexturePack * pRequiredTPack=pMinecraft->skins->getTexturePackById(app.GetRequiredTexturePackID()); - if(pRequiredTPack!=NULL) + if(pRequiredTPack!=nullptr) { // we can switch to the required pack // reset the timer @@ -206,7 +206,7 @@ void CXuiSceneBase::_TickAllBaseScenes() } } - if (EnderDragonRenderer::bossInstance == NULL) + if (EnderDragonRenderer::bossInstance == nullptr) { if(m_ticksWithNoBoss<=20) { @@ -221,7 +221,7 @@ void CXuiSceneBase::_TickAllBaseScenes() for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { - if(pMinecraft->localplayers[i] != NULL && pMinecraft->localplayers[i]->dimension == 1 && !ui.GetMenuDisplayed(i) && app.GetGameSettings(i,eGameSetting_DisplayHUD)) + if(pMinecraft->localplayers[i] != nullptr && pMinecraft->localplayers[i]->dimension == 1 && !ui.GetMenuDisplayed(i) && app.GetGameSettings(i,eGameSetting_DisplayHUD)) { int iGuiScale; @@ -245,7 +245,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(TRUE); m_BossHealthProgress2[i].SetShow(FALSE); m_BossHealthProgress3[i].SetShow(FALSE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -259,7 +259,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(FALSE); m_BossHealthProgress2[i].SetShow(TRUE); m_BossHealthProgress3[i].SetShow(FALSE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -272,7 +272,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(FALSE); m_BossHealthProgress2[i].SetShow(FALSE); m_BossHealthProgress3[i].SetShow(TRUE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -295,7 +295,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(TRUE); m_BossHealthProgress2[i].SetShow(FALSE); m_BossHealthProgress3[i].SetShow(FALSE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -308,7 +308,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(FALSE); m_BossHealthProgress2[i].SetShow(TRUE); m_BossHealthProgress3[i].SetShow(FALSE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -320,7 +320,7 @@ void CXuiSceneBase::_TickAllBaseScenes() m_BossHealthProgress1[i].SetShow(FALSE); m_BossHealthProgress2[i].SetShow(FALSE); m_BossHealthProgress3[i].SetShow(TRUE); - if(m_BossHealthProgress1_small[i]!=NULL) + if(m_BossHealthProgress1_small[i]!=nullptr) { m_BossHealthProgress1_small[i].SetShow(FALSE); m_BossHealthProgress2_small[i].SetShow(FALSE); @@ -401,7 +401,7 @@ void CXuiSceneBase::_TickAllBaseScenes() if(uiOpacityTimer < (SharedConstants::TICKS_PER_SECOND * 1) ) { float fStep=(80.0f)/10.0f; - float fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); XuiElementSetOpacity(m_selectedItemA[i],fVal); XuiElementSetOpacity(m_selectedItemSmallA[i],fVal); @@ -441,8 +441,8 @@ void CXuiSceneBase::_TickAllBaseScenes() { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -451,7 +451,7 @@ void CXuiSceneBase::_TickAllBaseScenes() } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else @@ -461,7 +461,7 @@ void CXuiSceneBase::_TickAllBaseScenes() { ucAlpha=15; } - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } XuiElementSetOpacity(app.GetCurrentHUDScene(i),fVal); @@ -470,7 +470,7 @@ void CXuiSceneBase::_TickAllBaseScenes() XuiSendMessage( app.GetCurrentHUDScene(i), &xuiMsg ); bool bDisplayGui=app.GetGameStarted() && !ui.GetMenuDisplayed(i) && !(app.GetXuiAction(i)==eAppAction_AutosaveSaveGameCapturedThumbnail) && app.GetGameSettings(i,eGameSetting_DisplayHUD)!=0; - if(bDisplayGui && pMinecraft->localplayers[i] != NULL) + if(bDisplayGui && pMinecraft->localplayers[i] != nullptr) { XuiElementSetShow(app.GetCurrentHUDScene(i),TRUE); } @@ -498,7 +498,7 @@ HRESULT CXuiSceneBase::_SetTooltipText( unsigned int iPad, unsigned int uiToolti XUIRect xuiRect, xuiRectSmall; HRESULT hr=S_OK; - LPCWSTR pString=NULL; + LPCWSTR pString=nullptr; float fWidth,fHeight; // Want to be able to show just a button (for RB LB) @@ -506,18 +506,17 @@ HRESULT CXuiSceneBase::_SetTooltipText( unsigned int iPad, unsigned int uiToolti { pString=app.GetString(iTextID); } - - if(hTooltipText[iPad][uiTooltip]==NULL) + if(hTooltipText[iPad][uiTooltip]==nullptr) { - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; hr=XuiControlGetVisual(m_Buttons[iPad][uiTooltip].m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"text_ButtonText",&hTooltipText[iPad][uiTooltip]); hr=XuiElementGetPosition(hTooltipText[iPad][uiTooltip],&m_vPosTextInTooltip[uiTooltip]); } - - if(hTooltipTextSmall[iPad][uiTooltip]==NULL) + + if(hTooltipTextSmall[iPad][uiTooltip]==nullptr) { - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; hr=XuiControlGetVisual(m_ButtonsSmall[iPad][uiTooltip].m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"text_ButtonText",&hTooltipTextSmall[iPad][uiTooltip]); hr=XuiElementGetPosition(hTooltipTextSmall[iPad][uiTooltip],&m_vPosTextInTooltipSmall[uiTooltip]); @@ -627,8 +626,8 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -637,7 +636,7 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else @@ -647,7 +646,7 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo { ucAlpha=15; } - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } m_Buttons[iPad][tooltip].SetOpacity(fVal); @@ -678,8 +677,8 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -688,12 +687,12 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } XuiElementSetOpacity(m_hGamerTagA[iPad],fVal); } @@ -701,7 +700,7 @@ HRESULT CXuiSceneBase::_ShowTooltip( unsigned int iPad, unsigned int tooltip, bo if(iPad==ProfileManager.GetPrimaryPad()) { unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); - XuiElementSetOpacity(m_hEmptyQuadrantLogo,0.01f*(float)ucAlpha); + XuiElementSetOpacity(m_hEmptyQuadrantLogo,0.01f*static_cast(ucAlpha)); } } } @@ -858,7 +857,7 @@ HRESULT CXuiSceneBase::_ShowBackground( unsigned int iPad, BOOL bShow ) hr=XuiElementGetChildById(hVisual,L"NightGroup",&hNight); hr=XuiElementGetChildById(hVisual,L"DayGroup",&hDay); - if(bShow && pMinecraft->level!=NULL) + if(bShow && pMinecraft->level!=nullptr) { int64_t i64TimeOfDay =0; // are we in the Nether? - Leave the time as 0 if we are, so we show daylight @@ -911,7 +910,7 @@ HRESULT CXuiSceneBase::_ShowPressStart(unsigned int iPad) m_PressStart.SetShow(TRUE); // retrieve the visual for this quadrant - HXUIOBJ hObj=NULL,hQuadrant; + HXUIOBJ hObj=nullptr,hQuadrant; HRESULT hr=XuiControlGetVisual(m_PressStart.m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"text_ButtonText",&hQuadrant); memset(&xuiRect, 0, sizeof(xuiRect)); @@ -976,7 +975,7 @@ HRESULT CXuiSceneBase::_UpdateTrialTimer(unsigned int iPad) { WCHAR wcTime[20]; - DWORD dwTimeTicks=(DWORD)app.getTrialTimer(); + DWORD dwTimeTicks=static_cast(app.getTrialTimer()); if(dwTimeTicks>m_dwTrialTimerLimitSecs) { @@ -1014,7 +1013,7 @@ HRESULT CXuiSceneBase::_UpdateTrialTimer(unsigned int iPad) void CXuiSceneBase::_ReduceTrialTimerValue() { - DWORD dwTimeTicks=(int)app.getTrialTimer(); + DWORD dwTimeTicks=static_cast(app.getTrialTimer()); if(dwTimeTicks>m_dwTrialTimerLimitSecs) { @@ -1038,7 +1037,7 @@ bool CXuiSceneBase::_PressStartPlaying(unsigned int iPad) HRESULT CXuiSceneBase::_SetPlayerBaseScenePosition( unsigned int iPad, EBaseScenePosition position ) { // turn off the empty quadrant logo - if(m_hEmptyQuadrantLogo!=NULL) + if(m_hEmptyQuadrantLogo!=nullptr) { XuiElementSetShow(m_hEmptyQuadrantLogo,FALSE); } @@ -1268,7 +1267,7 @@ HRESULT CXuiSceneBase::_SetPlayerBaseScenePosition( unsigned int iPad, EBaseScen // 4J Stu - If we already have some scenes open, then call this to update their positions // Fix for #10960 - All Lang: UI: Split-screen: Changing split screen mode (vertical/horizontal) make window layout strange - if(Minecraft::GetInstance() != NULL && Minecraft::GetInstance()->localplayers[iPad]!=NULL) + if(Minecraft::GetInstance() != nullptr && Minecraft::GetInstance()->localplayers[iPad]!=nullptr) { // 4J-PB - Can only do this once we know what the player's UI settings are, so we need to have the player game settings read _UpdateSelectedItemPos(iPad); @@ -1339,7 +1338,7 @@ void CXuiSceneBase::_UpdateSelectedItemPos(unsigned int iPad) unsigned char ucGuiScale=app.GetGameSettings(iPad,eGameSetting_UISize) + 2; - if(Minecraft::GetInstance() != NULL && Minecraft::GetInstance()->localgameModes[iPad] != NULL && Minecraft::GetInstance()->localgameModes[iPad]->canHurtPlayer()) + if(Minecraft::GetInstance() != nullptr && Minecraft::GetInstance()->localgameModes[iPad] != nullptr && Minecraft::GetInstance()->localgameModes[iPad]->canHurtPlayer()) { // SURVIVAL MODE - Move up further because of hearts, shield and xp switch(ucGuiScale) @@ -1428,7 +1427,7 @@ void CXuiSceneBase::_UpdateSelectedItemPos(unsigned int iPad) { float scale=0.5f; selectedItemPos.y -= (scale * 88.0f); - if(Minecraft::GetInstance() != NULL && Minecraft::GetInstance()->localgameModes[iPad] != NULL && Minecraft::GetInstance()->localgameModes[iPad]->canHurtPlayer()) + if(Minecraft::GetInstance() != nullptr && Minecraft::GetInstance()->localgameModes[iPad] != nullptr && Minecraft::GetInstance()->localgameModes[iPad]->canHurtPlayer()) { selectedItemPos.y -= (scale * 80.0f); } @@ -1471,7 +1470,7 @@ CXuiSceneBase::EBaseScenePosition CXuiSceneBase::_GetPlayerBasePosition(int iPad void CXuiSceneBase::_SetEmptyQuadrantLogo(int iPad,EBaseScenePosition ePos) { - if(m_hEmptyQuadrantLogo!=NULL) + if(m_hEmptyQuadrantLogo!=nullptr) { for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { @@ -1512,7 +1511,7 @@ void CXuiSceneBase::_SetEmptyQuadrantLogo(int iPad,EBaseScenePosition ePos) if(ProfileManager.GetLockedProfile()!=-1) { unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); - XuiElementSetOpacity(m_hEmptyQuadrantLogo,0.01f*(float)ucAlpha); + XuiElementSetOpacity(m_hEmptyQuadrantLogo,0.01f*static_cast(ucAlpha)); } XuiElementSetPosition(m_hEmptyQuadrantLogo, &pos ); @@ -1607,7 +1606,7 @@ HRESULT CXuiSceneBase::_DisplayGamertag( unsigned int iPad, BOOL bDisplay ) // The host decides whether these are on or off if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_DisplaySplitscreenGamertags)!=0) { - if(Minecraft::GetInstance() != NULL && Minecraft::GetInstance()->localplayers[iPad]!=NULL) + if(Minecraft::GetInstance() != nullptr && Minecraft::GetInstance()->localplayers[iPad]!= nullptr) { wstring wsGamertag = convStringToWstring( ProfileManager.GetGamertag(iPad)); XuiControlSetText(m_hGamerTagA[iPad],wsGamertag.c_str()); @@ -1638,8 +1637,8 @@ HRESULT CXuiSceneBase::_DisplayGamertag( unsigned int iPad, BOOL bDisplay ) { if(uiOpacityTimer<10) { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=0.01f*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); + float fStep=(80.0f-static_cast(ucAlpha))/10.0f; + fVal=0.01f*(80.0f-((10.0f-static_cast(uiOpacityTimer))*fStep)); } else { @@ -1648,12 +1647,12 @@ HRESULT CXuiSceneBase::_DisplayGamertag( unsigned int iPad, BOOL bDisplay ) } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } } else { - fVal=0.01f*(float)ucAlpha; + fVal=0.01f*static_cast(ucAlpha); } XuiElementSetOpacity(m_hGamerTagA[iPad],0.01f*fVal); } @@ -1864,7 +1863,7 @@ void CXuiSceneBase::ReLayout( unsigned int iPad ) void CXuiSceneBase::TickAllBaseScenes() { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { CXuiSceneBase::Instance->_TickAllBaseScenes(); } @@ -1872,7 +1871,7 @@ void CXuiSceneBase::TickAllBaseScenes() HRESULT CXuiSceneBase::SetEnableTooltips( unsigned int iPad, BOOL bVal ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_SetEnableTooltips(iPad, bVal ); } @@ -1881,7 +1880,7 @@ HRESULT CXuiSceneBase::SetEnableTooltips( unsigned int iPad, BOOL bVal ) HRESULT CXuiSceneBase::SetTooltipText( unsigned int iPad, unsigned int tooltip, int iTextID ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_SetTooltipText(iPad, tooltip, iTextID ); } @@ -1890,7 +1889,7 @@ HRESULT CXuiSceneBase::SetTooltipText( unsigned int iPad, unsigned int tooltip, HRESULT CXuiSceneBase::RefreshTooltips( unsigned int iPad) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_RefreshTooltips(iPad); } @@ -1899,7 +1898,7 @@ HRESULT CXuiSceneBase::RefreshTooltips( unsigned int iPad) HRESULT CXuiSceneBase::ShowTooltip( unsigned int iPad, unsigned int tooltip, bool show ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_ShowTooltip(iPad, tooltip, show ); } @@ -1908,7 +1907,7 @@ HRESULT CXuiSceneBase::ShowTooltip( unsigned int iPad, unsigned int tooltip, boo HRESULT CXuiSceneBase::ShowSafeArea( BOOL bShow ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_ShowSafeArea(bShow ); } @@ -1917,7 +1916,7 @@ HRESULT CXuiSceneBase::ShowSafeArea( BOOL bShow ) HRESULT CXuiSceneBase::SetTooltips( unsigned int iPad, int iA, int iB, int iX, int iY , int iLT, int iRT, int iRB, int iLB, int iLS, bool forceUpdate /*= false*/ ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { // Enable all the tooltips. We should disable them in the scenes as required CXuiSceneBase::Instance->_SetTooltipsEnabled( iPad ); @@ -1978,7 +1977,7 @@ HRESULT CXuiSceneBase::AnimateKeyPress(DWORD userIndex, DWORD dwKeyCode) HRESULT CXuiSceneBase::ShowSavingMessage( unsigned int iPad, C4JStorage::ESavingMessage eVal ) { - if( CXuiSceneBase::Instance != NULL ) + if( CXuiSceneBase::Instance != nullptr ) { return CXuiSceneBase::Instance->_ShowSavingMessage(iPad, eVal); } @@ -2078,7 +2077,7 @@ HRESULT CXuiSceneBase::UpdatePlayerBasePositions() Minecraft *pMinecraft = Minecraft::GetInstance(); // If the game is not started (or is being held paused for a bit) then display all scenes fullscreen - if( pMinecraft == NULL ) + if( pMinecraft == nullptr ) { for( BYTE idx = 0; idx < XUSER_MAX_COUNT; ++idx) { @@ -2105,7 +2104,7 @@ HRESULT CXuiSceneBase::UpdatePlayerBasePositions() for( BYTE idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(pMinecraft->localplayers[idx] != NULL) + if(pMinecraft->localplayers[idx] != nullptr) { if(pMinecraft->localplayers[idx]->m_iScreenSection==C4JRender::VIEWPORT_TYPE_FULLSCREEN) { @@ -2186,7 +2185,7 @@ void CXuiSceneBase::SetEmptyQuadrantLogo(int iScreenSection) // find the empty player for( iPad = 0; iPad < XUSER_MAX_COUNT; ++iPad) { - if(pMinecraft->localplayers[iPad] == NULL) + if(pMinecraft->localplayers[iPad] == nullptr) { switch( iScreenSection) { @@ -2238,6 +2237,6 @@ void CXuiSceneBase::CreateBaseSceneInstance() { CXuiSceneBase *sceneBase = new CXuiSceneBase(); BOOL handled; - sceneBase->OnInit(NULL,handled); + sceneBase->OnInit(nullptr,handled); } #endif \ No newline at end of file diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_BrewingStand.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_BrewingStand.cpp index cf6009661..a55e8f777 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_BrewingStand.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_BrewingStand.cpp @@ -24,7 +24,7 @@ HRESULT CXuiSceneBrewingStand::OnInit( XUIMessageInit* pInitData, BOOL& bHandled Minecraft *pMinecraft = Minecraft::GetInstance(); - BrewingScreenInput* initData = (BrewingScreenInput*)pInitData->pvInitData; + BrewingScreenInput* initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; @@ -36,7 +36,7 @@ HRESULT CXuiSceneBrewingStand::OnInit( XUIMessageInit* pInitData, BOOL& bHandled } #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -67,16 +67,16 @@ HRESULT CXuiSceneBrewingStand::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -106,7 +106,7 @@ CXuiControl* CXuiSceneBrewingStand::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneBrewingStand::GetSectionSlotList( ESceneSection eSection ) @@ -135,7 +135,7 @@ CXuiCtrlSlotList* CXuiSceneBrewingStand::GetSectionSlotList( ESceneSection eSect assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Container.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Container.cpp index 39b836d2c..25f5cffcb 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Container.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Container.cpp @@ -29,7 +29,7 @@ HRESULT CXuiSceneContainer::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - ContainerScreenInput* initData = (ContainerScreenInput*)pInitData->pvInitData; + ContainerScreenInput* initData = static_cast(pInitData->pvInitData); XuiControlSetText(m_ChestText,app.GetString(initData->container->getName())); @@ -40,7 +40,7 @@ HRESULT CXuiSceneContainer::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) m_bSplitscreen=initData->bSplitscreen; #ifdef _XBOX - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -75,9 +75,9 @@ HRESULT CXuiSceneContainer::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) // to get it into actual back buffer coordinates, and we need those to remain whole numbers to avoid issues with point sampling if(!RenderManager.IsHiDef()) { - int iY = (int)(vPos.y); + int iY = static_cast(vPos.y); iY &= 0xfffffffe; - vPos.y = (float)iY; + vPos.y = static_cast(iY); } this->SetPosition( &vPos ); @@ -95,16 +95,16 @@ HRESULT CXuiSceneContainer::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -125,7 +125,7 @@ CXuiControl* CXuiSceneContainer::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneContainer::GetSectionSlotList( ESceneSection eSection ) @@ -145,7 +145,7 @@ CXuiCtrlSlotList* CXuiSceneContainer::GetSectionSlotList( ESceneSection eSection assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_CraftingPanel.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_CraftingPanel.cpp index a5dc65849..f1c51ff0d 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_CraftingPanel.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_CraftingPanel.cpp @@ -40,7 +40,7 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle D3DXVECTOR3 vec; VOID *pObj; - CraftingPanelScreenInput* pCraftingPanelData = (CraftingPanelScreenInput*)pInitData->pvInitData; + CraftingPanelScreenInput* pCraftingPanelData = static_cast(pInitData->pvInitData); m_iContainerType=pCraftingPanelData->iContainerType; m_pPlayer=pCraftingPanelData->player; m_iPad=pCraftingPanelData->iPad; @@ -89,12 +89,12 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle for(int i=0;i(pObj); } XuiObjectFromHandle( m_hCraftOutput, &pObj ); - m_pCraftingOutput = (CXuiCtrlCraftIngredientSlot *)pObj; - m_pGroupA=(Recipy::_eGroupType *)&m_GroupTypeMapping9GridA; - m_pGroupTabA=(CXuiSceneCraftingPanel::_eGroupTab *)&m_GroupTabBkgMapping3x3A; + m_pCraftingOutput = static_cast(pObj); + m_pGroupA=static_cast(&m_GroupTypeMapping9GridA); + m_pGroupTabA=static_cast(&m_GroupTabBkgMapping3x3A); m_iCraftablesMaxHSlotC=m_iMaxHSlot3x3C; @@ -102,7 +102,7 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle for(int i=0;i<4;i++) { XuiObjectFromHandle( m_hCraftIngredientDescA[i], &pObj ); - m_pCraftIngredientDescA[i] = (CXuiCtrlCraftIngredientSlot *)pObj; + m_pCraftIngredientDescA[i] = static_cast(pObj); } } else @@ -113,13 +113,13 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle for(int i=0;i(pObj); } XuiObjectFromHandle( m_hCraftOutput, &pObj ); - m_pCraftingOutput = (CXuiCtrlCraftIngredientSlot *)pObj; - m_pGroupA=(Recipy::_eGroupType *)&m_GroupTypeMapping4GridA; - m_pGroupTabA=(CXuiSceneCraftingPanel::_eGroupTab *)&m_GroupTabBkgMapping2x2A; + m_pCraftingOutput = static_cast(pObj); + m_pGroupA=static_cast(&m_GroupTypeMapping4GridA); + m_pGroupTabA=static_cast(&m_GroupTabBkgMapping2x2A); m_iCraftablesMaxHSlotC=m_iMaxHSlot2x2C; @@ -127,7 +127,7 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle for(int i=0;i<4;i++) { XuiObjectFromHandle( m_hCraftIngredientDescA[i], &pObj ); - m_pCraftIngredientDescA[i] = (CXuiCtrlCraftIngredientSlot *)pObj; + m_pCraftIngredientDescA[i] = static_cast(pObj); } } @@ -165,7 +165,7 @@ HRESULT CXuiSceneCraftingPanel::OnInit( XUIMessageInit* pInitData, BOOL& bHandle Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -206,7 +206,7 @@ HRESULT CXuiSceneCraftingPanel::OnTransitionEnd( XUIMessageTransition *pTransDat { for(int i=0;iiItem; int iId=(pData->iData>>22)&0x1FF; - pData->szPath = NULL; + pData->szPath = nullptr; pData->bDirty=true; rfHandled = TRUE; return hr; @@ -352,15 +352,15 @@ HRESULT CXuiSceneCraftingPanel::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -433,7 +433,7 @@ void CXuiSceneCraftingPanel::setCraftVSlotItem(int iPad, int iIndex, shared_ptr< void CXuiSceneCraftingPanel::setCraftingOutputSlotItem(int iPad, shared_ptr item) { - if(item == NULL) + if(item == nullptr) { m_pCraftingOutput->SetIcon(iPad, 0,0,0,0,0,false); } @@ -450,7 +450,7 @@ void CXuiSceneCraftingPanel::setCraftingOutputSlotRedBox(bool show) void CXuiSceneCraftingPanel::setIngredientSlotItem(int iPad, int index, shared_ptr item) { - if(item == NULL) + if(item == nullptr) { m_pCraftingIngredientA[index]->SetIcon(iPad, 0,0,0,0,0,false); } diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Enchant.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Enchant.cpp index 5b3c72261..dabe6d6d1 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Enchant.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Enchant.cpp @@ -30,7 +30,7 @@ HRESULT CXuiSceneEnchant::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - EnchantingScreenInput *initData = (EnchantingScreenInput *) pInitData->pvInitData; + EnchantingScreenInput *initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; @@ -42,7 +42,7 @@ HRESULT CXuiSceneEnchant::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) } #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -73,16 +73,16 @@ HRESULT CXuiSceneEnchant::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -112,7 +112,7 @@ CXuiControl* CXuiSceneEnchant::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneEnchant::GetSectionSlotList( ESceneSection eSection ) @@ -132,7 +132,7 @@ CXuiCtrlSlotList* CXuiSceneEnchant::GetSectionSlotList( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Furnace.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Furnace.cpp index 832d6b4ce..c5e2d22c3 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Furnace.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Furnace.cpp @@ -26,7 +26,7 @@ HRESULT CXuiSceneFurnace::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - FurnaceScreenInput* initData = (FurnaceScreenInput*)pInitData->pvInitData; + FurnaceScreenInput* initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; @@ -38,7 +38,7 @@ HRESULT CXuiSceneFurnace::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) } #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -69,16 +69,16 @@ HRESULT CXuiSceneFurnace::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -105,7 +105,7 @@ CXuiControl* CXuiSceneFurnace::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneFurnace::GetSectionSlotList( ESceneSection eSection ) @@ -131,7 +131,7 @@ CXuiCtrlSlotList* CXuiSceneFurnace::GetSectionSlotList( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp index 6024b8d6e..e86ff67e0 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp @@ -23,7 +23,7 @@ HRESULT CXuiSceneInventory::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - InventoryScreenInput *initData = (InventoryScreenInput *)pInitData->pvInitData; + InventoryScreenInput *initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; @@ -38,7 +38,7 @@ HRESULT CXuiSceneInventory::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) } #ifdef _XBOX - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -79,15 +79,15 @@ HRESULT CXuiSceneInventory::OnDestroy() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -118,7 +118,7 @@ CXuiControl* CXuiSceneInventory::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneInventory::GetSectionSlotList( ESceneSection eSection ) @@ -138,7 +138,7 @@ CXuiCtrlSlotList* CXuiSceneInventory::GetSectionSlotList( ESceneSection eSection assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back @@ -156,12 +156,12 @@ void CXuiSceneInventory::updateEffectsDisplay() Minecraft *pMinecraft = Minecraft::GetInstance(); shared_ptr player = pMinecraft->localplayers[m_iPad]; - if(player == NULL) return; + if(player == nullptr) return; vector *activeEffects = player->getActiveEffects(); // Work out how to arrange the effects - int effectCount = (int)activeEffects->size(); + int effectCount = static_cast(activeEffects->size()); // Total size of all effects + spacing, minus spacing for the last effect float fHeight = (effectCount * m_effectDisplaySpacing) - (m_effectDisplaySpacing - m_effectDisplayHeight); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory_Creative.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory_Creative.cpp index 0793fc9e0..0fa3e7803 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory_Creative.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory_Creative.cpp @@ -33,7 +33,7 @@ HRESULT CXuiSceneInventoryCreative::OnInit( XUIMessageInit *pInitData, BOOL &bHa Minecraft *pMinecraft = Minecraft::GetInstance(); - InventoryScreenInput *initData = (InventoryScreenInput *)pInitData->pvInitData; + InventoryScreenInput *initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; @@ -48,7 +48,7 @@ HRESULT CXuiSceneInventoryCreative::OnInit( XUIMessageInit *pInitData, BOOL &bHa } #ifdef _XBOX - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -60,7 +60,7 @@ HRESULT CXuiSceneInventoryCreative::OnInit( XUIMessageInit *pInitData, BOOL &bHa initData->player->awardStat(GenericStats::openInventory(), GenericStats::param_noArgs()); // 4J JEV - Item Picker Menu - shared_ptr creativeContainer = shared_ptr(new SimpleContainer( 0, TabSpec::MAX_SIZE + 9 )); + shared_ptr creativeContainer = std::make_shared(0, TabSpec::MAX_SIZE + 9); itemPickerMenu = new ItemPickerMenu(creativeContainer, initData->player->inventory); // 4J JEV - InitDataAssociations. @@ -95,16 +95,16 @@ HRESULT CXuiSceneInventoryCreative::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -126,7 +126,7 @@ HRESULT CXuiSceneInventoryCreative::OnTransitionEnd( XUIMessageTransition *pTran { for(int i=0;im_icon,NULL,specs[i]->m_icon); + m_hGroupIconA[i].PlayVisualRange(specs[i]->m_icon,nullptr,specs[i]->m_icon); XuiElementSetShow(m_hGroupIconA[i].m_hObj,TRUE); } } @@ -139,16 +139,16 @@ CXuiControl* CXuiSceneInventoryCreative::GetSectionControl( ESceneSection eSecti switch( eSection ) { case eSectionInventoryCreativeUsing: - return (CXuiControl *)m_useRowControl; + return static_cast(m_useRowControl); break; case eSectionInventoryCreativeSelector: - return (CXuiControl *)m_containerControl; + return static_cast(m_containerControl); break; default: assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneInventoryCreative::GetSectionSlotList( ESceneSection eSection ) @@ -165,7 +165,7 @@ CXuiCtrlSlotList* CXuiSceneInventoryCreative::GetSectionSlotList( ESceneSection assert( false ); break; } - return NULL; + return nullptr; } void CXuiSceneInventoryCreative::updateTabHighlightAndText(ECreativeInventoryTabs tab) diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp index 8738e683e..3fbca979e 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp @@ -27,7 +27,7 @@ HRESULT CXuiSceneTrading::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - TradingScreenInput* initData = (TradingScreenInput *)pInitData->pvInitData; + TradingScreenInput* initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; m_merchant = initData->trader; @@ -39,9 +39,9 @@ HRESULT CXuiSceneTrading::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); } - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Trading_Menu, this); } @@ -79,15 +79,15 @@ HRESULT CXuiSceneTrading::OnDestroy() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -97,7 +97,7 @@ HRESULT CXuiSceneTrading::OnTransitionStart( XUIMessageTransition *pTransition, if(pTransition->dwTransType == XUI_TRANSITION_TO || pTransition->dwTransType == XUI_TRANSITION_BACKTO) { - HXUIOBJ hObj=NULL; + HXUIOBJ hObj=nullptr; HRESULT hr=XuiControlGetVisual(m_offerInfoControl.m_hObj,&hObj); hr=XuiElementGetChildById(hObj,L"text_measurer",&m_hOfferInfoTextMeasurer); hr=XuiElementGetChildById(hObj,L"text_name",&m_hOfferInfoText); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Trap.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Trap.cpp index 99dc6e4c4..326e62639 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Trap.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Trap.cpp @@ -22,12 +22,12 @@ HRESULT CXuiSceneTrap::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) Minecraft *pMinecraft = Minecraft::GetInstance(); - TrapScreenInput* initData = (TrapScreenInput*)pInitData->pvInitData; + TrapScreenInput* initData = static_cast(pInitData->pvInitData); m_iPad=initData->iPad; m_bSplitscreen=initData->bSplitscreen; #ifdef _XBOX - if( pMinecraft->localgameModes[initData->iPad] != NULL ) + if( pMinecraft->localgameModes[initData->iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[initData->iPad]; m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); @@ -57,16 +57,16 @@ HRESULT CXuiSceneTrap::OnDestroy() Minecraft *pMinecraft = Minecraft::GetInstance(); #ifdef _XBOX - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(gameMode != NULL) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); + if(gameMode != nullptr) gameMode->getTutorial()->changeTutorialState(m_previousTutorialState); } #endif // 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) - if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); + if(Minecraft::GetInstance()->localplayers[m_iPad] != nullptr) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -87,7 +87,7 @@ CXuiControl* CXuiSceneTrap::GetSectionControl( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } CXuiCtrlSlotList* CXuiSceneTrap::GetSectionSlotList( ESceneSection eSection ) @@ -107,7 +107,7 @@ CXuiCtrlSlotList* CXuiSceneTrap::GetSectionSlotList( ESceneSection eSection ) assert( false ); break; } - return NULL; + return nullptr; } // 4J Stu - Added to support auto-save. Need to re-associate on a navigate back diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp index 19e6b0161..c4c279a61 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp @@ -21,7 +21,7 @@ const float CScene_Win::PLAYER_SCROLL_SPEED = 3.0f; //---------------------------------------------------------------------------------- HRESULT CScene_Win::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); m_bIgnoreInput = false; @@ -57,18 +57,18 @@ HRESULT CScene_Win::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) noNoiseString = app.FormatHTMLString(m_iPad, noNoiseString, 0xff000000); Random random(8124371); - int found=(int)noNoiseString.find_first_of(L"{"); - int length; + size_t found=noNoiseString.find_first_of(L"{"); + size_t length; while (found!=string::npos) { length = random.nextInt(4) + 3; m_noiseLengths.push_back(length); - found=(int)noNoiseString.find_first_of(L"{",found+1); + found=noNoiseString.find_first_of(L"{", found + 1); } Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[s_winUserIndex] != NULL) + if(pMinecraft->localplayers[s_winUserIndex] != nullptr) { noNoiseString = replaceAll(noNoiseString,L"{*PLAYER*}",pMinecraft->localplayers[s_winUserIndex]->name); } @@ -134,7 +134,7 @@ HRESULT CScene_Win::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled) app.CloseAllPlayersXuiScenes(); for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { - if(pMinecraft->localplayers[i] != NULL) + if(pMinecraft->localplayers[i] != nullptr) { app.SetAction(i,eAppAction_Respawn); } @@ -143,7 +143,7 @@ HRESULT CScene_Win::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled) // Show the other players scenes CXuiSceneBase::ShowOtherPlayersBaseScene(pInputData->UserIndex, true); // This just allows it to be shown - if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); + if(pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) pMinecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(true); ui.UpdatePlayerBasePositions(); rfHandled = TRUE; @@ -277,7 +277,7 @@ HRESULT CScene_Win::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) CXuiSceneBase::ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); // This just allows it to be shown - if(Minecraft::GetInstance()->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) Minecraft::GetInstance()->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); + if(Minecraft::GetInstance()->localgameModes[ProfileManager.GetPrimaryPad()] != nullptr) Minecraft::GetInstance()->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); // Temporarily make this scene fullscreen CXuiSceneBase::SetPlayerBaseScenePosition( ProfileManager.GetPrimaryPad(), CXuiSceneBase::e_BaseScene_Fullscreen ); diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsAll.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsAll.cpp index c6dc7118f..3c37b8d85 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsAll.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsAll.cpp @@ -10,9 +10,9 @@ HRESULT CScene_SettingsAll::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { //WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); MapChildControls(); @@ -112,7 +112,7 @@ HRESULT CScene_SettingsAll::OnControlNavigate(XUIMessageControlNavigate *pContro // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -181,7 +181,7 @@ HRESULT CScene_SettingsAll::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* HRESULT CScene_SettingsAll::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // if we're not in the game, we need to use basescene 0 if(bNotInGame) diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsAudio.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsAudio.cpp index 0f0fe2e30..6f399d55e 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsAudio.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsAudio.cpp @@ -7,9 +7,9 @@ HRESULT CScene_SettingsAudio::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); MapChildControls(); @@ -86,13 +86,13 @@ HRESULT CScene_SettingsAudio::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotif if(hObjSource==m_SliderA[SLIDER_SETTINGS_MUSIC].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_MusicVolume,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_MUSIC ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_MUSIC ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_MUSIC].SetText(TempString); } else if(hObjSource==m_SliderA[SLIDER_SETTINGS_SOUND].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_SoundFXVolume,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SOUND ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SOUND ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_SOUND].SetText(TempString); } @@ -141,7 +141,7 @@ HRESULT CScene_SettingsAudio::OnControlNavigate(XUIMessageControlNavigate *pCont // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -240,7 +240,7 @@ HRESULT CScene_SettingsAudio::OnTransitionStart( XUIMessageTransition *pTransiti HRESULT CScene_SettingsAudio::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // if we're not in the game, we need to use basescene 0 if(bNotInGame) diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsControl.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsControl.cpp index 7e2835a27..4fa335fb5 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsControl.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsControl.cpp @@ -10,9 +10,9 @@ HRESULT CScene_SettingsControl::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); MapChildControls(); @@ -66,13 +66,13 @@ HRESULT CScene_SettingsControl::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINot if(hObjSource==m_SliderA[SLIDER_SETTINGS_SENSITIVITY_INGAME].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Sensitivity_InGame,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SENSITIVITY_INGAME ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SENSITIVITY_INGAME ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_SENSITIVITY_INGAME].SetText(TempString); } else if(hObjSource==m_SliderA[SLIDER_SETTINGS_SENSITIVITY_INMENU].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Sensitivity_InMenu,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SENSITIVITY_INMENU ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_SENSITIVITY_INMENU ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_SENSITIVITY_INMENU].SetText(TempString); } @@ -120,7 +120,7 @@ HRESULT CScene_SettingsControl::OnControlNavigate(XUIMessageControlNavigate *pCo // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -218,7 +218,7 @@ HRESULT CScene_SettingsControl::OnTransitionStart( XUIMessageTransition *pTransi HRESULT CScene_SettingsControl::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // if we're not in the game, we need to use basescene 0 if(bNotInGame) diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsGraphics.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsGraphics.cpp index 48a933e27..d73baa0b3 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsGraphics.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsGraphics.cpp @@ -10,9 +10,9 @@ HRESULT CScene_SettingsGraphics::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bIsPrimaryPad=(ProfileManager.GetPrimaryPad()==m_iPad); MapChildControls(); @@ -139,13 +139,13 @@ HRESULT CScene_SettingsGraphics::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINo if(hObjSource==m_SliderA[SLIDER_SETTINGS_GAMMA].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Gamma,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_GAMMA].SetText(TempString); } else if(hObjSource==m_SliderA[SLIDER_SETTINGS_INTERFACE_OPACITY].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_InterfaceOpacity,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_INTERFACE_OPACITY].SetText(TempString); } @@ -198,7 +198,7 @@ HRESULT CScene_SettingsGraphics::OnControlNavigate(XUIMessageControlNavigate *pC // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -310,7 +310,7 @@ HRESULT CScene_SettingsGraphics::OnTransitionStart( XUIMessageTransition *pTrans HRESULT CScene_SettingsGraphics::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // if we're not in the game, we need to use basescene 0 if(bNotInGame) diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsOptions.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsOptions.cpp index 526847c7c..683ee175e 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsOptions.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsOptions.cpp @@ -26,9 +26,9 @@ int CScene_SettingsOptions::m_iDifficultyTitleSettingA[4]= HRESULT CScene_SettingsOptions::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bPrimaryPlayer = ProfileManager.GetPrimaryPad()==m_iPad; MapChildControls(); @@ -274,14 +274,14 @@ HRESULT CScene_SettingsOptions::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINot else { app.SetAutosaveTimerTime(); - swprintf( (WCHAR *)TempString, 256, L"%ls: %d %ls", app.GetString( IDS_SLIDER_AUTOSAVE ),pNotifyValueChanged->nValue*15, app.GetString( IDS_MINUTES )); + swprintf( static_cast(TempString), 256, L"%ls: %d %ls", app.GetString( IDS_SLIDER_AUTOSAVE ),pNotifyValueChanged->nValue*15, app.GetString( IDS_MINUTES )); } m_SliderA[SLIDER_SETTINGS_AUTOSAVE].SetText(TempString); } else if(hObjSource==m_SliderA[SLIDER_SETTINGS_DIFFICULTY].GetSlider() ) { app.SetGameSettings(m_iPad,eGameSetting_Difficulty,pNotifyValueChanged->nValue); - swprintf( (WCHAR *)TempString, 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pNotifyValueChanged->nValue])); + swprintf( static_cast(TempString), 256, L"%ls: %ls", app.GetString( IDS_SLIDER_DIFFICULTY ),app.GetString(m_iDifficultyTitleSettingA[pNotifyValueChanged->nValue])); m_SliderA[SLIDER_SETTINGS_DIFFICULTY].SetText(TempString); wstring wsText=app.GetString(m_iDifficultySettingA[pNotifyValueChanged->nValue]); @@ -353,7 +353,7 @@ HRESULT CScene_SettingsOptions::OnControlNavigate(XUIMessageControlNavigate *pCo // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -467,7 +467,7 @@ HRESULT CScene_SettingsOptions::OnTransitionStart( XUIMessageTransition *pTransi // Need to refresh the scenes visual since the object size has now changed XuiControlAttachVisual(m_hObj); - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { diff --git a/Minecraft.Client/Common/XUI/XUI_SettingsUI.cpp b/Minecraft.Client/Common/XUI/XUI_SettingsUI.cpp index da95d084d..ab9cc53b4 100644 --- a/Minecraft.Client/Common/XUI/XUI_SettingsUI.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SettingsUI.cpp @@ -10,9 +10,9 @@ HRESULT CScene_SettingsUI::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { WCHAR TempString[256]; - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); bool bPrimaryPlayer = ProfileManager.GetPrimaryPad()==m_iPad; MapChildControls(); @@ -115,7 +115,7 @@ HRESULT CScene_SettingsUI::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotifyVa // slider is 1 to 3 // is this different from the current value? - swprintf( (WCHAR *)TempString, 256, L"%ls: %d", app.GetString( IDS_SLIDER_UISIZE ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d", app.GetString( IDS_SLIDER_UISIZE ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_UISIZE].SetText(TempString); if(pNotifyValueChanged->nValue != app.GetGameSettings(m_iPad,eGameSetting_UISize)+1) { @@ -126,7 +126,7 @@ HRESULT CScene_SettingsUI::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotifyVa } else if(hObjSource==m_SliderA[SLIDER_SETTINGS_UISIZESPLITSCREEN].GetSlider() ) { - swprintf( (WCHAR *)TempString, 256, L"%ls: %d", app.GetString( IDS_SLIDER_UISIZESPLITSCREEN ),pNotifyValueChanged->nValue); + swprintf( static_cast(TempString), 256, L"%ls: %d", app.GetString( IDS_SLIDER_UISIZESPLITSCREEN ),pNotifyValueChanged->nValue); m_SliderA[SLIDER_SETTINGS_UISIZESPLITSCREEN].SetText(TempString); if(pNotifyValueChanged->nValue != app.GetGameSettings(m_iPad,eGameSetting_UISizeSplitscreen)+1) @@ -210,7 +210,7 @@ HRESULT CScene_SettingsUI::OnControlNavigate(XUIMessageControlNavigate *pControl // added so we can skip greyed out items pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest!=NULL) + if(pControlNavigateData->hObjDest!=nullptr) { bHandled=TRUE; } @@ -353,7 +353,7 @@ HRESULT CScene_SettingsUI::OnTransitionStart( XUIMessageTransition *pTransition, HRESULT CScene_SettingsUI::OnNavReturn(HXUIOBJ hObj,BOOL& rfHandled) { - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); // if we're not in the game, we need to use basescene 0 if(bNotInGame) diff --git a/Minecraft.Client/Common/XUI/XUI_SignEntry.cpp b/Minecraft.Client/Common/XUI/XUI_SignEntry.cpp index 378ac147b..963d8f103 100644 --- a/Minecraft.Client/Common/XUI/XUI_SignEntry.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SignEntry.cpp @@ -15,7 +15,7 @@ HRESULT CScene_SignEntry::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) XuiControlSetText(m_ButtonDone,app.GetString(IDS_DONE)); XuiControlSetText(m_labelEditSign,app.GetString(IDS_EDIT_SIGN_MESSAGE)); - SignEntryScreenInput* initData = (SignEntryScreenInput*)pInitData->pvInitData; + SignEntryScreenInput* initData = static_cast(pInitData->pvInitData); m_sign = initData->sign; CXuiSceneBase::ShowDarkOverlay( initData->iPad, TRUE ); @@ -75,9 +75,9 @@ HRESULT CScene_SignEntry::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* p if (pMinecraft->level->isClientSide) { shared_ptr player = pMinecraft->localplayers[pNotifyPressData->UserIndex]; - if(player != NULL && player->connection && player->connection->isStarted()) + if(player != nullptr && player->connection && player->connection->isStarted()) { - player->connection->send( shared_ptr( new SignUpdatePacket(m_sign->x, m_sign->y, m_sign->z, m_sign->IsVerified(), m_sign->IsCensored(), m_sign->GetMessages()) ) ); + player->connection->send(std::make_shared(m_sign->x, m_sign->y, m_sign->z, m_sign->IsVerified(), m_sign->IsCensored(), m_sign->GetMessages())); } } app.CloseXuiScenes(pNotifyPressData->UserIndex); diff --git a/Minecraft.Client/Common/XUI/XUI_SkinSelect.cpp b/Minecraft.Client/Common/XUI/XUI_SkinSelect.cpp index ee7066108..b92159c05 100644 --- a/Minecraft.Client/Common/XUI/XUI_SkinSelect.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SkinSelect.cpp @@ -26,9 +26,9 @@ WCHAR *CScene_SkinSelect::wchDefaultNamesA[]= //---------------------------------------------------------------------------------- HRESULT CScene_SkinSelect::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // if we're not in the game, we need to use basescene 0 - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); m_bIgnoreInput=false; // 4J Stu - Added this so that we have skins loaded @@ -46,7 +46,7 @@ HRESULT CScene_SkinSelect::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) m_skinIndex = 0; m_currentSkinPath = app.GetPlayerSkinName(m_iPad); m_originalSkinId = app.GetPlayerSkinId(m_iPad); - m_currentPack = NULL; + m_currentPack = nullptr; m_bSlidingSkins = false; m_bAnimatingMove = false; currentPackCount = 0; @@ -86,7 +86,7 @@ HRESULT CScene_SkinSelect::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) // Change to display the favorites if there are any. The current skin will be in there (probably) - need to check for it m_currentPack = app.m_dlcManager.getPackContainingSkin(m_currentSkinPath); bool bFound; - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { m_packIndex = app.m_dlcManager.getPackIndex(m_currentPack,bFound,DLCManager::e_DLCType_Skin) + SKIN_SELECT_MAX_DEFAULTS; } @@ -232,7 +232,7 @@ HRESULT CScene_SkinSelect::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandle } break; default: - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { DLCSkinFile *skinFile = m_currentPack->getSkinFile(m_skinIndex); @@ -266,7 +266,7 @@ HRESULT CScene_SkinSelect::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandle DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(m_currentPack->getPurchaseOfferId()); ULONGLONG ullOfferID_Full; - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullOfferID_Full=pDLCInfo->ullOfferID_Full; } @@ -626,8 +626,8 @@ void CScene_SkinSelect::handleSkinIndexChanged() wstring skinOrigin = L""; bool bSkinIsFree=false; bool bLicensed=false; - DLCSkinFile *skinFile=NULL; - DLCPack *Pack=NULL; + DLCSkinFile *skinFile=nullptr; + DLCPack *Pack=nullptr; BYTE sidePreviewControlsL,sidePreviewControlsR; bool bNoSkinsToShow=false; @@ -635,7 +635,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() m_selectedGroup.SetShow( FALSE ); m_skinDetails.SetShow( FALSE ); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(m_skinIndex); m_selectedSkinPath = skinFile->getPath(); @@ -665,7 +665,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() { m_selectedSkinPath = L""; m_selectedCapePath = L""; - m_vAdditionalSkinBoxes = NULL; + m_vAdditionalSkinBoxes = nullptr; switch(m_packIndex) { @@ -753,13 +753,13 @@ void CScene_SkinSelect::handleSkinIndexChanged() { // add the boxes to the humanoid model, but only if we've not done this already vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),m_vAdditionalSkinBoxes); } } - if(skinFile!=NULL) + if(skinFile!=nullptr) { app.SetAnimOverrideBitmask(skinFile->getSkinID(),skinFile->getAnimOverrideBitmask()); } @@ -774,7 +774,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() wstring otherSkinPath = L""; wstring otherCapePath = L""; - vector *othervAdditionalSkinBoxes=NULL; + vector *othervAdditionalSkinBoxes=nullptr; wchar_t chars[256]; // turn off all displays @@ -820,10 +820,10 @@ void CScene_SkinSelect::handleSkinIndexChanged() { if(showNext) { - skinFile=NULL; + skinFile=nullptr; m_previewNextControls[i]->SetShow(TRUE); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(nextIndex); otherSkinPath = skinFile->getPath(); @@ -835,7 +835,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() { otherSkinPath = L""; otherCapePath = L""; - othervAdditionalSkinBoxes=NULL; + othervAdditionalSkinBoxes=nullptr; switch(m_packIndex) { case SKIN_SELECT_PACK_DEFAULT: @@ -867,13 +867,13 @@ void CScene_SkinSelect::handleSkinIndexChanged() if(othervAdditionalSkinBoxes && othervAdditionalSkinBoxes->size()!=0) { vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),othervAdditionalSkinBoxes); } } // 4J-PB - anim override needs set before SetTexture - if(skinFile!=NULL) + if(skinFile!=nullptr) { app.SetAnimOverrideBitmask(skinFile->getSkinID(),skinFile->getAnimOverrideBitmask()); } @@ -892,10 +892,10 @@ void CScene_SkinSelect::handleSkinIndexChanged() { if(showPrevious) { - skinFile=NULL; + skinFile=nullptr; m_previewPreviousControls[i]->SetShow(TRUE); - if( m_currentPack != NULL ) + if( m_currentPack != nullptr ) { skinFile = m_currentPack->getSkinFile(previousIndex); otherSkinPath = skinFile->getPath(); @@ -907,7 +907,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() { otherSkinPath = L""; otherCapePath = L""; - othervAdditionalSkinBoxes=NULL; + othervAdditionalSkinBoxes=nullptr; switch(m_packIndex) { case SKIN_SELECT_PACK_DEFAULT: @@ -939,7 +939,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() if(othervAdditionalSkinBoxes && othervAdditionalSkinBoxes->size()!=0) { vector *pAdditionalModelParts = app.GetAdditionalModelParts(skinFile->getSkinID()); - if(pAdditionalModelParts==NULL) + if(pAdditionalModelParts==nullptr) { pAdditionalModelParts = app.SetAdditionalSkinBoxes(skinFile->getSkinID(),othervAdditionalSkinBoxes); } @@ -957,7 +957,7 @@ void CScene_SkinSelect::handleSkinIndexChanged() } // update the tooltips - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNoSkinsToShow) { @@ -1001,10 +1001,10 @@ void CScene_SkinSelect::handlePackIndexChanged() } else { - m_currentPack = NULL; + m_currentPack = nullptr; } m_skinIndex = 0; - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { bool found; DWORD currentSkinIndex = m_currentPack->getSkinIndexAt(m_currentSkinPath, found); @@ -1021,7 +1021,7 @@ void CScene_SkinSelect::handlePackIndexChanged() DWORD defaultSkinIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(m_originalSkinId); if( ugcSkinIndex == 0 ) { - m_skinIndex = (EDefaultSkins) defaultSkinIndex; + m_skinIndex = static_cast(defaultSkinIndex); } } break; @@ -1199,7 +1199,7 @@ int CScene_SkinSelect::getNextSkinIndex(DWORD sourceIndex) { nextSkin = eDefaultSkins_ServerSelected; } - else if(m_currentPack != NULL && nextSkin>=m_currentPack->getSkinCount()) + else if(m_currentPack != nullptr && nextSkin>=m_currentPack->getSkinCount()) { nextSkin = 0; } @@ -1233,7 +1233,7 @@ int CScene_SkinSelect::getPreviousSkinIndex(DWORD sourceIndex) { previousSkin = eDefaultSkins_Count - 1; } - else if(m_currentPack != NULL) + else if(m_currentPack != nullptr) { previousSkin = m_currentPack->getSkinCount()-1; } @@ -1311,7 +1311,7 @@ void CScene_SkinSelect::updateClipping() int CScene_SkinSelect::UnlockSkinReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CScene_SkinSelect* pScene = (CScene_SkinSelect*)pParam; + CScene_SkinSelect* pScene = static_cast(pParam); #ifdef _XBOX if(result==C4JStorage::EMessage_ResultAccept) { @@ -1320,7 +1320,7 @@ int CScene_SkinSelect::UnlockSkinReturned(void *pParam,int iPad,C4JStorage::EMes ULONGLONG ullIndexA[1]; DLC_INFO *pDLCInfo = app.GetDLCInfoForTrialOfferID(pScene->m_currentPack->getPurchaseOfferId()); - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { ullIndexA[0]=pDLCInfo->ullOfferID_Full; } @@ -1330,13 +1330,13 @@ int CScene_SkinSelect::UnlockSkinReturned(void *pParam,int iPad,C4JStorage::EMes } // If we're in-game, then we need to enable DLC downloads. They'll be set back to Auto on leaving the pause menu - if(Minecraft::GetInstance()->level!=NULL) + if(Minecraft::GetInstance()->level!=nullptr) { // need to allow downloads here, or the player would need to quit the game to let the download of a skin pack happen. This might affect the network traffic, since the download could take all the bandwidth... XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); } - StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); + StorageManager.InstallOffer(1,ullIndexA,nullptr,nullptr); // the license change coming in when the offer has been installed will cause this scene to refresh } @@ -1380,7 +1380,7 @@ HRESULT CScene_SkinSelect::OnCustomMessage_DLCMountingComplete() if(app.m_dlcManager.getPackCount(DLCManager::e_DLCType_Skin)>0) { m_currentPack = app.m_dlcManager.getPackContainingSkin(m_currentSkinPath); - if(m_currentPack != NULL) + if(m_currentPack != nullptr) { bool bFound = false; m_packIndex = app.m_dlcManager.getPackIndex(m_currentPack,bFound,DLCManager::e_DLCType_Skin) + SKIN_SELECT_MAX_DEFAULTS; @@ -1400,7 +1400,7 @@ HRESULT CScene_SkinSelect::OnCustomMessage_DLCMountingComplete() updateCurrentFocus(); m_bIgnoreInput=false; app.m_dlcManager.checkForCorruptDLCAndAlert(); - bool bInGame=(Minecraft::GetInstance()->level!=NULL); + bool bInGame=(Minecraft::GetInstance()->level!=nullptr); if(bInGame) XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_AUTO); diff --git a/Minecraft.Client/Common/XUI/XUI_SocialPost.cpp b/Minecraft.Client/Common/XUI/XUI_SocialPost.cpp index f237e7d87..2bd842638 100644 --- a/Minecraft.Client/Common/XUI/XUI_SocialPost.cpp +++ b/Minecraft.Client/Common/XUI/XUI_SocialPost.cpp @@ -21,7 +21,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_SocialPost::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad = *(int *)pInitData->pvInitData; + m_iPad = *static_cast(pInitData->pvInitData); MapChildControls(); @@ -48,8 +48,8 @@ HRESULT CScene_SocialPost::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) wstring wDesc = m_EditDesc.GetText(); // set the caret to the end of the default text - m_EditCaption.SetCaretPosition((int)wCaption.length()); - m_EditDesc.SetCaretPosition((int)wDesc.length()); + m_EditCaption.SetCaretPosition(static_cast(wCaption.length())); + m_EditDesc.SetCaretPosition(static_cast(wDesc.length())); BOOL bHasAllText = /*( wTitle.length()!=0) && */(wCaption.length()!=0) && (wDesc.length()!=0); @@ -89,7 +89,7 @@ HRESULT CScene_SocialPost::OnControlNavigate(XUIMessageControlNavigate *pControl { pControlNavigateData->hObjDest=XuiControlGetNavigation(pControlNavigateData->hObjSource,pControlNavigateData->nControlNavigate,TRUE,TRUE); - if(pControlNavigateData->hObjDest==NULL) + if(pControlNavigateData->hObjDest==nullptr) { pControlNavigateData->hObjDest=pControlNavigateData->hObjSource; } diff --git a/Minecraft.Client/Common/XUI/XUI_Teleport.cpp b/Minecraft.Client/Common/XUI/XUI_Teleport.cpp index 1d6ac3bf6..bbf0005e9 100644 --- a/Minecraft.Client/Common/XUI/XUI_Teleport.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Teleport.cpp @@ -21,7 +21,7 @@ //---------------------------------------------------------------------------------- HRESULT CScene_Teleport::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - TeleportMenuInitData *initParam = (TeleportMenuInitData *)pInitData->pvInitData; + TeleportMenuInitData *initParam = static_cast(pInitData->pvInitData); m_iPad = initParam->iPad; m_teleportToPlayer = initParam->teleportToPlayer; @@ -51,7 +51,7 @@ HRESULT CScene_Teleport::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { INetworkPlayer *player = g_NetworkManager.GetPlayerByIndex( i ); - if( player != NULL && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) + if( player != nullptr && !(player->IsLocal() && player->GetUserIndex() == m_iPad) ) { m_players[m_playersCount] = player->GetSmallId(); ++m_playersCount; @@ -125,7 +125,7 @@ HRESULT CScene_Teleport::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress* pN void CScene_Teleport::OnPlayerChanged(void *callbackParam, INetworkPlayer *pPlayer, bool leaving) { - CScene_Teleport *scene = (CScene_Teleport *)callbackParam; + CScene_Teleport *scene = static_cast(callbackParam); bool playerFound = false; for(int i = 0; i < scene->m_playersCount; ++i) @@ -167,7 +167,7 @@ HRESULT CScene_Teleport::OnGetSourceDataText(XUIMessageGetSourceText *pGetSource if( pGetSourceTextData->iItem < m_playersCount ) { INetworkPlayer *player = g_NetworkManager.GetPlayerBySmallId( m_players[pGetSourceTextData->iItem] ); - if( player != NULL ) + if( player != nullptr ) { #ifndef _CONTENT_PACKAGE if(app.DebugSettingsOn() && (app.GetGameSettingsDebugMask()&(1L<HasVoice() ) + if(player != nullptr && player->HasVoice() ) { if( player->IsMutedByLocalUser(m_iPad) ) { diff --git a/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp b/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp index 0369928b4..5eff65e8e 100644 --- a/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp +++ b/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp @@ -24,7 +24,7 @@ HRESULT CScene_TextEntry::Init_Commands() HRESULT CScene_TextEntry::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { MapChildControls(); - XuiTextInputParams *params = (XuiTextInputParams *)pInitData->pvInitData; + XuiTextInputParams *params = static_cast(pInitData->pvInitData); m_iPad=params->iPad; m_wchInitialChar=params->wch; delete params; diff --git a/Minecraft.Client/Common/XUI/XUI_TransferToXboxOne.cpp b/Minecraft.Client/Common/XUI/XUI_TransferToXboxOne.cpp index 5a2e67b42..da224f7a3 100644 --- a/Minecraft.Client/Common/XUI/XUI_TransferToXboxOne.cpp +++ b/Minecraft.Client/Common/XUI/XUI_TransferToXboxOne.cpp @@ -16,7 +16,7 @@ HRESULT CScene_TransferToXboxOne::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { m_iX=-1; - m_params = (LoadMenuInitData *)pInitData->pvInitData; + m_params = static_cast(pInitData->pvInitData); m_iPad=m_params->iPad; @@ -26,9 +26,9 @@ HRESULT CScene_TransferToXboxOne::OnInit( XUIMessageInit* pInitData, BOOL& bHand VOID *pObj; XuiObjectFromHandle( m_SavesSlotList, &pObj ); - m_pSavesSlotList = (CXuiCtrl4JList *)pObj; + m_pSavesSlotList = static_cast(pObj); - m_pbImageData=NULL; + m_pbImageData=nullptr; m_dwImageBytes=0; StorageManager.GetSaveCacheFileInfo(m_params->iSaveGameInfoIndex,m_XContentData); @@ -48,7 +48,7 @@ HRESULT CScene_TransferToXboxOne::OnInit( XUIMessageInit* pInitData, BOOL& bHand // saves will be called slot1 to slotx // there will be a details file with the names and png of each slot - m_pbSlotListFile=NULL; + m_pbSlotListFile=nullptr; m_uiSlotListFileBytes=0; if(StorageManager.TMSPP_InFileList(C4JStorage::eGlobalStorage_TitleUser,m_iPad,L"XboxOne/SlotList")) @@ -86,7 +86,7 @@ HRESULT CScene_TransferToXboxOne::OnInit( XUIMessageInit* pInitData, BOOL& bHand //---------------------------------------------------------------------------------- int CScene_TransferToXboxOne::TMSPPWriteReturned(LPVOID pParam,int iPad,int iUserData) { - CScene_TransferToXboxOne* pClass = (CScene_TransferToXboxOne *) pParam; + CScene_TransferToXboxOne* pClass = static_cast(pParam); pClass->m_bWaitingForWrite=false; return 0; @@ -97,13 +97,13 @@ int CScene_TransferToXboxOne::TMSPPWriteReturned(LPVOID pParam,int iPad,int iUse //---------------------------------------------------------------------------------- int CScene_TransferToXboxOne::TMSPPDeleteReturned(LPVOID pParam,int iPad,int iUserData) { - CScene_TransferToXboxOne* pClass = (CScene_TransferToXboxOne *) pParam; + CScene_TransferToXboxOne* pClass = static_cast(pParam); pClass->m_SavesSlotListTimer.SetShow(FALSE); pClass->m_bIgnoreInput=false; // update the slots delete pClass->m_pbSlotListFile; - pClass->m_pbSlotListFile=NULL; + pClass->m_pbSlotListFile=nullptr; pClass->m_uiSlotListFileBytes=0; pClass->m_pSavesSlotList->RemoveAllData(); CXuiCtrl4JList::LIST_ITEM_INFO ListInfo; @@ -129,7 +129,7 @@ int CScene_TransferToXboxOne::TMSPPDeleteReturned(LPVOID pParam,int iPad,int iUs //---------------------------------------------------------------------------------- int CScene_TransferToXboxOne::TMSPPSlotListReturned(LPVOID pParam,int iPad,int iUserData,C4JStorage::PTMSPP_FILEDATA pFileData, LPCSTR szFilename) { - CScene_TransferToXboxOne* pClass = (CScene_TransferToXboxOne *) pParam; + CScene_TransferToXboxOne* pClass = static_cast(pParam); unsigned int uiSlotListFileSlots=*((unsigned int *)pFileData->pbData); pClass->m_pbSlotListFile=pFileData->pbData; pClass->m_uiSlotListFileBytes=pFileData->dwSize; @@ -220,7 +220,7 @@ HRESULT CScene_TransferToXboxOne::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify // check if there is a save there CXuiCtrl4JList::LIST_ITEM_INFO info = m_pSavesSlotList->GetData(iIndex); - if(info.pwszImage!=NULL) + if(info.pwszImage!=nullptr) { // we have a save here // Are you sure, etc. @@ -252,10 +252,10 @@ HRESULT CScene_TransferToXboxOne::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify HRESULT CScene_TransferToXboxOne::BuildSlotFile(int iIndexBeingUpdated,PBYTE pbImageData,DWORD dwImageBytes ) { - SLOTDATA *pCurrentSlotData=NULL; - PBYTE pbCurrentSlotDataPtr=NULL; + SLOTDATA *pCurrentSlotData=nullptr; + PBYTE pbCurrentSlotDataPtr=nullptr; // there may be no slot file yet - if(m_pbSlotListFile!=NULL) + if(m_pbSlotListFile!=nullptr) { pCurrentSlotData=(SLOTDATA *)(m_pbSlotListFile+sizeof(unsigned int)); pbCurrentSlotDataPtr=m_pbSlotListFile + sizeof(unsigned int) + sizeof(SLOTDATA)*m_MaxSlotC; @@ -298,7 +298,7 @@ HRESULT CScene_TransferToXboxOne::BuildSlotFile(int iIndexBeingUpdated,PBYTE pbI } else { - if(pbCurrentSlotDataPtr!=NULL) + if(pbCurrentSlotDataPtr!=nullptr) { memcpy(pbNewSlotImageDataPtr,pbCurrentSlotDataPtr,pCurrentSlotData[i].uiImageLength); pbNewSlotImageDataPtr+=pCurrentSlotData[i].uiImageLength; @@ -307,7 +307,7 @@ HRESULT CScene_TransferToXboxOne::BuildSlotFile(int iIndexBeingUpdated,PBYTE pbI } // move to the next image data in the current slot file - if(pbCurrentSlotDataPtr!=NULL) + if(pbCurrentSlotDataPtr!=nullptr) { pbCurrentSlotDataPtr+=pCurrentSlotData[i].uiImageLength; } @@ -323,7 +323,7 @@ HRESULT CScene_TransferToXboxOne::BuildSlotFile(int iIndexBeingUpdated,PBYTE pbI LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CScene_TransferToXboxOne::UploadSaveForXboxOneThreadProc; - loadingParams->lpParam = (LPVOID)this; + loadingParams->lpParam = static_cast(this); UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); completionData->bShowBackground=TRUE; @@ -342,7 +342,7 @@ int CScene_TransferToXboxOne::UploadSaveForXboxOneThreadProc( LPVOID lpParameter { HRESULT hr = S_OK; char szFilename[32]; - CScene_TransferToXboxOne* pClass = (CScene_TransferToXboxOne *) lpParameter; + CScene_TransferToXboxOne* pClass = static_cast(lpParameter); Minecraft *pMinecraft = Minecraft::GetInstance(); unsigned int uiComplete=0; pClass->m_bWaitingForWrite=true; @@ -415,7 +415,7 @@ int CScene_TransferToXboxOne::UploadSaveForXboxOneThreadProc( LPVOID lpParameter for(int i=0;i<(pClass->m_uiStorageLength/uiChunkSize)+1;i++) { sprintf( szFilename, "XboxOne/Slot%.2d%.2d", pClass->m_uiSlotID,i ); - PCHAR pchData=((PCHAR)pClass->m_pvSaveMem)+i*uiChunkSize; + PCHAR pchData=static_cast(pClass->m_pvSaveMem)+i*uiChunkSize; pClass->m_bWaitingForWrite=true; if(uiBytesLeft>=uiChunkSize) @@ -461,7 +461,7 @@ int CScene_TransferToXboxOne::UploadSaveForXboxOneThreadProc( LPVOID lpParameter int CScene_TransferToXboxOne::LoadSaveDataReturned(void *pParam,bool bContinue) { - CScene_TransferToXboxOne* pClass = (CScene_TransferToXboxOne*)pParam; + CScene_TransferToXboxOne* pClass = static_cast(pParam); if(bContinue==true) { @@ -502,7 +502,7 @@ HRESULT CScene_TransferToXboxOne::OnKeyDown(XUIMessageInput* pInputData, BOOL& r break; case VK_PAD_X: // wipe the save slots - if(m_pbSlotListFile!=NULL) + if(m_pbSlotListFile!=nullptr) { m_SavesSlotListTimer.SetShow(TRUE); m_bIgnoreInput=true; diff --git a/Minecraft.Client/Common/XUI/XUI_TrialExitUpsell.cpp b/Minecraft.Client/Common/XUI/XUI_TrialExitUpsell.cpp index 511210999..d99df9985 100644 --- a/Minecraft.Client/Common/XUI/XUI_TrialExitUpsell.cpp +++ b/Minecraft.Client/Common/XUI/XUI_TrialExitUpsell.cpp @@ -19,7 +19,7 @@ WCHAR *CScene_TrialExitUpsell::wchImages[]= //---------------------------------------------------------------------------------- HRESULT CScene_TrialExitUpsell::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); MapChildControls(); diff --git a/Minecraft.Client/Common/XUI/XUI_TutorialPopup.cpp b/Minecraft.Client/Common/XUI/XUI_TutorialPopup.cpp index 98951d81a..29893d041 100644 --- a/Minecraft.Client/Common/XUI/XUI_TutorialPopup.cpp +++ b/Minecraft.Client/Common/XUI/XUI_TutorialPopup.cpp @@ -14,7 +14,7 @@ HRESULT CScene_TutorialPopup::OnInit( XUIMessageInit* pInitData, BOOL& bHandled { HRESULT hr = S_OK; - tutorial = (Tutorial *)pInitData->pvInitData; + tutorial = static_cast(pInitData->pvInitData); m_iPad = tutorial->getPad(); MapChildControls(); @@ -29,7 +29,7 @@ HRESULT CScene_TutorialPopup::OnInit( XUIMessageInit* pInitData, BOOL& bHandled m_textFontSize = _fromString( m_fontSizeControl.GetText() ); m_fontSizeControl.SetShow(false); - m_interactScene = NULL; + m_interactScene = nullptr; m_lastSceneMovedLeft = false; m_bAllowFade = false; @@ -63,7 +63,7 @@ HRESULT CScene_TutorialPopup::OnTimer(XUIMessageTimer *pData,BOOL& rfHandled) void CScene_TutorialPopup::UpdateInteractScenePosition(bool visible) { - if( m_interactScene == NULL ) return; + if( m_interactScene == nullptr ) return; // 4J-PB - check this players screen section to see if we should allow the animation bool bAllowAnim=false; @@ -146,8 +146,8 @@ HRESULT CScene_TutorialPopup::_SetDescription(CXuiScene *interactScene, LPCWSTR { HRESULT hr = S_OK; m_interactScene = interactScene; - if( interactScene != m_lastInteractSceneMoved ) m_lastInteractSceneMoved = NULL; - if(desc == NULL) + if( interactScene != m_lastInteractSceneMoved ) m_lastInteractSceneMoved = nullptr; + if(desc == nullptr) { SetShow( false ); XuiSetTimer(m_hObj,TUTORIAL_POPUP_MOVE_SCENE_TIMER_ID,TUTORIAL_POPUP_MOVE_SCENE_TIME); @@ -195,7 +195,7 @@ HRESULT CScene_TutorialPopup::_SetDescription(CXuiScene *interactScene, LPCWSTR hr = XuiElementGetPosition( m_title, &titlePos ); BOOL titleShowAtStart = m_title.IsShown(); - if( title != NULL && title[0] != 0 ) + if( title != nullptr && title[0] != 0 ) { m_title.SetText( title ); m_title.SetShow(TRUE); @@ -241,7 +241,7 @@ HRESULT CScene_TutorialPopup::_SetDescription(CXuiScene *interactScene, LPCWSTR SetBounds(fWidth, fHeight + heightDiff); m_description.GetBounds(&fWidth,&fHeight); - m_description.SetBounds(fWidth, (float)(contentDims.nPageHeight + heightDiff)); + m_description.SetBounds(fWidth, static_cast(contentDims.nPageHeight + heightDiff)); } return hr; } @@ -269,7 +269,7 @@ HRESULT CScene_TutorialPopup::SetDescription(int iPad, TutorialPopupInfo *info) parsed = CScene_TutorialPopup::ParseDescription(iPad, parsed); if(parsed.empty()) { - hr = pThis->_SetDescription( info->interactScene, NULL, NULL, info->allowFade, info->isReminder ); + hr = pThis->_SetDescription( info->interactScene, nullptr, nullptr, info->allowFade, info->isReminder ); } else { @@ -289,7 +289,7 @@ wstring CScene_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, LPCWS if( icon != TUTORIAL_NO_ICON ) { bool itemIsFoil = false; - itemIsFoil = (shared_ptr(new ItemInstance(icon,1,iAuxVal)))->isFoil(); + itemIsFoil = (std::make_shared(icon, 1, iAuxVal))->isFoil(); if(!itemIsFoil) itemIsFoil = isFoil; m_pCraftingPic->SetIcon(m_iPad, icon,iAuxVal,1,10,31,false,itemIsFoil); @@ -298,13 +298,13 @@ wstring CScene_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, LPCWS { wstring openTag(L"{*ICON*}"); wstring closeTag(L"{*/ICON*}"); - int iconTagStartPos = (int)temp.find(openTag); - int iconStartPos = iconTagStartPos + (int)openTag.length(); - if( iconTagStartPos > 0 && iconStartPos < (int)temp.length() ) + size_t iconTagStartPos = temp.find(openTag); + size_t iconStartPos = iconTagStartPos + openTag.length(); + if( iconTagStartPos > 0 && iconStartPos < temp.length() ) { - int iconEndPos = (int)temp.find( closeTag, iconStartPos ); + size_t iconEndPos = temp.find(closeTag, iconStartPos); - if(iconEndPos > iconStartPos && iconEndPos < (int)temp.length() ) + if(iconEndPos > iconStartPos && iconEndPos < temp.length() ) { wstring id = temp.substr(iconStartPos, iconEndPos - iconStartPos); @@ -322,7 +322,7 @@ wstring CScene_TutorialPopup::_SetIcon(int icon, int iAuxVal, bool isFoil, LPCWS } bool itemIsFoil = false; - itemIsFoil = (shared_ptr(new ItemInstance(iconId,1,iAuxVal)))->isFoil(); + itemIsFoil = (std::make_shared(iconId, 1, iAuxVal))->isFoil(); if(!itemIsFoil) itemIsFoil = isFoil; m_pCraftingPic->SetIcon(m_iPad, iconId,iAuxVal,1,10,31,false,itemIsFoil); @@ -443,13 +443,13 @@ wstring CScene_TutorialPopup::_SetImage(wstring &desc) wstring openTag(L"{*IMAGE*}"); wstring closeTag(L"{*/IMAGE*}"); - int imageTagStartPos = (int)desc.find(openTag); - int imageStartPos = imageTagStartPos + (int)openTag.length(); - if( imageTagStartPos > 0 && imageStartPos < (int)desc.length() ) + size_t imageTagStartPos = desc.find(openTag); + size_t imageStartPos = imageTagStartPos + openTag.length(); + if( imageTagStartPos > 0 && imageStartPos < desc.length() ) { - int imageEndPos = (int)desc.find( closeTag, imageStartPos ); + size_t imageEndPos = desc.find(closeTag, imageStartPos); - if(imageEndPos > imageStartPos && imageEndPos < (int)desc.length() ) + if(imageEndPos > imageStartPos && imageEndPos < desc.length() ) { wstring id = desc.substr(imageStartPos, imageEndPos - imageStartPos); m_image.SetImagePath( id.c_str() ); @@ -564,7 +564,7 @@ HRESULT CScene_TutorialPopup::SetSceneVisible(int iPad, bool show) if( XuiClassDerivesFrom( objClass, thisClass ) ) { CScene_TutorialPopup *pThis; - hr = XuiObjectFromHandle(hObj, (void **) &pThis); + hr = XuiObjectFromHandle(hObj, static_cast(&pThis)); if (FAILED(hr)) return hr; @@ -593,7 +593,7 @@ bool CScene_TutorialPopup::IsSceneVisible(int iPad) if( XuiClassDerivesFrom( objClass, thisClass ) ) { CScene_TutorialPopup *pThis; - hr = XuiObjectFromHandle(hObj, (void **) &pThis); + hr = XuiObjectFromHandle(hObj, static_cast(&pThis)); if (FAILED(hr)) return false; diff --git a/Minecraft.Client/Common/XUI/XUI_debug.cpp b/Minecraft.Client/Common/XUI/XUI_debug.cpp index 61b818a07..9aee38882 100644 --- a/Minecraft.Client/Common/XUI/XUI_debug.cpp +++ b/Minecraft.Client/Common/XUI/XUI_debug.cpp @@ -50,7 +50,7 @@ LPCWSTR CScene_Debug::m_DebugButtonTextA[eDebugButton_Max+1]= //---------------------------------------------------------------------------------- HRESULT CScene_Debug::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { - m_iPad=*(int *)pInitData->pvInitData; + m_iPad=*static_cast(pInitData->pvInitData); // set text and enable any debug options required int iCheckboxIndex=0; @@ -89,7 +89,7 @@ HRESULT CScene_Debug::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) XuiCreateObject( XUI_CLASS_CHECKBOX, &m_DebugCheckboxDataA[iCheckboxIndex].hXuiObj ); XuiObjectFromHandle( m_DebugCheckboxDataA[iCheckboxIndex].hXuiObj, &m_DebugCheckboxDataA[iCheckboxIndex].pvData ); - pCheckbox = (CXuiCheckbox *)m_DebugCheckboxDataA[iCheckboxIndex].pvData; + pCheckbox = static_cast(m_DebugCheckboxDataA[iCheckboxIndex].pvData); //m_phXuiObjA[iElementIndex] = pCheckbox->m_hObj; pCheckbox->SetText(m_DebugCheckboxTextA[iCheckboxIndex]); pCheckbox->SetShow(TRUE); @@ -139,7 +139,7 @@ HRESULT CScene_Debug::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) XuiCreateObject( XUI_CLASS_BUTTON, &m_DebugButtonDataA[iButtonIndex].hXuiObj ); XuiObjectFromHandle( m_DebugButtonDataA[iButtonIndex].hXuiObj, &m_DebugButtonDataA[iButtonIndex].pvData ); - pButton = (CXuiControl *)m_DebugButtonDataA[iButtonIndex].pvData; + pButton = static_cast(m_DebugButtonDataA[iButtonIndex].pvData); //m_phXuiObjA[iElementIndex] = pCheckbox->m_hObj; pButton->SetText(m_DebugButtonTextA[iButtonIndex]); pButton->SetShow(TRUE); @@ -171,7 +171,7 @@ HRESULT CScene_Debug::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) for(int i=0;i(m_DebugCheckboxDataA[i].pvData); pCheckbox->SetCheck( (uiDebugBitmask&(1<(m_DebugCheckboxDataA[i].pvData); uiDebugBitmask|=pCheckbox->IsChecked()?(1< -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif -#endif -#ifdef DYNAMIC_CRC_TABLE -# define Z_ONCE -#endif - -#include "zutil.h" /* for Z_U4, Z_U8, z_crc_t, and FAR definitions */ - -#ifdef HAVE_S390X_VX -# include "contrib/crc32vx/crc32_vx_hooks.h" -#endif - - /* - A CRC of a message is computed on N braids of words in the message, where - each word consists of W bytes (4 or 8). If N is 3, for example, then three - running sparse CRCs are calculated respectively on each braid, at these - indices in the array of words: 0, 3, 6, ..., 1, 4, 7, ..., and 2, 5, 8, ... - This is done starting at a word boundary, and continues until as many blocks - of N * W bytes as are available have been processed. The results are combined - into a single CRC at the end. For this code, N must be in the range 1..6 and - W must be 4 or 8. The upper limit on N can be increased if desired by adding - more #if blocks, extending the patterns apparent in the code. In addition, - crc32.h would need to be regenerated, if the maximum N value is increased. - - N and W are chosen empirically by benchmarking the execution time on a given - processor. The choices for N and W below were based on testing on Intel Kaby - Lake i7, AMD Ryzen 7, ARM Cortex-A57, Sparc64-VII, PowerPC POWER9, and MIPS64 - Octeon II processors. The Intel, AMD, and ARM processors were all fastest - with N=5, W=8. The Sparc, PowerPC, and MIPS64 were all fastest at N=5, W=4. - They were all tested with either gcc or clang, all using the -O3 optimization - level. Your mileage may vary. - */ - -/* Define N */ -#ifdef Z_TESTN -# define N Z_TESTN -#else -# define N 5 -#endif -#if N < 1 || N > 6 -# error N must be in 1..6 -#endif - -/* - z_crc_t must be at least 32 bits. z_word_t must be at least as long as - z_crc_t. It is assumed here that z_word_t is either 32 bits or 64 bits, and - that bytes are eight bits. - */ - -/* - Define W and the associated z_word_t type. If W is not defined, then a - braided calculation is not used, and the associated tables and code are not - compiled. - */ -#ifdef Z_TESTW -# if Z_TESTW-1 != -1 -# define W Z_TESTW -# endif -#else -# ifdef MAKECRCH -# define W 8 /* required for MAKECRCH */ -# else -# if defined(__x86_64__) || defined(__aarch64__) -# define W 8 -# else -# define W 4 -# endif -# endif -#endif -#ifdef W -# if W == 8 && defined(Z_U8) - typedef Z_U8 z_word_t; -# elif defined(Z_U4) -# undef W -# define W 4 - typedef Z_U4 z_word_t; -# else -# undef W -# endif -#endif - -/* If available, use the ARM processor CRC32 instruction. */ -#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && \ - defined(W) && W == 8 -# define ARMCRC32 -#endif - -#if defined(W) && (!defined(ARMCRC32) || defined(DYNAMIC_CRC_TABLE)) -/* - Swap the bytes in a z_word_t to convert between little and big endian. Any - self-respecting compiler will optimize this to a single machine byte-swap - instruction, if one is available. This assumes that word_t is either 32 bits - or 64 bits. - */ -local z_word_t byte_swap(z_word_t word) { -# if W == 8 - return - (word & 0xff00000000000000) >> 56 | - (word & 0xff000000000000) >> 40 | - (word & 0xff0000000000) >> 24 | - (word & 0xff00000000) >> 8 | - (word & 0xff000000) << 8 | - (word & 0xff0000) << 24 | - (word & 0xff00) << 40 | - (word & 0xff) << 56; -# else /* W == 4 */ - return - (word & 0xff000000) >> 24 | - (word & 0xff0000) >> 8 | - (word & 0xff00) << 8 | - (word & 0xff) << 24; -# endif -} -#endif - -#ifdef DYNAMIC_CRC_TABLE -/* ========================================================================= - * Table of powers of x for combining CRC-32s, filled in by make_crc_table() - * below. - */ - local z_crc_t FAR x2n_table[32]; -#else -/* ========================================================================= - * Tables for byte-wise and braided CRC-32 calculations, and a table of powers - * of x for combining CRC-32s, all made by make_crc_table(). - */ -# include "crc32.h" -#endif - -/* CRC polynomial. */ -#define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */ - -/* - Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, - reflected. For speed, this requires that a not be zero. - */ -local uLong multmodp(uLong a, uLong b) { - uLong m, p; - - m = (uLong)1 << 31; - p = 0; - for (;;) { - if (a & m) { - p ^= b; - if ((a & (m - 1)) == 0) - break; - } - m >>= 1; - b = b & 1 ? (b >> 1) ^ POLY : b >> 1; - } - return p; -} - -/* - Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been - initialized. n must not be negative. - */ -local uLong x2nmodp(z_off64_t n, unsigned k) { - uLong p; - - p = (uLong)1 << 31; /* x^0 == 1 */ - while (n) { - if (n & 1) - p = multmodp(x2n_table[k & 31], p); - n >>= 1; - k++; - } - return p; -} - -#ifdef DYNAMIC_CRC_TABLE -/* ========================================================================= - * Build the tables for byte-wise and braided CRC-32 calculations, and a table - * of powers of x for combining CRC-32s. - */ -local z_crc_t FAR crc_table[256]; -#ifdef W - local z_word_t FAR crc_big_table[256]; - local z_crc_t FAR crc_braid_table[W][256]; - local z_word_t FAR crc_braid_big_table[W][256]; - local void braid(z_crc_t [][256], z_word_t [][256], int, int); -#endif -#ifdef MAKECRCH - local void write_table(FILE *, const z_crc_t FAR *, int); - local void write_table32hi(FILE *, const z_word_t FAR *, int); - local void write_table64(FILE *, const z_word_t FAR *, int); -#endif /* MAKECRCH */ - -/* State for once(). */ -local z_once_t made = Z_ONCE_INIT; - -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x^2+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x - (which is shifting right by one and adding x^32 mod p if the bit shifted out - is a one). We start with the highest power (least significant bit) of q and - repeat for all eight bits of q. - - The table is simply the CRC of all possible eight bit values. This is all the - information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. - */ - -local void make_crc_table(void) { - unsigned i, j, n; - z_crc_t p; - - /* initialize the CRC of bytes tables */ - for (i = 0; i < 256; i++) { - p = i; - for (j = 0; j < 8; j++) - p = p & 1 ? (p >> 1) ^ POLY : p >> 1; - crc_table[i] = p; -#ifdef W - crc_big_table[i] = byte_swap(p); -#endif - } - - /* initialize the x^2^n mod p(x) table */ - p = (z_crc_t)1 << 30; /* x^1 */ - x2n_table[0] = p; - for (n = 1; n < 32; n++) - x2n_table[n] = p = (z_crc_t)multmodp(p, p); - -#ifdef W - /* initialize the braiding tables -- needs x2n_table[] */ - braid(crc_braid_table, crc_braid_big_table, N, W); -#endif - -#ifdef MAKECRCH - { - /* - The crc32.h header file contains tables for both 32-bit and 64-bit - z_word_t's, and so requires a 64-bit type be available. In that case, - z_word_t must be defined to be 64-bits. This code then also generates - and writes out the tables for the case that z_word_t is 32 bits. - */ -#if !defined(W) || W != 8 -# error Need a 64-bit integer type in order to generate crc32.h. -#endif - FILE *out; - int k, n; - z_crc_t ltl[8][256]; - z_word_t big[8][256]; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - - /* write out little-endian CRC table to crc32.h */ - fprintf(out, - "/* crc32.h -- tables for rapid CRC calculation\n" - " * Generated automatically by crc32.c\n */\n" - "\n" - "local const z_crc_t FAR crc_table[] = {\n" - " "); - write_table(out, crc_table, 256); - fprintf(out, - "};\n"); - - /* write out big-endian CRC table for 64-bit z_word_t to crc32.h */ - fprintf(out, - "\n" - "#ifdef W\n" - "\n" - "#if W == 8\n" - "\n" - "local const z_word_t FAR crc_big_table[] = {\n" - " "); - write_table64(out, crc_big_table, 256); - fprintf(out, - "};\n"); - - /* write out big-endian CRC table for 32-bit z_word_t to crc32.h */ - fprintf(out, - "\n" - "#else /* W == 4 */\n" - "\n" - "local const z_word_t FAR crc_big_table[] = {\n" - " "); - write_table32hi(out, crc_big_table, 256); - fprintf(out, - "};\n" - "\n" - "#endif\n"); - - /* write out braid tables for each value of N */ - for (n = 1; n <= 6; n++) { - fprintf(out, - "\n" - "#if N == %d\n", n); - - /* compute braid tables for this N and 64-bit word_t */ - braid(ltl, big, n, 8); - - /* write out braid tables for 64-bit z_word_t to crc32.h */ - fprintf(out, - "\n" - "#if W == 8\n" - "\n" - "local const z_crc_t FAR crc_braid_table[][256] = {\n"); - for (k = 0; k < 8; k++) { - fprintf(out, " {"); - write_table(out, ltl[k], 256); - fprintf(out, "}%s", k < 7 ? ",\n" : ""); - } - fprintf(out, - "};\n" - "\n" - "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); - for (k = 0; k < 8; k++) { - fprintf(out, " {"); - write_table64(out, big[k], 256); - fprintf(out, "}%s", k < 7 ? ",\n" : ""); - } - fprintf(out, - "};\n"); - - /* compute braid tables for this N and 32-bit word_t */ - braid(ltl, big, n, 4); - - /* write out braid tables for 32-bit z_word_t to crc32.h */ - fprintf(out, - "\n" - "#else /* W == 4 */\n" - "\n" - "local const z_crc_t FAR crc_braid_table[][256] = {\n"); - for (k = 0; k < 4; k++) { - fprintf(out, " {"); - write_table(out, ltl[k], 256); - fprintf(out, "}%s", k < 3 ? ",\n" : ""); - } - fprintf(out, - "};\n" - "\n" - "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); - for (k = 0; k < 4; k++) { - fprintf(out, " {"); - write_table32hi(out, big[k], 256); - fprintf(out, "}%s", k < 3 ? ",\n" : ""); - } - fprintf(out, - "};\n" - "\n" - "#endif\n" - "\n" - "#endif\n"); - } - fprintf(out, - "\n" - "#endif\n"); - - /* write out zeros operator table to crc32.h */ - fprintf(out, - "\n" - "local const z_crc_t FAR x2n_table[] = {\n" - " "); - write_table(out, x2n_table, 32); - fprintf(out, - "};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH - -/* - Write the 32-bit values in table[0..k-1] to out, five per line in - hexadecimal separated by commas. - */ -local void write_table(FILE *out, const z_crc_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) - fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", - (unsigned long)(table[n]), - n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); -} - -/* - Write the high 32-bits of each value in table[0..k-1] to out, five per line - in hexadecimal separated by commas. - */ -local void write_table32hi(FILE *out, const z_word_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) - fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", - (unsigned long)(table[n] >> 32), - n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); -} - -/* - Write the 64-bit values in table[0..k-1] to out, three per line in - hexadecimal separated by commas. This assumes that if there is a 64-bit - type, then there is also a long long integer type, and it is at least 64 - bits. If not, then the type cast and format string can be adjusted - accordingly. - */ -local void write_table64(FILE *out, const z_word_t FAR *table, int k) { - int n; - - for (n = 0; n < k; n++) - fprintf(out, "%s0x%016llx%s", n == 0 || n % 3 ? "" : " ", - (unsigned long long)(table[n]), - n == k - 1 ? "" : (n % 3 == 2 ? ",\n" : ", ")); -} - -/* Actually do the deed. */ -int main(void) { - make_crc_table(); - return 0; -} - -#endif /* MAKECRCH */ - -#ifdef W -/* - Generate the little and big-endian braid tables for the given n and z_word_t - size w. Each array must have room for w blocks of 256 elements. - */ -local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) { - int k; - z_crc_t i, p, q; - for (k = 0; k < w; k++) { - p = (z_crc_t)x2nmodp((n * w + 3 - k) << 3, 0); - ltl[k][0] = 0; - big[w - 1 - k][0] = 0; - for (i = 1; i < 256; i++) { - ltl[k][i] = q = (z_crc_t)multmodp(i << 24, p); - big[w - 1 - k][i] = byte_swap(q); - } - } -} -#endif - -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32(), and to force the - * generation of the CRC tables in a threaded application. - */ -const z_crc_t FAR * ZEXPORT get_crc_table(void) { -#ifdef DYNAMIC_CRC_TABLE - z_once(&made, make_crc_table); -#endif /* DYNAMIC_CRC_TABLE */ - return (const z_crc_t FAR *)crc_table; -} - -/* ========================================================================= - * Use ARM machine instructions if available. This will compute the CRC about - * ten times faster than the braided calculation. This code does not check for - * the presence of the CRC instruction at run time. __ARM_FEATURE_CRC32 will - * only be defined if the compilation specifies an ARM processor architecture - * that has the instructions. For example, compiling with -march=armv8.1-a or - * -march=armv8-a+crc, or -march=native if the compile machine has the crc32 - * instructions. - */ -#ifdef ARMCRC32 - -/* - Constants empirically determined to maximize speed. These values are from - measurements on a Cortex-A57. Your mileage may vary. - */ -#define Z_BATCH 3990 /* number of words in a batch */ -#define Z_BATCH_ZEROS 0xa10d3d0c /* computed from Z_BATCH = 3990 */ -#define Z_BATCH_MIN 800 /* fewest words in a final batch */ - -uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) { - uLong val; - z_word_t crc1, crc2; - const z_word_t *word; - z_word_t val0, val1, val2; - z_size_t last, last2, i; - z_size_t num; - - /* Return initial CRC, if requested. */ - if (buf == Z_NULL) return 0; - -#ifdef DYNAMIC_CRC_TABLE - z_once(&made, make_crc_table); -#endif /* DYNAMIC_CRC_TABLE */ - - /* Pre-condition the CRC */ - crc = (~crc) & 0xffffffff; - - /* Compute the CRC up to a word boundary. */ - while (len && ((z_size_t)buf & 7) != 0) { - len--; - val = *buf++; - __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); - } - - /* Prepare to compute the CRC on full 64-bit words word[0..num-1]. */ - word = (z_word_t const *)buf; - num = len >> 3; - len &= 7; - - /* Do three interleaved CRCs to realize the throughput of one crc32x - instruction per cycle. Each CRC is calculated on Z_BATCH words. The - three CRCs are combined into a single CRC after each set of batches. */ - while (num >= 3 * Z_BATCH) { - crc1 = 0; - crc2 = 0; - for (i = 0; i < Z_BATCH; i++) { - val0 = word[i]; - val1 = word[i + Z_BATCH]; - val2 = word[i + 2 * Z_BATCH]; - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); - } - word += 3 * Z_BATCH; - num -= 3 * Z_BATCH; - crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc1; - crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc2; - } - - /* Do one last smaller batch with the remaining words, if there are enough - to pay for the combination of CRCs. */ - last = num / 3; - if (last >= Z_BATCH_MIN) { - last2 = last << 1; - crc1 = 0; - crc2 = 0; - for (i = 0; i < last; i++) { - val0 = word[i]; - val1 = word[i + last]; - val2 = word[i + last2]; - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); - } - word += 3 * last; - num -= 3 * last; - val = x2nmodp((int)last, 6); - crc = multmodp(val, crc) ^ crc1; - crc = multmodp(val, crc) ^ crc2; - } - - /* Compute the CRC on any remaining words. */ - for (i = 0; i < num; i++) { - val0 = word[i]; - __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); - } - word += num; - - /* Complete the CRC on any remaining bytes. */ - buf = (const unsigned char FAR *)word; - while (len) { - len--; - val = *buf++; - __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); - } - - /* Return the CRC, post-conditioned. */ - return crc ^ 0xffffffff; -} - -#else - -#ifdef W - -/* - Return the CRC of the W bytes in the word_t data, taking the - least-significant byte of the word as the first byte of data, without any pre - or post conditioning. This is used to combine the CRCs of each braid. - */ -local z_crc_t crc_word(z_word_t data) { - int k; - for (k = 0; k < W; k++) - data = (data >> 8) ^ crc_table[data & 0xff]; - return (z_crc_t)data; -} - -local z_word_t crc_word_big(z_word_t data) { - int k; - for (k = 0; k < W; k++) - data = (data << 8) ^ - crc_big_table[(data >> ((W - 1) << 3)) & 0xff]; - return data; -} - -#endif - -/* ========================================================================= */ -uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) { - /* Return initial CRC, if requested. */ - if (buf == Z_NULL) return 0; - -#ifdef DYNAMIC_CRC_TABLE - z_once(&made, make_crc_table); -#endif /* DYNAMIC_CRC_TABLE */ - - /* Pre-condition the CRC */ - crc = (~crc) & 0xffffffff; - -#ifdef W - - /* If provided enough bytes, do a braided CRC calculation. */ - if (len >= N * W + W - 1) { - z_size_t blks; - z_word_t const *words; - unsigned endian; - int k; - - /* Compute the CRC up to a z_word_t boundary. */ - while (len && ((z_size_t)buf & (W - 1)) != 0) { - len--; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - } - - /* Compute the CRC on as many N z_word_t blocks as are available. */ - blks = len / (N * W); - len -= blks * N * W; - words = (z_word_t const *)buf; - - /* Do endian check at execution time instead of compile time, since ARM - processors can change the endianness at execution time. If the - compiler knows what the endianness will be, it can optimize out the - check and the unused branch. */ - endian = 1; - if (*(unsigned char *)&endian) { - /* Little endian. */ - - z_crc_t crc0; - z_word_t word0; -#if N > 1 - z_crc_t crc1; - z_word_t word1; -#if N > 2 - z_crc_t crc2; - z_word_t word2; -#if N > 3 - z_crc_t crc3; - z_word_t word3; -#if N > 4 - z_crc_t crc4; - z_word_t word4; -#if N > 5 - z_crc_t crc5; - z_word_t word5; -#endif -#endif -#endif -#endif -#endif - - /* Initialize the CRC for each braid. */ - crc0 = crc; -#if N > 1 - crc1 = 0; -#if N > 2 - crc2 = 0; -#if N > 3 - crc3 = 0; -#if N > 4 - crc4 = 0; -#if N > 5 - crc5 = 0; -#endif -#endif -#endif -#endif -#endif - - /* - Process the first blks-1 blocks, computing the CRCs on each braid - independently. - */ - while (--blks) { - /* Load the word for each braid into registers. */ - word0 = crc0 ^ words[0]; -#if N > 1 - word1 = crc1 ^ words[1]; -#if N > 2 - word2 = crc2 ^ words[2]; -#if N > 3 - word3 = crc3 ^ words[3]; -#if N > 4 - word4 = crc4 ^ words[4]; -#if N > 5 - word5 = crc5 ^ words[5]; -#endif -#endif -#endif -#endif -#endif - words += N; - - /* Compute and update the CRC for each word. The loop should - get unrolled. */ - crc0 = crc_braid_table[0][word0 & 0xff]; -#if N > 1 - crc1 = crc_braid_table[0][word1 & 0xff]; -#if N > 2 - crc2 = crc_braid_table[0][word2 & 0xff]; -#if N > 3 - crc3 = crc_braid_table[0][word3 & 0xff]; -#if N > 4 - crc4 = crc_braid_table[0][word4 & 0xff]; -#if N > 5 - crc5 = crc_braid_table[0][word5 & 0xff]; -#endif -#endif -#endif -#endif -#endif - for (k = 1; k < W; k++) { - crc0 ^= crc_braid_table[k][(word0 >> (k << 3)) & 0xff]; -#if N > 1 - crc1 ^= crc_braid_table[k][(word1 >> (k << 3)) & 0xff]; -#if N > 2 - crc2 ^= crc_braid_table[k][(word2 >> (k << 3)) & 0xff]; -#if N > 3 - crc3 ^= crc_braid_table[k][(word3 >> (k << 3)) & 0xff]; -#if N > 4 - crc4 ^= crc_braid_table[k][(word4 >> (k << 3)) & 0xff]; -#if N > 5 - crc5 ^= crc_braid_table[k][(word5 >> (k << 3)) & 0xff]; -#endif -#endif -#endif -#endif -#endif - } - } - - /* - Process the last block, combining the CRCs of the N braids at the - same time. - */ - crc = crc_word(crc0 ^ words[0]); -#if N > 1 - crc = crc_word(crc1 ^ words[1] ^ crc); -#if N > 2 - crc = crc_word(crc2 ^ words[2] ^ crc); -#if N > 3 - crc = crc_word(crc3 ^ words[3] ^ crc); -#if N > 4 - crc = crc_word(crc4 ^ words[4] ^ crc); -#if N > 5 - crc = crc_word(crc5 ^ words[5] ^ crc); -#endif -#endif -#endif -#endif -#endif - words += N; - } - else { - /* Big endian. */ - - z_word_t crc0, word0, comb; -#if N > 1 - z_word_t crc1, word1; -#if N > 2 - z_word_t crc2, word2; -#if N > 3 - z_word_t crc3, word3; -#if N > 4 - z_word_t crc4, word4; -#if N > 5 - z_word_t crc5, word5; -#endif -#endif -#endif -#endif -#endif - - /* Initialize the CRC for each braid. */ - crc0 = byte_swap(crc); -#if N > 1 - crc1 = 0; -#if N > 2 - crc2 = 0; -#if N > 3 - crc3 = 0; -#if N > 4 - crc4 = 0; -#if N > 5 - crc5 = 0; -#endif -#endif -#endif -#endif -#endif - - /* - Process the first blks-1 blocks, computing the CRCs on each braid - independently. - */ - while (--blks) { - /* Load the word for each braid into registers. */ - word0 = crc0 ^ words[0]; -#if N > 1 - word1 = crc1 ^ words[1]; -#if N > 2 - word2 = crc2 ^ words[2]; -#if N > 3 - word3 = crc3 ^ words[3]; -#if N > 4 - word4 = crc4 ^ words[4]; -#if N > 5 - word5 = crc5 ^ words[5]; -#endif -#endif -#endif -#endif -#endif - words += N; - - /* Compute and update the CRC for each word. The loop should - get unrolled. */ - crc0 = crc_braid_big_table[0][word0 & 0xff]; -#if N > 1 - crc1 = crc_braid_big_table[0][word1 & 0xff]; -#if N > 2 - crc2 = crc_braid_big_table[0][word2 & 0xff]; -#if N > 3 - crc3 = crc_braid_big_table[0][word3 & 0xff]; -#if N > 4 - crc4 = crc_braid_big_table[0][word4 & 0xff]; -#if N > 5 - crc5 = crc_braid_big_table[0][word5 & 0xff]; -#endif -#endif -#endif -#endif -#endif - for (k = 1; k < W; k++) { - crc0 ^= crc_braid_big_table[k][(word0 >> (k << 3)) & 0xff]; -#if N > 1 - crc1 ^= crc_braid_big_table[k][(word1 >> (k << 3)) & 0xff]; -#if N > 2 - crc2 ^= crc_braid_big_table[k][(word2 >> (k << 3)) & 0xff]; -#if N > 3 - crc3 ^= crc_braid_big_table[k][(word3 >> (k << 3)) & 0xff]; -#if N > 4 - crc4 ^= crc_braid_big_table[k][(word4 >> (k << 3)) & 0xff]; -#if N > 5 - crc5 ^= crc_braid_big_table[k][(word5 >> (k << 3)) & 0xff]; -#endif -#endif -#endif -#endif -#endif - } - } - - /* - Process the last block, combining the CRCs of the N braids at the - same time. - */ - comb = crc_word_big(crc0 ^ words[0]); -#if N > 1 - comb = crc_word_big(crc1 ^ words[1] ^ comb); -#if N > 2 - comb = crc_word_big(crc2 ^ words[2] ^ comb); -#if N > 3 - comb = crc_word_big(crc3 ^ words[3] ^ comb); -#if N > 4 - comb = crc_word_big(crc4 ^ words[4] ^ comb); -#if N > 5 - comb = crc_word_big(crc5 ^ words[5] ^ comb); -#endif -#endif -#endif -#endif -#endif - words += N; - crc = byte_swap(comb); - } - - /* - Update the pointer to the remaining bytes to process. - */ - buf = (unsigned char const *)words; - } - -#endif /* W */ - - /* Complete the computation of the CRC on any remaining bytes. */ - while (len >= 8) { - len -= 8; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - } - while (len) { - len--; - crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; - } - - /* Return the CRC, post-conditioned. */ - return crc ^ 0xffffffff; -} - -#endif - -/* ========================================================================= */ -uLong ZEXPORT crc32(uLong crc, const unsigned char FAR *buf, uInt len) { - #ifdef HAVE_S390X_VX - return crc32_z_hook(crc, buf, len); - #endif - return crc32_z(crc, buf, len); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine_gen64(z_off64_t len2) { - if (len2 < 0) - return 0; -#ifdef DYNAMIC_CRC_TABLE - z_once(&made, make_crc_table); -#endif /* DYNAMIC_CRC_TABLE */ - return x2nmodp(len2, 3); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine_gen(z_off_t len2) { - return crc32_combine_gen64((z_off64_t)len2); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) { - if (op == 0) - return 0; - return multmodp(op, crc1 & 0xffffffff) ^ (crc2 & 0xffffffff); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) { - return crc32_combine_op(crc1, crc2, crc32_combine_gen64(len2)); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) { - return crc32_combine64(crc1, crc2, (z_off64_t)len2); -} +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2026 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * This interleaved implementation of a CRC makes use of pipelined multiple + * arithmetic-logic units, commonly found in modern CPU cores. It is due to + * Kadatch and Jenkins (2010). See doc/crc-doc.1.0.pdf in this distribution. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + MAKECRCH can be #defined to write out crc32.h. A main() routine is also + produced, so that this one source file can be compiled to an executable. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif +#endif +#ifdef DYNAMIC_CRC_TABLE +# define Z_ONCE +#endif + +#include "zutil.h" /* for Z_U4, Z_U8, z_crc_t, and FAR definitions */ + +#ifdef HAVE_S390X_VX +# include "contrib/crc32vx/crc32_vx_hooks.h" +#endif + + /* + A CRC of a message is computed on N braids of words in the message, where + each word consists of W bytes (4 or 8). If N is 3, for example, then three + running sparse CRCs are calculated respectively on each braid, at these + indices in the array of words: 0, 3, 6, ..., 1, 4, 7, ..., and 2, 5, 8, ... + This is done starting at a word boundary, and continues until as many blocks + of N * W bytes as are available have been processed. The results are combined + into a single CRC at the end. For this code, N must be in the range 1..6 and + W must be 4 or 8. The upper limit on N can be increased if desired by adding + more #if blocks, extending the patterns apparent in the code. In addition, + crc32.h would need to be regenerated, if the maximum N value is increased. + + N and W are chosen empirically by benchmarking the execution time on a given + processor. The choices for N and W below were based on testing on Intel Kaby + Lake i7, AMD Ryzen 7, ARM Cortex-A57, Sparc64-VII, PowerPC POWER9, and MIPS64 + Octeon II processors. The Intel, AMD, and ARM processors were all fastest + with N=5, W=8. The Sparc, PowerPC, and MIPS64 were all fastest at N=5, W=4. + They were all tested with either gcc or clang, all using the -O3 optimization + level. Your mileage may vary. + */ + +/* Define N */ +#ifdef Z_TESTN +# define N Z_TESTN +#else +# define N 5 +#endif +#if N < 1 || N > 6 +# error N must be in 1..6 +#endif + +/* + z_crc_t must be at least 32 bits. z_word_t must be at least as long as + z_crc_t. It is assumed here that z_word_t is either 32 bits or 64 bits, and + that bytes are eight bits. + */ + +/* + Define W and the associated z_word_t type. If W is not defined, then a + braided calculation is not used, and the associated tables and code are not + compiled. + */ +#ifdef Z_TESTW +# if Z_TESTW-1 != -1 +# define W Z_TESTW +# endif +#else +# ifdef MAKECRCH +# define W 8 /* required for MAKECRCH */ +# else +# if defined(__x86_64__) || defined(__aarch64__) +# define W 8 +# else +# define W 4 +# endif +# endif +#endif +#ifdef W +# if W == 8 && defined(Z_U8) + typedef Z_U8 z_word_t; +# elif defined(Z_U4) +# undef W +# define W 4 + typedef Z_U4 z_word_t; +# else +# undef W +# endif +#endif + +/* If available, use the ARM processor CRC32 instruction. */ +#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && \ + defined(W) && W == 8 +# define ARMCRC32 +#endif + +#if defined(W) && (!defined(ARMCRC32) || defined(DYNAMIC_CRC_TABLE)) +/* + Swap the bytes in a z_word_t to convert between little and big endian. Any + self-respecting compiler will optimize this to a single machine byte-swap + instruction, if one is available. This assumes that word_t is either 32 bits + or 64 bits. + */ +local z_word_t byte_swap(z_word_t word) { +# if W == 8 + return + (word & 0xff00000000000000) >> 56 | + (word & 0xff000000000000) >> 40 | + (word & 0xff0000000000) >> 24 | + (word & 0xff00000000) >> 8 | + (word & 0xff000000) << 8 | + (word & 0xff0000) << 24 | + (word & 0xff00) << 40 | + (word & 0xff) << 56; +# else /* W == 4 */ + return + (word & 0xff000000) >> 24 | + (word & 0xff0000) >> 8 | + (word & 0xff00) << 8 | + (word & 0xff) << 24; +# endif +} +#endif + +#ifdef DYNAMIC_CRC_TABLE +/* ========================================================================= + * Table of powers of x for combining CRC-32s, filled in by make_crc_table() + * below. + */ + local z_crc_t FAR x2n_table[32]; +#else +/* ========================================================================= + * Tables for byte-wise and braided CRC-32 calculations, and a table of powers + * of x for combining CRC-32s, all made by make_crc_table(). + */ +# include "crc32.h" +#endif + +/* CRC polynomial. */ +#define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */ + +/* + Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, + reflected. For speed, this requires that a not be zero. + */ +local uLong multmodp(uLong a, uLong b) { + uLong m, p; + + m = (uLong)1 << 31; + p = 0; + for (;;) { + if (a & m) { + p ^= b; + if ((a & (m - 1)) == 0) + break; + } + m >>= 1; + b = b & 1 ? (b >> 1) ^ POLY : b >> 1; + } + return p; +} + +/* + Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been + initialized. n must not be negative. + */ +local uLong x2nmodp(z_off64_t n, unsigned k) { + uLong p; + + p = (uLong)1 << 31; /* x^0 == 1 */ + while (n) { + if (n & 1) + p = multmodp(x2n_table[k & 31], p); + n >>= 1; + k++; + } + return p; +} + +#ifdef DYNAMIC_CRC_TABLE +/* ========================================================================= + * Build the tables for byte-wise and braided CRC-32 calculations, and a table + * of powers of x for combining CRC-32s. + */ +local z_crc_t FAR crc_table[256]; +#ifdef W + local z_word_t FAR crc_big_table[256]; + local z_crc_t FAR crc_braid_table[W][256]; + local z_word_t FAR crc_braid_big_table[W][256]; + local void braid(z_crc_t [][256], z_word_t [][256], int, int); +#endif +#ifdef MAKECRCH + local void write_table(FILE *, const z_crc_t FAR *, int); + local void write_table32hi(FILE *, const z_word_t FAR *, int); + local void write_table64(FILE *, const z_word_t FAR *, int); +#endif /* MAKECRCH */ + +/* State for once(). */ +local z_once_t made = Z_ONCE_INIT; + +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x^2+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x + (which is shifting right by one and adding x^32 mod p if the bit shifted out + is a one). We start with the highest power (least significant bit) of q and + repeat for all eight bits of q. + + The table is simply the CRC of all possible eight bit values. This is all the + information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. + */ + +local void make_crc_table(void) { + unsigned i, j, n; + z_crc_t p; + + /* initialize the CRC of bytes tables */ + for (i = 0; i < 256; i++) { + p = i; + for (j = 0; j < 8; j++) + p = p & 1 ? (p >> 1) ^ POLY : p >> 1; + crc_table[i] = p; +#ifdef W + crc_big_table[i] = byte_swap(p); +#endif + } + + /* initialize the x^2^n mod p(x) table */ + p = (z_crc_t)1 << 30; /* x^1 */ + x2n_table[0] = p; + for (n = 1; n < 32; n++) + x2n_table[n] = p = (z_crc_t)multmodp(p, p); + +#ifdef W + /* initialize the braiding tables -- needs x2n_table[] */ + braid(crc_braid_table, crc_braid_big_table, N, W); +#endif + +#ifdef MAKECRCH + { + /* + The crc32.h header file contains tables for both 32-bit and 64-bit + z_word_t's, and so requires a 64-bit type be available. In that case, + z_word_t must be defined to be 64-bits. This code then also generates + and writes out the tables for the case that z_word_t is 32 bits. + */ +#if !defined(W) || W != 8 +# error Need a 64-bit integer type in order to generate crc32.h. +#endif + FILE *out; + int k, n; + z_crc_t ltl[8][256]; + z_word_t big[8][256]; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + + /* write out little-endian CRC table to crc32.h */ + fprintf(out, + "/* crc32.h -- tables for rapid CRC calculation\n" + " * Generated automatically by crc32.c\n */\n" + "\n" + "local const z_crc_t FAR crc_table[] = {\n" + " "); + write_table(out, crc_table, 256); + fprintf(out, + "};\n"); + + /* write out big-endian CRC table for 64-bit z_word_t to crc32.h */ + fprintf(out, + "\n" + "#ifdef W\n" + "\n" + "#if W == 8\n" + "\n" + "local const z_word_t FAR crc_big_table[] = {\n" + " "); + write_table64(out, crc_big_table, 256); + fprintf(out, + "};\n"); + + /* write out big-endian CRC table for 32-bit z_word_t to crc32.h */ + fprintf(out, + "\n" + "#else /* W == 4 */\n" + "\n" + "local const z_word_t FAR crc_big_table[] = {\n" + " "); + write_table32hi(out, crc_big_table, 256); + fprintf(out, + "};\n" + "\n" + "#endif\n"); + + /* write out braid tables for each value of N */ + for (n = 1; n <= 6; n++) { + fprintf(out, + "\n" + "#if N == %d\n", n); + + /* compute braid tables for this N and 64-bit word_t */ + braid(ltl, big, n, 8); + + /* write out braid tables for 64-bit z_word_t to crc32.h */ + fprintf(out, + "\n" + "#if W == 8\n" + "\n" + "local const z_crc_t FAR crc_braid_table[][256] = {\n"); + for (k = 0; k < 8; k++) { + fprintf(out, " {"); + write_table(out, ltl[k], 256); + fprintf(out, "}%s", k < 7 ? ",\n" : ""); + } + fprintf(out, + "};\n" + "\n" + "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); + for (k = 0; k < 8; k++) { + fprintf(out, " {"); + write_table64(out, big[k], 256); + fprintf(out, "}%s", k < 7 ? ",\n" : ""); + } + fprintf(out, + "};\n"); + + /* compute braid tables for this N and 32-bit word_t */ + braid(ltl, big, n, 4); + + /* write out braid tables for 32-bit z_word_t to crc32.h */ + fprintf(out, + "\n" + "#else /* W == 4 */\n" + "\n" + "local const z_crc_t FAR crc_braid_table[][256] = {\n"); + for (k = 0; k < 4; k++) { + fprintf(out, " {"); + write_table(out, ltl[k], 256); + fprintf(out, "}%s", k < 3 ? ",\n" : ""); + } + fprintf(out, + "};\n" + "\n" + "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); + for (k = 0; k < 4; k++) { + fprintf(out, " {"); + write_table32hi(out, big[k], 256); + fprintf(out, "}%s", k < 3 ? ",\n" : ""); + } + fprintf(out, + "};\n" + "\n" + "#endif\n" + "\n" + "#endif\n"); + } + fprintf(out, + "\n" + "#endif\n"); + + /* write out zeros operator table to crc32.h */ + fprintf(out, + "\n" + "local const z_crc_t FAR x2n_table[] = {\n" + " "); + write_table(out, x2n_table, 32); + fprintf(out, + "};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH + +/* + Write the 32-bit values in table[0..k-1] to out, five per line in + hexadecimal separated by commas. + */ +local void write_table(FILE *out, const z_crc_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) + fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); +} + +/* + Write the high 32-bits of each value in table[0..k-1] to out, five per line + in hexadecimal separated by commas. + */ +local void write_table32hi(FILE *out, const z_word_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) + fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", + (unsigned long)(table[n] >> 32), + n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); +} + +/* + Write the 64-bit values in table[0..k-1] to out, three per line in + hexadecimal separated by commas. This assumes that if there is a 64-bit + type, then there is also a long long integer type, and it is at least 64 + bits. If not, then the type cast and format string can be adjusted + accordingly. + */ +local void write_table64(FILE *out, const z_word_t FAR *table, int k) { + int n; + + for (n = 0; n < k; n++) + fprintf(out, "%s0x%016llx%s", n == 0 || n % 3 ? "" : " ", + (unsigned long long)(table[n]), + n == k - 1 ? "" : (n % 3 == 2 ? ",\n" : ", ")); +} + +/* Actually do the deed. */ +int main(void) { + make_crc_table(); + return 0; +} + +#endif /* MAKECRCH */ + +#ifdef W +/* + Generate the little and big-endian braid tables for the given n and z_word_t + size w. Each array must have room for w blocks of 256 elements. + */ +local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) { + int k; + z_crc_t i, p, q; + for (k = 0; k < w; k++) { + p = (z_crc_t)x2nmodp((n * w + 3 - k) << 3, 0); + ltl[k][0] = 0; + big[w - 1 - k][0] = 0; + for (i = 1; i < 256; i++) { + ltl[k][i] = q = (z_crc_t)multmodp(i << 24, p); + big[w - 1 - k][i] = byte_swap(q); + } + } +} +#endif + +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32(), and to force the + * generation of the CRC tables in a threaded application. + */ +const z_crc_t FAR * ZEXPORT get_crc_table(void) { +#ifdef DYNAMIC_CRC_TABLE + z_once(&made, make_crc_table); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= + * Use ARM machine instructions if available. This will compute the CRC about + * ten times faster than the braided calculation. This code does not check for + * the presence of the CRC instruction at run time. __ARM_FEATURE_CRC32 will + * only be defined if the compilation specifies an ARM processor architecture + * that has the instructions. For example, compiling with -march=armv8.1-a or + * -march=armv8-a+crc, or -march=native if the compile machine has the crc32 + * instructions. + */ +#ifdef ARMCRC32 + +/* + Constants empirically determined to maximize speed. These values are from + measurements on a Cortex-A57. Your mileage may vary. + */ +#define Z_BATCH 3990 /* number of words in a batch */ +#define Z_BATCH_ZEROS 0xa10d3d0c /* computed from Z_BATCH = 3990 */ +#define Z_BATCH_MIN 800 /* fewest words in a final batch */ + +uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) { + uLong val; + z_word_t crc1, crc2; + const z_word_t *word; + z_word_t val0, val1, val2; + z_size_t last, last2, i; + z_size_t num; + + /* Return initial CRC, if requested. */ + if (buf == Z_NULL) return 0; + +#ifdef DYNAMIC_CRC_TABLE + z_once(&made, make_crc_table); +#endif /* DYNAMIC_CRC_TABLE */ + + /* Pre-condition the CRC */ + crc = (~crc) & 0xffffffff; + + /* Compute the CRC up to a word boundary. */ + while (len && ((z_size_t)buf & 7) != 0) { + len--; + val = *buf++; + __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); + } + + /* Prepare to compute the CRC on full 64-bit words word[0..num-1]. */ + word = (z_word_t const *)buf; + num = len >> 3; + len &= 7; + + /* Do three interleaved CRCs to realize the throughput of one crc32x + instruction per cycle. Each CRC is calculated on Z_BATCH words. The + three CRCs are combined into a single CRC after each set of batches. */ + while (num >= 3 * Z_BATCH) { + crc1 = 0; + crc2 = 0; + for (i = 0; i < Z_BATCH; i++) { + val0 = word[i]; + val1 = word[i + Z_BATCH]; + val2 = word[i + 2 * Z_BATCH]; + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); + } + word += 3 * Z_BATCH; + num -= 3 * Z_BATCH; + crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc1; + crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc2; + } + + /* Do one last smaller batch with the remaining words, if there are enough + to pay for the combination of CRCs. */ + last = num / 3; + if (last >= Z_BATCH_MIN) { + last2 = last << 1; + crc1 = 0; + crc2 = 0; + for (i = 0; i < last; i++) { + val0 = word[i]; + val1 = word[i + last]; + val2 = word[i + last2]; + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); + } + word += 3 * last; + num -= 3 * last; + val = x2nmodp((int)last, 6); + crc = multmodp(val, crc) ^ crc1; + crc = multmodp(val, crc) ^ crc2; + } + + /* Compute the CRC on any remaining words. */ + for (i = 0; i < num; i++) { + val0 = word[i]; + __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); + } + word += num; + + /* Complete the CRC on any remaining bytes. */ + buf = (const unsigned char FAR *)word; + while (len) { + len--; + val = *buf++; + __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); + } + + /* Return the CRC, post-conditioned. */ + return crc ^ 0xffffffff; +} + +#else + +#ifdef W + +/* + Return the CRC of the W bytes in the word_t data, taking the + least-significant byte of the word as the first byte of data, without any pre + or post conditioning. This is used to combine the CRCs of each braid. + */ +local z_crc_t crc_word(z_word_t data) { + int k; + for (k = 0; k < W; k++) + data = (data >> 8) ^ crc_table[data & 0xff]; + return (z_crc_t)data; +} + +local z_word_t crc_word_big(z_word_t data) { + int k; + for (k = 0; k < W; k++) + data = (data << 8) ^ + crc_big_table[(data >> ((W - 1) << 3)) & 0xff]; + return data; +} + +#endif + +/* ========================================================================= */ +uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) { + /* Return initial CRC, if requested. */ + if (buf == Z_NULL) return 0; + +#ifdef DYNAMIC_CRC_TABLE + z_once(&made, make_crc_table); +#endif /* DYNAMIC_CRC_TABLE */ + + /* Pre-condition the CRC */ + crc = (~crc) & 0xffffffff; + +#ifdef W + + /* If provided enough bytes, do a braided CRC calculation. */ + if (len >= N * W + W - 1) { + z_size_t blks; + z_word_t const *words; + unsigned endian; + int k; + + /* Compute the CRC up to a z_word_t boundary. */ + while (len && ((z_size_t)buf & (W - 1)) != 0) { + len--; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + } + + /* Compute the CRC on as many N z_word_t blocks as are available. */ + blks = len / (N * W); + len -= blks * N * W; + words = (z_word_t const *)buf; + + /* Do endian check at execution time instead of compile time, since ARM + processors can change the endianness at execution time. If the + compiler knows what the endianness will be, it can optimize out the + check and the unused branch. */ + endian = 1; + if (*(unsigned char *)&endian) { + /* Little endian. */ + + z_crc_t crc0; + z_word_t word0; +#if N > 1 + z_crc_t crc1; + z_word_t word1; +#if N > 2 + z_crc_t crc2; + z_word_t word2; +#if N > 3 + z_crc_t crc3; + z_word_t word3; +#if N > 4 + z_crc_t crc4; + z_word_t word4; +#if N > 5 + z_crc_t crc5; + z_word_t word5; +#endif +#endif +#endif +#endif +#endif + + /* Initialize the CRC for each braid. */ + crc0 = crc; +#if N > 1 + crc1 = 0; +#if N > 2 + crc2 = 0; +#if N > 3 + crc3 = 0; +#if N > 4 + crc4 = 0; +#if N > 5 + crc5 = 0; +#endif +#endif +#endif +#endif +#endif + + /* + Process the first blks-1 blocks, computing the CRCs on each braid + independently. + */ + while (--blks) { + /* Load the word for each braid into registers. */ + word0 = crc0 ^ words[0]; +#if N > 1 + word1 = crc1 ^ words[1]; +#if N > 2 + word2 = crc2 ^ words[2]; +#if N > 3 + word3 = crc3 ^ words[3]; +#if N > 4 + word4 = crc4 ^ words[4]; +#if N > 5 + word5 = crc5 ^ words[5]; +#endif +#endif +#endif +#endif +#endif + words += N; + + /* Compute and update the CRC for each word. The loop should + get unrolled. */ + crc0 = crc_braid_table[0][word0 & 0xff]; +#if N > 1 + crc1 = crc_braid_table[0][word1 & 0xff]; +#if N > 2 + crc2 = crc_braid_table[0][word2 & 0xff]; +#if N > 3 + crc3 = crc_braid_table[0][word3 & 0xff]; +#if N > 4 + crc4 = crc_braid_table[0][word4 & 0xff]; +#if N > 5 + crc5 = crc_braid_table[0][word5 & 0xff]; +#endif +#endif +#endif +#endif +#endif + for (k = 1; k < W; k++) { + crc0 ^= crc_braid_table[k][(word0 >> (k << 3)) & 0xff]; +#if N > 1 + crc1 ^= crc_braid_table[k][(word1 >> (k << 3)) & 0xff]; +#if N > 2 + crc2 ^= crc_braid_table[k][(word2 >> (k << 3)) & 0xff]; +#if N > 3 + crc3 ^= crc_braid_table[k][(word3 >> (k << 3)) & 0xff]; +#if N > 4 + crc4 ^= crc_braid_table[k][(word4 >> (k << 3)) & 0xff]; +#if N > 5 + crc5 ^= crc_braid_table[k][(word5 >> (k << 3)) & 0xff]; +#endif +#endif +#endif +#endif +#endif + } + } + + /* + Process the last block, combining the CRCs of the N braids at the + same time. + */ + crc = crc_word(crc0 ^ words[0]); +#if N > 1 + crc = crc_word(crc1 ^ words[1] ^ crc); +#if N > 2 + crc = crc_word(crc2 ^ words[2] ^ crc); +#if N > 3 + crc = crc_word(crc3 ^ words[3] ^ crc); +#if N > 4 + crc = crc_word(crc4 ^ words[4] ^ crc); +#if N > 5 + crc = crc_word(crc5 ^ words[5] ^ crc); +#endif +#endif +#endif +#endif +#endif + words += N; + } + else { + /* Big endian. */ + + z_word_t crc0, word0, comb; +#if N > 1 + z_word_t crc1, word1; +#if N > 2 + z_word_t crc2, word2; +#if N > 3 + z_word_t crc3, word3; +#if N > 4 + z_word_t crc4, word4; +#if N > 5 + z_word_t crc5, word5; +#endif +#endif +#endif +#endif +#endif + + /* Initialize the CRC for each braid. */ + crc0 = byte_swap(crc); +#if N > 1 + crc1 = 0; +#if N > 2 + crc2 = 0; +#if N > 3 + crc3 = 0; +#if N > 4 + crc4 = 0; +#if N > 5 + crc5 = 0; +#endif +#endif +#endif +#endif +#endif + + /* + Process the first blks-1 blocks, computing the CRCs on each braid + independently. + */ + while (--blks) { + /* Load the word for each braid into registers. */ + word0 = crc0 ^ words[0]; +#if N > 1 + word1 = crc1 ^ words[1]; +#if N > 2 + word2 = crc2 ^ words[2]; +#if N > 3 + word3 = crc3 ^ words[3]; +#if N > 4 + word4 = crc4 ^ words[4]; +#if N > 5 + word5 = crc5 ^ words[5]; +#endif +#endif +#endif +#endif +#endif + words += N; + + /* Compute and update the CRC for each word. The loop should + get unrolled. */ + crc0 = crc_braid_big_table[0][word0 & 0xff]; +#if N > 1 + crc1 = crc_braid_big_table[0][word1 & 0xff]; +#if N > 2 + crc2 = crc_braid_big_table[0][word2 & 0xff]; +#if N > 3 + crc3 = crc_braid_big_table[0][word3 & 0xff]; +#if N > 4 + crc4 = crc_braid_big_table[0][word4 & 0xff]; +#if N > 5 + crc5 = crc_braid_big_table[0][word5 & 0xff]; +#endif +#endif +#endif +#endif +#endif + for (k = 1; k < W; k++) { + crc0 ^= crc_braid_big_table[k][(word0 >> (k << 3)) & 0xff]; +#if N > 1 + crc1 ^= crc_braid_big_table[k][(word1 >> (k << 3)) & 0xff]; +#if N > 2 + crc2 ^= crc_braid_big_table[k][(word2 >> (k << 3)) & 0xff]; +#if N > 3 + crc3 ^= crc_braid_big_table[k][(word3 >> (k << 3)) & 0xff]; +#if N > 4 + crc4 ^= crc_braid_big_table[k][(word4 >> (k << 3)) & 0xff]; +#if N > 5 + crc5 ^= crc_braid_big_table[k][(word5 >> (k << 3)) & 0xff]; +#endif +#endif +#endif +#endif +#endif + } + } + + /* + Process the last block, combining the CRCs of the N braids at the + same time. + */ + comb = crc_word_big(crc0 ^ words[0]); +#if N > 1 + comb = crc_word_big(crc1 ^ words[1] ^ comb); +#if N > 2 + comb = crc_word_big(crc2 ^ words[2] ^ comb); +#if N > 3 + comb = crc_word_big(crc3 ^ words[3] ^ comb); +#if N > 4 + comb = crc_word_big(crc4 ^ words[4] ^ comb); +#if N > 5 + comb = crc_word_big(crc5 ^ words[5] ^ comb); +#endif +#endif +#endif +#endif +#endif + words += N; + crc = byte_swap(comb); + } + + /* + Update the pointer to the remaining bytes to process. + */ + buf = (unsigned char const *)words; + } + +#endif /* W */ + + /* Complete the computation of the CRC on any remaining bytes. */ + while (len >= 8) { + len -= 8; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + } + while (len) { + len--; + crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; + } + + /* Return the CRC, post-conditioned. */ + return crc ^ 0xffffffff; +} + +#endif + +/* ========================================================================= */ +uLong ZEXPORT crc32(uLong crc, const unsigned char FAR *buf, uInt len) { + #ifdef HAVE_S390X_VX + return crc32_z_hook(crc, buf, len); + #endif + return crc32_z(crc, buf, len); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine_gen64(z_off64_t len2) { + if (len2 < 0) + return 0; +#ifdef DYNAMIC_CRC_TABLE + z_once(&made, make_crc_table); +#endif /* DYNAMIC_CRC_TABLE */ + return x2nmodp(len2, 3); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine_gen(z_off_t len2) { + return crc32_combine_gen64((z_off64_t)len2); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) { + if (op == 0) + return 0; + return multmodp(op, crc1 & 0xffffffff) ^ (crc2 & 0xffffffff); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) { + return crc32_combine_op(crc1, crc2, crc32_combine_gen64(len2)); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) { + return crc32_combine64(crc1, crc2, (z_off64_t)len2); +} diff --git a/Minecraft.Client/Common/zlib/trees.c b/Minecraft.Client/Common/zlib/trees.c index fa31c0fa4..8e4da01e9 100644 --- a/Minecraft.Client/Common/zlib/trees.c +++ b/Minecraft.Client/Common/zlib/trees.c @@ -1,1119 +1,1119 @@ -/* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2026 Jean-loup Gailly - * detect_data_type() function provided freely by Cosmin Truta, 2006 - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process uses several Huffman trees. The more - * common source values are represented by shorter bit sequences. - * - * Each code tree is stored in a compressed form which is itself - * a Huffman encoding of the lengths of all the code strings (in - * ascending order by source values). The actual code strings are - * reconstructed from the lengths in the inflate process, as described - * in the deflate specification. - * - * REFERENCES - * - * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". - * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc - * - * Storer, James A. - * Data Compression: Methods and Theory, pp. 49-50. - * Computer Science Press, 1988. ISBN 0-7167-8156-5. - * - * Sedgewick, R. - * Algorithms, p290. - * Addison-Wesley, 1983. ISBN 0-201-06672-6. - */ - -/* @(#) $Id$ */ - -/* #define GEN_TREES_H */ - -#include "deflate.h" - -#ifdef ZLIB_DEBUG -# include -#endif - -/* =========================================================================== - * Constants - */ - -#define MAX_BL_BITS 7 -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -#define END_BLOCK 256 -/* end of block literal code */ - -#define REP_3_6 16 -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -#define REPZ_3_10 17 -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -#define REPZ_11_138 18 -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - -local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ - -#if defined(GEN_TREES_H) || !defined(STDC) -/* non ANSI compilers may not accept trees.h */ - -local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -uch _length_code[MAX_MATCH-MIN_MATCH+1]; -/* length code for each normalized match length (0 == MIN_MATCH) */ - -local int base_length[LENGTH_CODES]; -/* First normalized length for each code (0 = MIN_MATCH) */ - -local int base_dist[D_CODES]; -/* First normalized distance for each code (0 = distance of 1) */ - -#else -# include "trees.h" -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ - -struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ -}; - -#ifdef NO_INIT_GLOBAL_POINTERS -# define TCONST -#else -# define TCONST const -#endif - -local TCONST static_tree_desc static_l_desc = -{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - -local TCONST static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - -local TCONST static_tree_desc static_bl_desc = -{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -#define put_short(s, w) { \ - put_byte(s, (uch)((w) & 0xff)); \ - put_byte(s, (uch)((ush)(w) >> 8)); \ -} - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -local unsigned bi_reverse(unsigned code, int len) { - unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; -} - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -local void bi_flush(deflate_state *s) { - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } -} - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -local void bi_windup(deflate_state *s) { - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_used = ((s->bi_valid - 1) & 7) + 1; - s->bi_buf = 0; - s->bi_valid = 0; -#ifdef ZLIB_DEBUG - s->bits_sent = (s->bits_sent + 7) & ~(ulg)7; -#endif -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - unsigned code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - code = (code + bl_count[bits - 1]) << 1; - next_code[bits] = (ush)code; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, - "inconsistent bit counts"); - Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); - - for (n = 0; n <= max_code; n++) { - int len = tree[n].Len; - if (len == 0) continue; - /* Now reverse the bits */ - tree[n].Code = (ush)bi_reverse(next_code[len]++, len); - - Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", - n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); - } -} - -#ifdef GEN_TREES_H -local void gen_trees_header(void); -#endif - -#ifndef ZLIB_DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ - -#else /* !ZLIB_DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } -#endif - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -#ifdef ZLIB_DEBUG -local void send_bits(deflate_state *s, int value, int length) { - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (ush)value << s->bi_valid; - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= (ush)value << s->bi_valid; - s->bi_valid += length; - } -} -#else /* !ZLIB_DEBUG */ - -#define send_bits(s, value, length) \ -{ int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = (int)value;\ - s->bi_buf |= (ush)val << s->bi_valid;\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (ush)(value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ -} -#endif /* ZLIB_DEBUG */ - - -/* the arguments must not have side effects */ - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -local void tr_static_init(void) { -#if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ -#ifdef NO_INIT_GLOBAL_POINTERS - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; -#endif - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1 << extra_lbits[code]); n++) { - _length_code[length++] = (uch)code; - } - } - Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = (uch)code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1 << extra_dbits[code]); n++) { - _dist_code[dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256 + dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ -} - -/* =========================================================================== - * Generate the file trees.h describing the static trees. - */ -#ifdef GEN_TREES_H -# ifndef ZLIB_DEBUG -# include -# endif - -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width) - 1 ? ",\n" : ", ")) - -void gen_trees_header(void) { - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, - "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); -} -#endif /* GEN_TREES_H */ - -/* =========================================================================== - * Initialize a new block. - */ -local void init_block(deflate_state *s) { - int n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->sym_next = s->matches = 0; -} - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -void ZLIB_INTERNAL _tr_init(deflate_state *s) { - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; - - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; - - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; - - s->bi_buf = 0; - s->bi_valid = 0; - s->bi_used = 0; -#ifdef ZLIB_DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; -#endif - - /* Initialize the first block of the first file: */ - init_block(s); -} - -#define SMALLEST 1 -/* Index within the heap array of least frequent node in the Huffman tree */ - - -/* =========================================================================== - * Remove the smallest element from the heap and recreate the heap with - * one less element. Updates heap and heap_len. - */ -#define pqremove(s, tree, top) \ -{\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -local void pqdownheap(deflate_state *s, ct_data *tree, int k) { - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; -} - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -local void gen_bitlen(deflate_state *s, tree_desc *desc) { - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n - base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (unsigned)(bits + xbits); - if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); - } - if (overflow == 0) return; - - Tracev((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } -} - -#ifdef DUMP_BL_TREE -# include -#endif - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -local void build_tree(deflate_state *s, tree_desc *desc) { - ct_data *tree = desc->dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; -#ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } -#endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); - - } while (s->heap_len >= 2); - - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); -} - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -local void scan_tree(deflate_state *s, ct_data *tree, int max_code) { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code + 1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n + 1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += (ush)count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -local void send_tree(deflate_state *s, ct_data *tree, int max_code) { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code + 1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n + 1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -local int build_bl_tree(deflate_state *s) { - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except the - * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4; - Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", - s->opt_len, s->static_len)); - - return max_blindex; -} - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -local void send_all_trees(deflate_state *s, int lcodes, int dcodes, - int blcodes) { - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent)); -} - -/* =========================================================================== - * Send a stored block - */ -void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, - ulg stored_len, int last) { - send_bits(s, (STORED_BLOCK<<1) + last, 3); /* send block type */ - bi_windup(s); /* align on byte boundary */ - put_short(s, (ush)stored_len); - put_short(s, (ush)~stored_len); - if (stored_len) - zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); - s->pending += stored_len; -#ifdef ZLIB_DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; - s->bits_sent += 2*16; - s->bits_sent += stored_len << 3; -#endif -} - -/* =========================================================================== - * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) - */ -void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) { - bi_flush(s); -} - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -void ZLIB_INTERNAL _tr_align(deflate_state *s) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef ZLIB_DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ -#endif - bi_flush(s); -} - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -local void compress_block(deflate_state *s, const ct_data *ltree, - const ct_data *dtree) { - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned sx = 0; /* running index in symbol buffers */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->sym_next != 0) do { -#ifdef LIT_MEM - dist = s->d_buf[sx]; - lc = s->l_buf[sx++]; -#else - dist = s->sym_buf[sx++] & 0xff; - dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; - lc = s->sym_buf[sx++]; -#endif - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= (unsigned)base_dist[code]; - send_bits(s, (int)dist, extra); /* send the extra bits */ - } - } /* literal or match pair ? */ - - /* Check for no overlay of pending_buf on needed symbols */ -#ifdef LIT_MEM - Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); -#else - Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); -#endif - - } while (sx < s->sym_next); - - send_code(s, END_BLOCK, ltree); -} - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "block list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -local int detect_data_type(deflate_state *s) { - /* block_mask is the bit mask of block-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - unsigned long block_mask = 0xf3ffc07fUL; - int n; - - /* Check for non-textual ("block-listed") bytes. */ - for (n = 0; n <= 31; n++, block_mask >>= 1) - if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) - return Z_BINARY; - - /* Check for textual ("allow-listed") bytes. */ - if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 - || s->dyn_ltree[13].Freq != 0) - return Z_TEXT; - for (n = 32; n < LITERALS; n++) - if (s->dyn_ltree[n].Freq != 0) - return Z_TEXT; - - /* There are no "block-listed" or "allow-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and write out the encoded block. - */ -void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, - ulg stored_len, int last) { - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (s->strm->data_type == Z_UNKNOWN) - s->strm->data_type = detect_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %lu, stat %lu", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %lu, stat %lu", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len + 3 + 7) >> 3; - static_lenb = (s->static_len + 3 + 7) >> 3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->sym_next / 3)); - -#ifndef FORCE_STATIC - if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) -#endif - opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - -#ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ -#else - if (stored_len + 4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ -#endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (static_lenb == opt_lenb) { - send_bits(s, (STATIC_TREES<<1) + last, 3); - compress_block(s, (const ct_data *)static_ltree, - (const ct_data *)static_dtree); -#ifdef ZLIB_DEBUG - s->compressed_len += 3 + s->static_len; -#endif - } else { - send_bits(s, (DYN_TREES<<1) + last, 3); - send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1, - max_blindex + 1); - compress_block(s, (const ct_data *)s->dyn_ltree, - (const ct_data *)s->dyn_dtree); -#ifdef ZLIB_DEBUG - s->compressed_len += 3 + s->opt_len; -#endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); -#ifdef ZLIB_DEBUG - s->compressed_len += 7; /* align on byte boundary */ -#endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3, - s->compressed_len - 7*(ulg)last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) { -#ifdef LIT_MEM - s->d_buf[s->sym_next] = (ush)dist; - s->l_buf[s->sym_next++] = (uch)lc; -#else - s->sym_buf[s->sym_next++] = (uch)dist; - s->sym_buf[s->sym_next++] = (uch)(dist >> 8); - s->sym_buf[s->sym_next++] = (uch)lc; -#endif - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - return (s->sym_next == s->sym_end); -} +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2026 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef ZLIB_DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +#ifdef NO_INIT_GLOBAL_POINTERS +# define TCONST +#else +# define TCONST const +#endif + +local TCONST static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local TCONST static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local TCONST static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(unsigned code, int len) { + unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(deflate_state *s) { + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(deflate_state *s) { + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_used = ((s->bi_valid - 1) & 7) + 1; + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->bits_sent = (s->bits_sent + 7) & ~(ulg)7; +#endif +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + unsigned code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits - 1]) << 1; + next_code[bits] = (ush)code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, + "inconsistent bit counts"); + Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + int len = tree[n].Len; + if (len == 0) continue; + /* Now reverse the bits */ + tree[n].Code = (ush)bi_reverse(next_code[len]++, len); + + Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); + } +} + +#ifdef GEN_TREES_H +local void gen_trees_header(void); +#endif + +#ifndef ZLIB_DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* !ZLIB_DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef ZLIB_DEBUG +local void send_bits(deflate_state *s, int value, int length) { + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !ZLIB_DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = (int)value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* ZLIB_DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init(void) { +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = (uch)code; + } + } + Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = (uch)code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256 + dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Generate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef ZLIB_DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width) - 1 ? ",\n" : ", ")) + +void gen_trees_header(void) { + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(deflate_state *s) { + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->sym_next = s->matches = 0; +} + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(deflate_state *s) { + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->bi_used = 0; +#ifdef ZLIB_DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(deflate_state *s, ct_data *tree, int k) { + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(deflate_state *s, tree_desc *desc) { + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n - base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); + } + if (overflow == 0) return; + + Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +#ifdef DUMP_BL_TREE +# include +#endif + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +local void build_tree(deflate_state *s, tree_desc *desc) { + ct_data *tree = desc->dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree(deflate_state *s, ct_data *tree, int max_code) { + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code + 1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n + 1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += (ush)count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree(deflate_state *s, ct_data *tree, int max_code) { + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code + 1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n + 1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(deflate_state *s) { + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except the + * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4; + Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(deflate_state *s, int lcodes, int dcodes, + int blcodes) { + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, + ulg stored_len, int last) { + send_bits(s, (STORED_BLOCK<<1) + last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); + if (stored_len) + zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); + s->pending += stored_len; +#ifdef ZLIB_DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; + s->bits_sent += stored_len << 3; +#endif +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) { + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(deflate_state *s) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef ZLIB_DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(deflate_state *s, const ct_data *ltree, + const ct_data *dtree) { + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned sx = 0; /* running index in symbol buffers */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->sym_next != 0) do { +#ifdef LIT_MEM + dist = s->d_buf[sx]; + lc = s->l_buf[sx++]; +#else + dist = s->sym_buf[sx++] & 0xff; + dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; + lc = s->sym_buf[sx++]; +#endif + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= (unsigned)base_dist[code]; + send_bits(s, (int)dist, extra); /* send the extra bits */ + } + } /* literal or match pair ? */ + + /* Check for no overlay of pending_buf on needed symbols */ +#ifdef LIT_MEM + Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); +#else + Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); +#endif + + } while (sx < s->sym_next); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "block list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(deflate_state *s) { + /* block_mask is the bit mask of block-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long block_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("block-listed") bytes. */ + for (n = 0; n <= 31; n++, block_mask >>= 1) + if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("allow-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "block-listed" or "allow-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, + ulg stored_len, int last) { + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %lu, stat %lu", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %lu, stat %lu", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len + 3 + 7) >> 3; + static_lenb = (s->static_len + 3 + 7) >> 3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->sym_next / 3)); + +#ifndef FORCE_STATIC + if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) +#endif + opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len + 4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (static_lenb == opt_lenb) { + send_bits(s, (STATIC_TREES<<1) + last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1) + last, 3); + send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1, + max_blindex + 1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef ZLIB_DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3, + s->compressed_len - 7*(ulg)last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) { +#ifdef LIT_MEM + s->d_buf[s->sym_next] = (ush)dist; + s->l_buf[s->sym_next++] = (uch)lc; +#else + s->sym_buf[s->sym_next++] = (uch)dist; + s->sym_buf[s->sym_next++] = (uch)(dist >> 8); + s->sym_buf[s->sym_next++] = (uch)lc; +#endif + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + return (s->sym_next == s->sym_end); +} diff --git a/Minecraft.Client/Common/zlib/zlib.h b/Minecraft.Client/Common/zlib/zlib.h index 398a431ab..0a9e7909f 100644 --- a/Minecraft.Client/Common/zlib/zlib.h +++ b/Minecraft.Client/Common/zlib/zlib.h @@ -1,2057 +1,2057 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.3.2.1, February xxth, 2026 - - Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 at https://datatracker.ietf.org/doc/html/rfc1950 - (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#ifdef ZLIB_BUILD -# include -#else -# include "zconf.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.3.2.1-motley" -#define ZLIB_VERNUM 0x1321 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 3 -#define ZLIB_VER_REVISION 2 -#define ZLIB_VER_SUBREVISION 1 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip and raw deflate streams in - memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in the case of corrupted input. -*/ - -typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size); -typedef void (*free_func)(voidpf opaque, voidpf address); - -struct internal_state; - -typedef struct z_stream_s { - z_const Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total number of input bytes read so far */ - - Bytef *next_out; /* next output byte will go here */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total number of bytes output so far */ - - z_const char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text - for deflate, or the decoding state for inflate */ - uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. In that case, zlib is thread-safe. When zalloc and zfree are - Z_NULL on entry to the initialization function, they are set to internal - routines that use the standard library functions malloc() and free(). - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use by the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field for deflate() */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion(void); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. total_in, total_out, adler, and msg are initialized. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Generate more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary. Some output may be provided even if - flush is zero. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. See deflatePending(), - which can be used if desired to determine whether or not there is more output - in that case. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed - codes block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six when the flush marker begins, in order to avoid - repeated flush markers upon calling deflate() again when avail_out == 0. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this - function must be called again with Z_FINISH and more output space (updated - avail_out) but no more input data, until it returns with Z_STREAM_END or an - error. After deflate has returned Z_STREAM_END, the only possible operations - on the stream are deflateReset or deflateEnd. - - Z_FINISH can be used in the first deflate call after deflateInit if all the - compression is to be done in a single step. In order to complete in one - call, avail_out must be at least the value returned by deflateBound (see - below). Then deflate is guaranteed to return Z_STREAM_END. If not enough - output space is provided, deflate will not return Z_STREAM_END, and it must - be called again as described above. - - deflate() sets strm->adler to the Adler-32 checksum of all input read - so far (that is, total_in bytes). If a gzip stream is being generated, then - strm->adler will be the CRC-32 checksum of the input read so far. (See - deflateInit2 below.) - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is - considered binary. This field is only for information purposes and does not - affect the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL or the state was inadvertently written over - by the application), or Z_BUF_ERROR if no progress is possible (for example - avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and - deflate() can be called again with more input and more output space to - continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd(z_streamp strm); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit(z_streamp strm); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. In the current version of inflate, the provided input is not - read or consumed. The allocation of a sliding window will be deferred to - the first call of inflate (if the decompression does not complete on the - first call). If zalloc and zfree are set to Z_NULL, inflateInit updates - them to use default allocation functions. total_in, total_out, adler, and - msg are initialized. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression. - Actual decompression will be done by inflate(). So next_in, and avail_in, - next_out, and avail_out are unused and unchanged. The current - implementation of inflateInit() does not process any header information -- - that is deferred until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), then next_in and avail_in are updated - accordingly, and processing will resume at this point for the next call of - inflate(). - - - Generate more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. If the - caller of inflate() does not provide both available input and available - output space, it is possible that there will be no progress made. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - To assist in this, on return inflate() always sets strm->data_type to the - number of unused bits in the input taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all of the uncompressed data for the - operation to complete. (The size of the uncompressed data may have been - saved by the compressor for this purpose.) The use of Z_FINISH is not - required to perform an inflation in one step. However it may be used to - inform inflate that a faster approach can be used for the single inflate() - call. Z_FINISH also informs inflate to not maintain a sliding window if the - stream completes, which reduces inflate's memory footprint. If the stream - does not complete, either because not all of the stream is provided or not - enough output space is provided, then a sliding window will be allocated and - inflate() can be called again to continue the operation as if Z_NO_FLUSH had - been used. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the effects of the flush parameter in this implementation are - on the return value of inflate() as noted below, when inflate() returns early - when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of - memory for a sliding window when Z_FINISH is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the Adler-32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the Adler-32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed Adler-32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained unless inflateGetHeader() is used. When processing - gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output - produced so far. The CRC-32 is checked against the gzip trailer, as is the - uncompressed length, modulo 2^32. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value, in which case strm->msg points to a string with a more specific - error), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL, or the state was inadvertently written over - by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR - if no progress was possible or if there was not enough room in the output - buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is to be attempted. -*/ - - -ZEXTERN int ZEXPORT inflateEnd(z_streamp strm); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state - was inconsistent. -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2(z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy); - - This is another version of deflateInit with more compression options. The - fields zalloc, zfree and opaque must be initialized before by the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - For the current implementation of deflate(), a windowBits value of 8 (a - window size of 256 bytes) is not supported. As a result, a request for 8 - will result in 9 (a 512-byte window). In that case, providing 8 to - inflateInit2() will result in an error when the zlib header with 9 is - checked against the initialization of inflate(). The remedy is to not use 8 - with deflateInit2() with this initialization, or at least in that case use 9 - with inflateInit2(). - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute a check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to the appropriate value, - if the operating system was determined at compile time. If a gzip stream is - being written, strm->adler is a CRC-32 instead of an Adler-32. - - For raw deflate or gzip encoding, a request for a 256-byte window is - rejected as invalid, since only the zlib header provides a means of - transmitting the window size to the decompressor. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_RLE to limit match distances to one (run-length - encoding), or Z_HUFFMAN_ONLY to force Huffman encoding only (no string - matching). Filtered data consists mostly of small values with a somewhat - random distribution, as produced by the PNG filters. In this case, the - compression algorithm is tuned to compress them better. The effect of - Z_FILTERED is to force more Huffman coding and less string matching than the - default; it is intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. - Z_RLE is almost as fast as Z_HUFFMAN_ONLY, but should give better - compression for PNG image data than Huffman only. The degree of string - matching from most to none is: Z_DEFAULT_STRATEGY, Z_FILTERED, Z_RLE, then - Z_HUFFMAN_ONLY. The strategy parameter affects the compression ratio but - never the correctness of the compressed output, even if it is not set - optimally for the given data. Z_FIXED uses the default string matching, but - prevents the use of dynamic Huffman codes, allowing for a simpler decoder - for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm, - const Bytef *dictionary, - uInt dictLength); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. When using the zlib format, this - function must be called immediately after deflateInit, deflateInit2 or - deflateReset, and before any call of deflate. When doing raw deflate, this - function must be called either before any call of deflate, or immediately - after the completion of a deflate block, i.e. after all input has been - consumed and all output has been delivered when using any of the flush - options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The - compressor and decompressor must use exactly the same dictionary (see - inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the Adler-32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The Adler-32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - Adler-32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if not at a block boundary for raw deflate). deflateSetDictionary does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm, - Bytef *dictionary, - uInt *dictLength); -/* - Returns the sliding dictionary being maintained by deflate. dictLength is - set to the number of bytes in the dictionary, and that many bytes are copied - to dictionary. dictionary must have enough space, where 32768 bytes is - always enough. If deflateGetDictionary() is called with dictionary equal to - Z_NULL, then only the dictionary length is returned, and nothing is copied. - Similarly, if dictLength is Z_NULL, then it is not set. - - deflateGetDictionary() may return a length less than the window size, even - when more than the window size in input has been provided. It may return up - to 258 bytes less in that case, due to how zlib's implementation of deflate - manages the sliding window and lookahead for matches, where matches can be - up to 258 bytes long. If the application needs the last window-size bytes of - input, then that would need to be saved by the application outside of zlib. - - deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the - stream state is inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, - z_streamp source); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset(z_streamp strm); -/* - This function is equivalent to deflateEnd followed by deflateInit, but - does not free and reallocate the internal compression state. The stream - will leave the compression level and any other attributes that may have been - set unchanged. total_in, total_out, adler, and msg are initialized. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams(z_streamp strm, - int level, - int strategy); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2(). This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression approach (which is a function of the level) or the - strategy is changed, and if there have been any deflate() calls since the - state was initialized or reset, then the input available so far is - compressed with the old level and strategy using deflate(strm, Z_BLOCK). - There are three approaches for the compression levels 0, 1..3, and 4..9 - respectively. The new level and strategy will take effect at the next call - of deflate(). - - If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does - not have enough output space to complete, then the parameter change will not - take effect. In this case, deflateParams() can be called again with the - same parameters and more output space to try again. - - In order to assure a change in the parameters on the first try, the - deflate stream should be flushed using deflate() with Z_BLOCK or other flush - request until strm.avail_out is not zero, before calling deflateParams(). - Then no more input data should be provided before the deflateParams() call. - If this is done, the old level and strategy will be applied to the data - compressed before deflateParams(), and the new level and strategy will be - applied to the data compressed after deflateParams(). - - deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream - state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if - there was not enough output space to complete the compression of the - available input data before a change in the strategy or approach. Note that - in the case of a Z_BUF_ERROR, the parameters are not changed. A return - value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be - retried with more output space. -*/ - -ZEXTERN int ZEXPORT deflateTune(z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen); -ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). If that first deflate() call is provided the - sourceLen input bytes, an output buffer allocated to the size returned by - deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed - to return Z_STREAM_END. Note that it is possible for the compressed size to - be larger than the value returned by deflateBound() if flush options other - than Z_FINISH or Z_NO_FLUSH are used. - - delfateBound_z() is the same, but takes and returns a size_t length. Note - that a long is 32 bits on Windows. -*/ - -ZEXTERN int ZEXPORT deflatePending(z_streamp strm, - unsigned *pending, - int *bits); -/* - deflatePending() returns the number of bytes and bits of output that have - been generated, but not yet provided in the available output. The bytes not - provided would be due to the available output space having being consumed. - The number of bits of output not provided are between 0 and 7, where they - await more bits to join them in order to fill out a full byte. If pending - or bits are Z_NULL, then those values are not set. - - deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. If an int is 16 bits and memLevel is 9, then - it is possible for the number of pending bytes to not fit in an unsigned. In - that case Z_BUF_ERROR is returned and *pending is set to the maximum value - of an unsigned. - */ - -ZEXTERN int ZEXPORT deflateUsed(z_streamp strm, - int *bits); -/* - deflateUsed() returns in *bits the most recent number of deflate bits used - in the last byte when flushing to a byte boundary. The result is in 1..8, or - 0 if there has not yet been a flush. This helps determine the location of - the last bit of a deflate stream. - - deflateUsed returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. - */ - -ZEXTERN int ZEXPORT deflatePrime(z_streamp strm, - int bits, - int value); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough - room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm, - gz_headerp head); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to the current operating system, with no - extra, name, or comment fields. The gzip header is returned to the default - state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, - int windowBits); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an Adler-32 or a CRC-32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see - below), inflate() will *not* automatically decode concatenated gzip members. - inflate() will return Z_STREAM_END at the end of the gzip member. The state - would need to be reset to continue decoding a subsequent gzip member. This - *must* be done if there is more data after a gzip member, in order for the - decompression to be compliant with the gzip standard (RFC 1952). - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm, - const Bytef *dictionary, - uInt dictLength); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the Adler-32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called at any - time to set the dictionary. If the provided dictionary is smaller than the - window and there is already data in the window, then the provided dictionary - will amend what's there. The application must insure that the dictionary - that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect Adler-32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm, - Bytef *dictionary, - uInt *dictLength); -/* - Returns the sliding dictionary being maintained by inflate. dictLength is - set to the number of bytes in the dictionary, and that many bytes are copied - to dictionary. dictionary must have enough space, where 32768 bytes is - always enough. If inflateGetDictionary() is called with dictionary equal to - Z_NULL, then only the dictionary length is returned, and nothing is copied. - Similarly, if dictLength is Z_NULL, then it is not set. - - inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the - stream state is inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateSync(z_streamp strm); -/* - Skips invalid compressed data until a possible full flush point (see above - for the description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync searches for a 00 00 FF FF pattern in the compressed data. - All full flush points have this pattern, but not all occurrences of this - pattern are full flush points. - - inflateSync returns Z_OK if a possible full flush point has been found, - Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point - has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. - In the success case, the application may save the current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, - z_streamp source); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset(z_streamp strm); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - total_in, total_out, adler, and msg are initialized. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2(z_streamp strm, - int windowBits); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. If the window size is changed, then the - memory allocated for the window is freed, and the window will be reallocated - by inflate() if needed. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime(z_streamp strm, - int bits, - int value); -/* - This function inserts bits in the inflate input stream. The intent is to - use inflatePrime() to start inflating at a bit position in the middle of a - byte. The provided bits will be used before any bytes are used from - next_in. This function should be used with raw inflate, before the first - inflate() call, after inflateInit2() or inflateReset(). It can also be used - after an inflate() return indicates the end of a deflate block or header - when using Z_BLOCK. bits must be less than or equal to 16, and that many of - the least significant bits of value will be inserted in the input. The - other bits in value can be non-zero, and will be ignored. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent, or if bits is out of range. If inflate was - in the middle of processing a header, trailer, or stored block lengths, then - it is possible for there to be only eight bits available in the bit buffer. - In that case, bits > 8 is considered out of range. However, when used as - outlined above, there will always be 16 bits available in the buffer for - insertion. As noted in its documentation above, inflate records the number - of bits in the bit buffer on return in data_type. 32 minus that is the - number of bits available for insertion. inflatePrime does not update - data_type with the new number of bits in buffer. -*/ - -ZEXTERN long ZEXPORT inflateMark(z_streamp strm); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above, or -65536 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, - gz_headerp head); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) The extra, name, and comment pointers - much each be either Z_NULL or point to space to store that information from - the header. If extra is not Z_NULL, then extra_max contains the maximum - number of bytes that can be written to extra. Once done is true, extra_len - contains the actual extra field length, and extra contains the extra field, - or that field truncated if extra_max is less than extra_len. If name is not - Z_NULL, then up to name_max characters, including the terminating zero, are - written there. If comment is not Z_NULL, then up to comm_max characters, - including the terminating zero, are written there. The application can tell - that the name or comment did not fit in the provided space by the absence of - a terminating zero. If any of extra, name, or comment are not present in - the header, then that field's pointer is set to Z_NULL. This allows the use - of deflateSetHeader() with the returned structure to duplicate the header. - Note that if those fields initially pointed to allocated memory, then the - application will need to save them elsewhere so that they can be eventually - freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits, - unsigned char FAR *window); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the parameters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func)(void FAR *, - z_const unsigned char FAR * FAR *); -typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned); - -ZEXTERN int ZEXPORT inflateBack(z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is potentially more efficient than - inflate() for file i/o applications, in that it avoids copying between the - output and the sliding window by simply making the window itself the output - buffer. inflate() can be faster on modern CPUs when used with large - buffers. inflateBack() trusts the application to not change the output - buffer passed by the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the default - behavior of inflate(), which expects a zlib header and trailer around the - deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero -- buf is ignored in that - case -- and inflateBack() will return a buffer error. inflateBack() will - call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. - out() should return zero on success, or non-zero on failure. If out() - returns non-zero, inflateBack() will return with an error. Neither in() nor - out() are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags(void); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: ZLIB_DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (all zeros is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() is not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - 27: 0 = gzprintf() present, 1 = not -- 1 means gzprintf() returns an error - - Remainder: - 28-31: 0 (reserved) - */ - -#ifndef Z_SOLO - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. The _z versions of the functions use the size_t - type for lengths. Note that a long is 32 bits on Windows. -*/ - -ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen); -ZEXTERN int ZEXPORT compress_z(Bytef *dest, z_size_t *destLen, - const Bytef *source, z_size_t sourceLen); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed data. compress() is equivalent to compress2() with a level - parameter of Z_DEFAULT_COMPRESSION. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level); -ZEXTERN int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen, - const Bytef *source, z_size_t sourceLen, - int level); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed data. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen); -ZEXTERN z_size_t ZEXPORT compressBound_z(z_size_t sourceLen); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen); -ZEXTERN int ZEXPORT uncompress_z(Bytef *dest, z_size_t *destLen, - const Bytef *source, z_size_t sourceLen); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. On entry, *destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) On exit, *destLen - is the actual size of the uncompressed data. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In - the case where there is not enough room, uncompress() will fill the output - buffer with the uncompressed data up to that point. -*/ - -ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen); -ZEXTERN int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen, - const Bytef *source, z_size_t *sourceLen); -/* - Same as uncompress, except that sourceLen is a pointer, where the - length of the source is *sourceLen. On return, *sourceLen is the number of - source bytes consumed. -*/ - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); - - Open the gzip (.gz) file at path for reading and decompressing, or - compressing and writing. The mode parameter is as in fopen ("rb" or "wb") - but can also include a compression level ("wb9") or a strategy: 'f' for - filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", - 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression - as in "wb9F". (See the description of deflateInit2 for more information - about the strategy parameter.) 'T' will request transparent writing or - appending with no compression and not using the gzip format. 'T' cannot be - used to force transparent reading. Transparent reading is automatically - performed if there is no gzip header at the start. Transparent reading can - be disabled with the 'G' option, which will instead return an error if there - is no gzip header. 'N' will open the file in non-blocking mode. - - 'a' can be used instead of 'w' to request that the gzip stream that will - be written be appended to the file. '+' will result in an error, since - reading and writing to the same gzip file is not supported. The addition of - 'x' when writing will create the file exclusively, which fails if the file - already exists. On systems that support it, the addition of 'e' when - reading or writing will set the flag to close the file on an execve() call. - - These functions, as well as gzip, will read and decode a sequence of gzip - streams in a file. The append function of gzopen() can be used to create - such a file. (Also see gzflush() for another way to do this.) When - appending, gzopen does not test whether the file begins with a gzip stream, - nor does it look for the end of the gzip streams to begin appending. gzopen - will simply append a gzip stream to the existing file. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. When - reading, this will be detected automatically by looking for the magic two- - byte gzip header. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. Note that if 'N' is in mode for non-blocking, the - open() itself can fail in order to not block. In that case gzopen() will - return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can - then be re-tried. If the application would like to block on opening the - file, then it can use open() without O_NONBLOCK, and then gzdopen() with the - resulting file descriptor and 'N' in the mode, which will set it to non- - blocking. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode); -/* - Associate a gzFile with the file descriptor fd. File descriptors are - obtained from calls like open, dup, creat, pipe or fileno (if the file has - been previously opened with fopen). The mode parameter is as in gzopen. An - 'e' in mode will set fd's flag to close the file on an execve() call. An 'N' - in mode will set fd's non-blocking flag. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. If you are using fileno() to get the - file descriptor from a FILE *, then you will have to use dup() to avoid - double-close()ing the file descriptor. Both gzclose() and fclose() will - close the associated file descriptor, so they need to have different file - descriptors. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size); -/* - Set the internal buffer size used by this library's functions for file to - size. The default buffer size is 8192 bytes. This function must be called - after gzopen() or gzdopen(), and before any other calls that read or write - the file. The buffer memory allocation is always deferred to the first read - or write. Three times that size in buffer space is allocated. A larger - buffer size of, for example, 64K or 128K bytes will noticeably increase the - speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy); -/* - Dynamically update the compression level and strategy for file. See the - description of deflateInit2 for the meaning of these parameters. Previously - provided data is flushed before applying the parameter changes. - - gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not - opened for writing, Z_ERRNO if there is an error writing the flushed data, - or Z_MEM_ERROR if there is a memory allocation error. -*/ - -ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len); -/* - Read and decompress up to len uncompressed bytes from file into buf. If - the input file is not in gzip format, gzread copies the given number of - bytes into the buffer directly from the file. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream. Any number of gzip streams may be - concatenated in the input file, and will all be decompressed by gzread(). - If something other than a gzip stream is encountered after a gzip stream, - that remaining trailing garbage is ignored (and no error is returned). - - gzread can be used to read a gzip file that is being concurrently written. - Upon reaching the end of the input, gzread will return with the available - data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then - gzclearerr can be used to clear the end of file indicator in order to permit - gzread to be tried again. Z_OK indicates that a gzip stream was completed - on the last gzread. Z_BUF_ERROR indicates that the input file ended in the - middle of a gzip stream. Note that gzread does not return -1 in the event - of an incomplete gzip stream. This error is deferred until gzclose(), which - will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip - stream. Alternatively, gzerror can be used before gzclose to detect this - case. - - gzread can be used to read a gzip file on a non-blocking device. If the - input stalls and there is no uncompressed data to return, then gzread() will - return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be - called again. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. If len is too large to fit in an int, - then nothing is read, -1 is returned, and the error state is set to - Z_STREAM_ERROR. If some data was read before an error, then that data is - returned until exhausted, after which the next call will signal the error. -*/ - -ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, - gzFile file); -/* - Read and decompress up to nitems items of size size from file into buf, - otherwise operating as gzread() does. This duplicates the interface of - stdio's fread(), with size_t request and return types. If the library - defines size_t, then z_size_t is identical to size_t. If not, then z_size_t - is an unsigned integer type that can contain a pointer. - - gzfread() returns the number of full items read of size size, or zero if - the end of the file was reached and a full item could not be read, or if - there was an error. gzerror() must be consulted if zero is returned in - order to determine if there was an error. If the multiplication of size and - nitems overflows, i.e. the product does not fit in a z_size_t, then nothing - is read, zero is returned, and the error state is set to Z_STREAM_ERROR. - - In the event that the end of file is reached and only a partial item is - available at the end, i.e. the remaining uncompressed data length is not a - multiple of size, then the final partial item is nevertheless read into buf - and the end-of-file flag is set. The length of the partial item read is not - provided, but could be inferred from the result of gztell(). This behavior - is the same as that of fread() implementations in common libraries. This - could result in data loss if used with size != 1 when reading a concurrently - written file or a non-blocking file. In that case, use size == 1 or gzread() - instead. -*/ - -ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len); -/* - Compress and write the len uncompressed bytes at buf to file. gzwrite - returns the number of uncompressed bytes written, or 0 in case of error or - if len is 0. If the write destination is non-blocking, then gzwrite() may - return a number of bytes written that is not 0 and less than len. - - If len does not fit in an int, then 0 is returned and nothing is written. -*/ - -ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, - z_size_t nitems, gzFile file); -/* - Compress and write nitems items of size size from buf to file, duplicating - the interface of stdio's fwrite(), with size_t request and return types. If - the library defines size_t, then z_size_t is identical to size_t. If not, - then z_size_t is an unsigned integer type that can contain a pointer. - - gzfwrite() returns the number of full items written of size size, or zero - if there was an error. If the multiplication of size and nitems overflows, - i.e. the product does not fit in a z_size_t, then nothing is written, zero - is returned, and the error state is set to Z_STREAM_ERROR. - - If writing a concurrently read file or a non-blocking file with size != 1, - a partial item could be written, with no way of knowing how much of it was - not written, resulting in data loss. In that case, use size == 1 or - gzwrite() instead. -*/ - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...); -#else -ZEXTERN int ZEXPORTVA gzprintf(); -#endif -/* - Convert, format, compress, and write the arguments (...) to file under - control of the string format, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or a negative zlib error code in case - of error. The number of uncompressed bytes written is limited to 8191, or - one less than the buffer size given to gzbuffer(). The caller should assure - that this limit is not exceeded. If it is exceeded, then gzprintf() will - return an error (0) with nothing written. - - In that last case, there may also be a buffer overflow with unpredictable - consequences, which is possible only if zlib was compiled with the insecure - functions sprintf() or vsprintf(), because the secure snprintf() and - vsnprintf() functions were not available. That would only be the case for - a non-ANSI C compiler. zlib may have been built without gzprintf() because - secure functions were not available and having gzprintf() be insecure was - not an option, in which case, gzprintf() returns Z_STREAM_ERROR. All of - these possibilities can be determined using zlibCompileFlags(). - - If a Z_BUF_ERROR is returned, then nothing was written due to a stall on - the non-blocking write destination. -*/ - -ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); -/* - Compress and write the given null-terminated string s to file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. - The number of characters written may be less than the length of the string - if the write destination is non-blocking. - - If the length of the string does not fit in an int, then -1 is returned - and nothing is written. -*/ - -ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len); -/* - Read and decompress bytes from file into buf, until len-1 characters are - read, or until a newline character is read and transferred to buf, or an - end-of-file condition is encountered. If any characters are read or if len - is one, the string is terminated with a null character. If no characters - are read due to an end-of-file or len is less than one, then the buffer is - left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If some data was read before an error, - then that data is returned until exhausted, after which the next call will - return NULL to signal the error. - - gzgets can be used on a file being concurrently written, and on a non- - blocking device, both as for gzread(). However lines may be broken in the - middle, leaving it up to the application to reassemble them as needed. -*/ - -ZEXTERN int ZEXPORT gzputc(gzFile file, int c); -/* - Compress and write c, converted to an unsigned char, into file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc(gzFile file); -/* - Read and decompress one byte from file. gzgetc returns this byte or -1 in - case of end of file or error. If some data was read before an error, then - that data is returned until exhausted, after which the next call will return - -1 to signal the error. - - This is implemented as a macro for speed. As such, it does not do all of - the checking the other functions do. I.e. it does not check to see if file - is NULL, nor whether the structure file points to has been clobbered or not. - - gzgetc can be used to read a gzip file on a non-blocking device. If the - input stalls and there is no uncompressed data to return, then gzgetc() will - return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be - called again. -*/ - -ZEXTERN int ZEXPORT gzungetc(int c, gzFile file); -/* - Push c back onto the stream for file to be read as the first character on - the next read. At least one character of push-back is always allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). - - gzungetc(-1, file) will force any pending seek to execute. Then gztell() - will report the position, even if the requested seek reached end of file. - This can be used to determine the number of uncompressed bytes in a gzip - file without having to read it into a buffer. -*/ - -ZEXTERN int ZEXPORT gzflush(gzFile file, int flush); -/* - Flush all pending output to file. The parameter flush is as in the - deflate() function. The return value is the zlib error number (see function - gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatenated gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, - z_off_t offset, int whence); - - Set the starting position to offset relative to whence for the next gzread - or gzwrite on file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. For reading or writing, any actual seeking is deferred - until the next read or write operation, or close operation when writing. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind(gzFile file); -/* - Rewind file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET). -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell(gzFile file); - - Return the starting position for the next gzread or gzwrite on file. - This position represents a number of bytes in the uncompressed data stream, - and is zero when starting, even if appending or reading a gzip stream from - the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file); - - Return the current compressed (actual) read or write offset of file. This - offset includes the count of bytes that precede the gzip stream, for example - when appending or when using gzdopen() for reading. When reading, the - offset does not include as yet unused buffered input. This information can - be used for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof(gzFile file); -/* - Return true (1) if the end-of-file indicator for file has been set while - reading, false (0) otherwise. Note that the end-of-file indicator is set - only if the read tried to go past the end of the input, but came up short. - Therefore, just like feof(), gzeof() may return false even if there is no - more data to read, in the event that the last read request was for the exact - number of bytes remaining in the input file. This will happen if the input - file size is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect(gzFile file); -/* - Return true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). If the input is being written concurrently or the device is non- - blocking, then gzdirect() may give a different answer once four bytes of - input have been accumulated, which is what is needed to confirm or deny a - gzip header. Before this, gzdirect() will return true (1). - - When writing, gzdirect() returns true (1) if transparent writing was - requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: - gzdirect() is not needed when writing. Transparent writing must be - explicitly requested, so the application already knows the answer. When - linking statically, using gzdirect() will include all of the zlib code for - gzip file reading and decompression, which may not be desired.) -*/ - -ZEXTERN int ZEXPORT gzclose(gzFile file); -/* - Flush all pending output for file, if necessary, close file and - deallocate the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the - last read ended in the middle of a gzip stream, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r(gzFile file); -ZEXTERN int ZEXPORT gzclose_w(gzFile file); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); -/* - Return the error message for the last error which occurred on file. - If errnum is not NULL, *errnum is set to zlib error number. If an error - occurred in the file system and not in the compression library, *errnum is - set to Z_ERRNO and the application may consult errno to get the exact error - code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr(gzFile file); -/* - Clear the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - -#endif /* !Z_SOLO */ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. An Adler-32 value is in the range of a 32-bit - unsigned integer. If buf is Z_NULL, this function returns the required - initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, - z_size_t len); -/* - Same as adler32(), but with a size_t length. Note that a long is 32 bits - on Windows. -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, - z_off_t len2); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note - that the z_off_t type (like off_t) is a signed integer. If len2 is - negative, the result has no meaning or utility. -*/ - -ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. - If buf is Z_NULL, this function returns the required initial value for the - crc. Pre- and post-conditioning (one's complement) is performed within this - function so it shouldn't be done by the application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf, - z_size_t len); -/* - Same as crc32(), but with a size_t length. Note that a long is 32 bits on - Windows. -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. len2 must be non-negative, otherwise zero is returned. -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2); - - Return the operator corresponding to length len2, to be used with - crc32_combine_op(). len2 must be non-negative, otherwise zero is returned. -*/ - -ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op); -/* - Give the same result as crc32_combine(), using op in place of len2. op is - is generated from len2 by crc32_combine_gen(). This will be faster than - crc32_combine() if the generated op is used more than once. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level, - const char *version, int stream_size); -ZEXTERN int ZEXPORT inflateInit_(z_streamp strm, - const char *version, int stream_size); -ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size); -ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, - const char *version, int stream_size); -ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size); -#ifdef Z_PREFIX_SET -# define z_deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) -# define z_inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) -# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) -# define z_inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ - (int)sizeof(z_stream)) -# define z_inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, (int)sizeof(z_stream)) -#else -# define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) -# define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) -# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) -# define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ - (int)sizeof(z_stream)) -# define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, (int)sizeof(z_stream)) -#endif - -#ifndef Z_SOLO - -/* gzgetc() macro and its supporting function and exposed data structure. Note - * that the real internal state is much larger than the exposed structure. - * This abbreviated structure exposes just enough for the gzgetc() macro. The - * user should not mess with these exposed elements, since their names or - * behavior could change in the future, perhaps even capriciously. They can - * only be used by the gzgetc() macro. You have been warned. - */ -struct gzFile_s { - unsigned have; - unsigned char *next; - z_off64_t pos; -}; -ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ -#ifdef Z_PREFIX_SET -# undef z_gzgetc -# define z_gzgetc(g) \ - ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) -#else -# define gzgetc(g) \ - ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) -#endif - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#ifdef Z_LARGE64 - ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); - ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); - ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); - ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); - ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); -#endif - -#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) -# ifdef Z_PREFIX_SET -# define z_gzopen z_gzopen64 -# define z_gzseek z_gzseek64 -# define z_gztell z_gztell64 -# define z_gzoffset z_gzoffset64 -# define z_adler32_combine z_adler32_combine64 -# define z_crc32_combine z_crc32_combine64 -# define z_crc32_combine_gen z_crc32_combine_gen64 -# else -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# define crc32_combine_gen crc32_combine_gen64 -# endif -# ifndef Z_LARGE64 - ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); - ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int); - ZEXTERN z_off_t ZEXPORT gztell64(gzFile); - ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile); - ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *); - ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int); - ZEXTERN z_off_t ZEXPORT gztell(gzFile); - ZEXTERN z_off_t ZEXPORT gzoffset(gzFile); - ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); - ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); - ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); -#endif - -#else /* Z_SOLO */ - - ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); - ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); - ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); - -#endif /* !Z_SOLO */ - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError(int); -ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); -ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); -ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int); -ZEXTERN int ZEXPORT inflateValidate(z_streamp, int); -ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp); -ZEXTERN int ZEXPORT inflateResetKeep(z_streamp); -ZEXTERN int ZEXPORT deflateResetKeep(z_streamp); -#if defined(_WIN32) && !defined(Z_SOLO) -ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path, - const char *mode); -#endif -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -ZEXTERN int ZEXPORTVA gzvprintf(gzFile file, - const char *format, - va_list va); -# endif -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.3.2.1, February xxth, 2026 + + Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 at https://datatracker.ietf.org/doc/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#ifdef ZLIB_BUILD +# include +#else +# include "zconf.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.3.2.1-motley" +#define ZLIB_VERNUM 0x1321 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 3 +#define ZLIB_VER_REVISION 2 +#define ZLIB_VER_SUBREVISION 1 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size); +typedef void (*free_func)(voidpf opaque, voidpf address); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion(void); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. total_in, total_out, adler, and msg are initialized. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more output + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six when the flush marker begins, in order to avoid + repeated flush markers upon calling deflate() again when avail_out == 0. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd(z_streamp strm); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit(z_streamp strm); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. total_in, total_out, adler, and + msg are initialized. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the input taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd(z_streamp strm); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2(z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy); + + This is another version of deflateInit with more compression options. The + fields zalloc, zfree and opaque must be initialized before by the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_RLE to limit match distances to one (run-length + encoding), or Z_HUFFMAN_ONLY to force Huffman encoding only (no string + matching). Filtered data consists mostly of small values with a somewhat + random distribution, as produced by the PNG filters. In this case, the + compression algorithm is tuned to compress them better. The effect of + Z_FILTERED is to force more Huffman coding and less string matching than the + default; it is intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. + Z_RLE is almost as fast as Z_HUFFMAN_ONLY, but should give better + compression for PNG image data than Huffman only. The degree of string + matching from most to none is: Z_DEFAULT_STRATEGY, Z_FILTERED, Z_RLE, then + Z_HUFFMAN_ONLY. The strategy parameter affects the compression ratio but + never the correctness of the compressed output, even if it is not set + optimally for the given data. Z_FIXED uses the default string matching, but + prevents the use of dynamic Huffman codes, allowing for a simpler decoder + for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm, + const Bytef *dictionary, + uInt dictLength); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm, + Bytef *dictionary, + uInt *dictLength); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, + z_streamp source); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset(z_streamp strm); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. total_in, total_out, adler, and msg are initialized. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams(z_streamp strm, + int level, + int strategy); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if there have been any deflate() calls since the + state was initialized or reset, then the input available so far is + compressed with the old level and strategy using deflate(strm, Z_BLOCK). + There are three approaches for the compression levels 0, 1..3, and 4..9 + respectively. The new level and strategy will take effect at the next call + of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune(z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen); +ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. + + delfateBound_z() is the same, but takes and returns a size_t length. Note + that a long is 32 bits on Windows. +*/ + +ZEXTERN int ZEXPORT deflatePending(z_streamp strm, + unsigned *pending, + int *bits); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. If an int is 16 bits and memLevel is 9, then + it is possible for the number of pending bytes to not fit in an unsigned. In + that case Z_BUF_ERROR is returned and *pending is set to the maximum value + of an unsigned. + */ + +ZEXTERN int ZEXPORT deflateUsed(z_streamp strm, + int *bits); +/* + deflateUsed() returns in *bits the most recent number of deflate bits used + in the last byte when flushing to a byte boundary. The result is in 1..8, or + 0 if there has not yet been a flush. This helps determine the location of + the last bit of a deflate stream. + + deflateUsed returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime(z_streamp strm, + int bits, + int value); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm, + gz_headerp head); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to the current operating system, with no + extra, name, or comment fields. The gzip header is returned to the default + state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, + int windowBits); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will *not* automatically decode concatenated gzip members. + inflate() will return Z_STREAM_END at the end of the gzip member. The state + would need to be reset to continue decoding a subsequent gzip member. This + *must* be done if there is more data after a gzip member, in order for the + decompression to be compliant with the gzip standard (RFC 1952). + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm, + const Bytef *dictionary, + uInt dictLength); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm, + Bytef *dictionary, + uInt *dictLength); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync(z_streamp strm); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current value of total_in + which indicates where valid compressed data was found. In the error case, + the application may repeatedly call inflateSync, providing more input each + time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, + z_streamp source); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset(z_streamp strm); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + total_in, total_out, adler, and msg are initialized. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2(z_streamp strm, + int windowBits); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime(z_streamp strm, + int bits, + int value); +/* + This function inserts bits in the inflate input stream. The intent is to + use inflatePrime() to start inflating at a bit position in the middle of a + byte. The provided bits will be used before any bytes are used from + next_in. This function should be used with raw inflate, before the first + inflate() call, after inflateInit2() or inflateReset(). It can also be used + after an inflate() return indicates the end of a deflate block or header + when using Z_BLOCK. bits must be less than or equal to 16, and that many of + the least significant bits of value will be inserted in the input. The + other bits in value can be non-zero, and will be ignored. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent, or if bits is out of range. If inflate was + in the middle of processing a header, trailer, or stored block lengths, then + it is possible for there to be only eight bits available in the bit buffer. + In that case, bits > 8 is considered out of range. However, when used as + outlined above, there will always be 16 bits available in the buffer for + insertion. As noted in its documentation above, inflate records the number + of bits in the bit buffer on return in data_type. 32 minus that is the + number of bits available for insertion. inflatePrime does not update + data_type with the new number of bits in buffer. +*/ + +ZEXTERN long ZEXPORT inflateMark(z_streamp strm); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, + gz_headerp head); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) The extra, name, and comment pointers + much each be either Z_NULL or point to space to store that information from + the header. If extra is not Z_NULL, then extra_max contains the maximum + number of bytes that can be written to extra. Once done is true, extra_len + contains the actual extra field length, and extra contains the extra field, + or that field truncated if extra_max is less than extra_len. If name is not + Z_NULL, then up to name_max characters, including the terminating zero, are + written there. If comment is not Z_NULL, then up to comm_max characters, + including the terminating zero, are written there. The application can tell + that the name or comment did not fit in the provided space by the absence of + a terminating zero. If any of extra, name, or comment are not present in + the header, then that field's pointer is set to Z_NULL. This allows the use + of deflateSetHeader() with the returned structure to duplicate the header. + Note that if those fields initially pointed to allocated memory, then the + application will need to save them elsewhere so that they can be eventually + freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits, + unsigned char FAR *window); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func)(void FAR *, + z_const unsigned char FAR * FAR *); +typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned); + +ZEXTERN int ZEXPORT inflateBack(z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags(void); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (all zeros is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() is not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + 27: 0 = gzprintf() present, 1 = not -- 1 means gzprintf() returns an error + + Remainder: + 28-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. The _z versions of the functions use the size_t + type for lengths. Note that a long is 32 bits on Windows. +*/ + +ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen); +ZEXTERN int ZEXPORT compress_z(Bytef *dest, z_size_t *destLen, + const Bytef *source, z_size_t sourceLen); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level); +ZEXTERN int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen, + const Bytef *source, z_size_t sourceLen, + int level); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen); +ZEXTERN z_size_t ZEXPORT compressBound_z(z_size_t sourceLen); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen); +ZEXTERN int ZEXPORT uncompress_z(Bytef *dest, z_size_t *destLen, + const Bytef *source, z_size_t sourceLen); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. On entry, *destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) On exit, *destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen); +ZEXTERN int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen, + const Bytef *source, z_size_t *sourceLen); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); + + Open the gzip (.gz) file at path for reading and decompressing, or + compressing and writing. The mode parameter is as in fopen ("rb" or "wb") + but can also include a compression level ("wb9") or a strategy: 'f' for + filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", + 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression + as in "wb9F". (See the description of deflateInit2 for more information + about the strategy parameter.) 'T' will request transparent writing or + appending with no compression and not using the gzip format. 'T' cannot be + used to force transparent reading. Transparent reading is automatically + performed if there is no gzip header at the start. Transparent reading can + be disabled with the 'G' option, which will instead return an error if there + is no gzip header. 'N' will open the file in non-blocking mode. + + 'a' can be used instead of 'w' to request that the gzip stream that will + be written be appended to the file. '+' will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + 'x' when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of 'e' when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. Note that if 'N' is in mode for non-blocking, the + open() itself can fail in order to not block. In that case gzopen() will + return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can + then be re-tried. If the application would like to block on opening the + file, then it can use open() without O_NONBLOCK, and then gzdopen() with the + resulting file descriptor and 'N' in the mode, which will set it to non- + blocking. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode); +/* + Associate a gzFile with the file descriptor fd. File descriptors are + obtained from calls like open, dup, creat, pipe or fileno (if the file has + been previously opened with fopen). The mode parameter is as in gzopen. An + 'e' in mode will set fd's flag to close the file on an execve() call. An 'N' + in mode will set fd's non-blocking flag. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size); +/* + Set the internal buffer size used by this library's functions for file to + size. The default buffer size is 8192 bytes. This function must be called + after gzopen() or gzdopen(), and before any other calls that read or write + the file. The buffer memory allocation is always deferred to the first read + or write. Three times that size in buffer space is allocated. A larger + buffer size of, for example, 64K or 128K bytes will noticeably increase the + speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy); +/* + Dynamically update the compression level and strategy for file. See the + description of deflateInit2 for the meaning of these parameters. Previously + provided data is flushed before applying the parameter changes. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len); +/* + Read and decompress up to len uncompressed bytes from file into buf. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread can be used to read a gzip file on a non-blocking device. If the + input stalls and there is no uncompressed data to return, then gzread() will + return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be + called again. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. If some data was read before an error, then that data is + returned until exhausted, after which the next call will signal the error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, + gzFile file); +/* + Read and decompress up to nitems items of size size from file into buf, + otherwise operating as gzread() does. This duplicates the interface of + stdio's fread(), with size_t request and return types. If the library + defines size_t, then z_size_t is identical to size_t. If not, then z_size_t + is an unsigned integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevertheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as that of fread() implementations in common libraries. This + could result in data loss if used with size != 1 when reading a concurrently + written file or a non-blocking file. In that case, use size == 1 or gzread() + instead. +*/ + +ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len); +/* + Compress and write the len uncompressed bytes at buf to file. gzwrite + returns the number of uncompressed bytes written, or 0 in case of error or + if len is 0. If the write destination is non-blocking, then gzwrite() may + return a number of bytes written that is not 0 and less than len. + + If len does not fit in an int, then 0 is returned and nothing is written. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, + z_size_t nitems, gzFile file); +/* + Compress and write nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. + + If writing a concurrently read file or a non-blocking file with size != 1, + a partial item could be written, with no way of knowing how much of it was + not written, resulting in data loss. In that case, use size == 1 or + gzwrite() instead. +*/ + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...); +#else +ZEXTERN int ZEXPORTVA gzprintf(); +#endif +/* + Convert, format, compress, and write the arguments (...) to file under + control of the string format, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. + + In that last case, there may also be a buffer overflow with unpredictable + consequences, which is possible only if zlib was compiled with the insecure + functions sprintf() or vsprintf(), because the secure snprintf() and + vsnprintf() functions were not available. That would only be the case for + a non-ANSI C compiler. zlib may have been built without gzprintf() because + secure functions were not available and having gzprintf() be insecure was + not an option, in which case, gzprintf() returns Z_STREAM_ERROR. All of + these possibilities can be determined using zlibCompileFlags(). + + If a Z_BUF_ERROR is returned, then nothing was written due to a stall on + the non-blocking write destination. +*/ + +ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); +/* + Compress and write the given null-terminated string s to file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. + The number of characters written may be less than the length of the string + if the write destination is non-blocking. + + If the length of the string does not fit in an int, then -1 is returned + and nothing is written. +*/ + +ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len); +/* + Read and decompress bytes from file into buf, until len-1 characters are + read, or until a newline character is read and transferred to buf, or an + end-of-file condition is encountered. If any characters are read or if len + is one, the string is terminated with a null character. If no characters + are read due to an end-of-file or len is less than one, then the buffer is + left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If some data was read before an error, + then that data is returned until exhausted, after which the next call will + return NULL to signal the error. + + gzgets can be used on a file being concurrently written, and on a non- + blocking device, both as for gzread(). However lines may be broken in the + middle, leaving it up to the application to reassemble them as needed. +*/ + +ZEXTERN int ZEXPORT gzputc(gzFile file, int c); +/* + Compress and write c, converted to an unsigned char, into file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc(gzFile file); +/* + Read and decompress one byte from file. gzgetc returns this byte or -1 in + case of end of file or error. If some data was read before an error, then + that data is returned until exhausted, after which the next call will return + -1 to signal the error. + + This is implemented as a macro for speed. As such, it does not do all of + the checking the other functions do. I.e. it does not check to see if file + is NULL, nor whether the structure file points to has been clobbered or not. + + gzgetc can be used to read a gzip file on a non-blocking device. If the + input stalls and there is no uncompressed data to return, then gzgetc() will + return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be + called again. +*/ + +ZEXTERN int ZEXPORT gzungetc(int c, gzFile file); +/* + Push c back onto the stream for file to be read as the first character on + the next read. At least one character of push-back is always allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). + + gzungetc(-1, file) will force any pending seek to execute. Then gztell() + will report the position, even if the requested seek reached end of file. + This can be used to determine the number of uncompressed bytes in a gzip + file without having to read it into a buffer. +*/ + +ZEXTERN int ZEXPORT gzflush(gzFile file, int flush); +/* + Flush all pending output to file. The parameter flush is as in the + deflate() function. The return value is the zlib error number (see function + gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, + z_off_t offset, int whence); + + Set the starting position to offset relative to whence for the next gzread + or gzwrite on file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. For reading or writing, any actual seeking is deferred + until the next read or write operation, or close operation when writing. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind(gzFile file); +/* + Rewind file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET). +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell(gzFile file); + + Return the starting position for the next gzread or gzwrite on file. + This position represents a number of bytes in the uncompressed data stream, + and is zero when starting, even if appending or reading a gzip stream from + the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file); + + Return the current compressed (actual) read or write offset of file. This + offset includes the count of bytes that precede the gzip stream, for example + when appending or when using gzdopen() for reading. When reading, the + offset does not include as yet unused buffered input. This information can + be used for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof(gzFile file); +/* + Return true (1) if the end-of-file indicator for file has been set while + reading, false (0) otherwise. Note that the end-of-file indicator is set + only if the read tried to go past the end of the input, but came up short. + Therefore, just like feof(), gzeof() may return false even if there is no + more data to read, in the event that the last read request was for the exact + number of bytes remaining in the input file. This will happen if the input + file size is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect(gzFile file); +/* + Return true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). If the input is being written concurrently or the device is non- + blocking, then gzdirect() may give a different answer once four bytes of + input have been accumulated, which is what is needed to confirm or deny a + gzip header. Before this, gzdirect() will return true (1). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose(gzFile file); +/* + Flush all pending output for file, if necessary, close file and + deallocate the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r(gzFile file); +ZEXTERN int ZEXPORT gzclose_w(gzFile file); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); +/* + Return the error message for the last error which occurred on file. + If errnum is not NULL, *errnum is set to zlib error number. If an error + occurred in the file system and not in the compression library, *errnum is + set to Z_ERRNO and the application may consult errno to get the exact error + code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr(gzFile file); +/* + Clear the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. An Adler-32 value is in the range of a 32-bit + unsigned integer. If buf is Z_NULL, this function returns the required + initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, + z_size_t len); +/* + Same as adler32(), but with a size_t length. Note that a long is 32 bits + on Windows. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, + z_off_t len2); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. + If buf is Z_NULL, this function returns the required initial value for the + crc. Pre- and post-conditioning (one's complement) is performed within this + function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf, + z_size_t len); +/* + Same as crc32(), but with a size_t length. Note that a long is 32 bits on + Windows. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. len2 must be non-negative, otherwise zero is returned. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2); + + Return the operator corresponding to length len2, to be used with + crc32_combine_op(). len2 must be non-negative, otherwise zero is returned. +*/ + +ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op); +/* + Give the same result as crc32_combine(), using op in place of len2. op is + is generated from len2 by crc32_combine_gen(). This will be faster than + crc32_combine() if the generated op is used more than once. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level, + const char *version, int stream_size); +ZEXTERN int ZEXPORT inflateInit_(z_streamp strm, + const char *version, int stream_size); +ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size); +ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, + const char *version, int stream_size); +ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); + ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int); + ZEXTERN z_off64_t ZEXPORT gztell64(gzFile); + ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile); + ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# define z_crc32_combine_gen z_crc32_combine_gen64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# define crc32_combine_gen crc32_combine_gen64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); + ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int); + ZEXTERN z_off_t ZEXPORT gztell64(gzFile); + ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile); + ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *); + ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int); + ZEXTERN z_off_t ZEXPORT gztell(gzFile); + ZEXTERN z_off_t ZEXPORT gzoffset(gzFile); + ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); + ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); + ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t); + ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t); + ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError(int); +ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); +ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int); +ZEXTERN int ZEXPORT inflateValidate(z_streamp, int); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp); +ZEXTERN int ZEXPORT inflateResetKeep(z_streamp); +ZEXTERN int ZEXPORT deflateResetKeep(z_streamp); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path, + const char *mode); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf(gzFile file, + const char *format, + va_list va); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/Minecraft.Client/Common/zlib/zutil.c b/Minecraft.Client/Common/zlib/zutil.c index 22f29aea0..0e30c5664 100644 --- a/Minecraft.Client/Common/zlib/zutil.c +++ b/Minecraft.Client/Common/zlib/zutil.c @@ -1,312 +1,312 @@ -/* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2026 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zutil.h" -#ifndef Z_SOLO -# include "gzguts.h" -#endif - -z_const char * const z_errmsg[10] = { - (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ - (z_const char *)"stream end", /* Z_STREAM_END 1 */ - (z_const char *)"", /* Z_OK 0 */ - (z_const char *)"file error", /* Z_ERRNO (-1) */ - (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ - (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ - (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ - (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ - (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ - (z_const char *)"" -}; - - -const char * ZEXPORT zlibVersion(void) { - return ZLIB_VERSION; -} - -uLong ZEXPORT zlibCompileFlags(void) { - uLong flags; - - flags = 0; - switch ((int)(sizeof(uInt))) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch ((int)(sizeof(uLong))) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch ((int)(sizeof(voidpf))) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch ((int)(sizeof(z_off_t))) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } -#ifdef ZLIB_DEBUG - flags += 1 << 8; -#endif - /* -#if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; -#endif - */ -#ifdef ZLIB_WINAPI - flags += 1 << 10; -#endif -#ifdef BUILDFIXED - flags += 1 << 12; -#endif -#ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; -#endif -#ifdef NO_GZCOMPRESS - flags += 1L << 16; -#endif -#ifdef NO_GZIP - flags += 1L << 17; -#endif -#ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; -#endif -#ifdef FASTEST - flags += 1L << 21; -#endif -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifdef NO_vsnprintf -# ifdef ZLIB_INSECURE - flags += 1L << 25; -# else - flags += 1L << 27; -# endif -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif -#else - flags += 1L << 24; -# ifdef NO_snprintf -# ifdef ZLIB_INSECURE - flags += 1L << 25; -# else - flags += 1L << 27; -# endif -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif -#endif - return flags; -} - -#ifdef ZLIB_DEBUG -#include -# ifndef verbose -# define verbose 0 -# endif -int ZLIB_INTERNAL z_verbose = verbose; - -void ZLIB_INTERNAL z_error(char *m) { - fprintf(stderr, "%s\n", m); - exit(1); -} -#endif - -/* exported to allow conversion of error code to string for compress() and - * uncompress() - */ -const char * ZEXPORT zError(int err) { - return ERR_MSG(err); -} - -#if defined(_WIN32_WCE) && _WIN32_WCE < 0x800 - /* The older Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; -#endif - -#ifndef HAVE_MEMCPY - -void ZLIB_INTERNAL zmemcpy(void FAR *dst, const void FAR *src, z_size_t n) { - uchf *p = dst; - const uchf *q = src; - while (n) { - *p++ = *q++; - n--; - } -} - -int ZLIB_INTERNAL zmemcmp(const void FAR *s1, const void FAR *s2, z_size_t n) { - const uchf *p = s1, *q = s2; - while (n) { - if (*p++ != *q++) - return (int)p[-1] - (int)q[-1]; - n--; - } - return 0; -} - -void ZLIB_INTERNAL zmemzero(void FAR *b, z_size_t len) { - uchf *p = b; - while (len) { - *p++ = 0; - len--; - } -} - -#endif - -#ifndef Z_SOLO - -#ifdef SYS16BIT - -#ifdef __TURBOC__ -/* Turbo C in 16-bit mode */ - -# define MY_ZCALLOC - -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes - * and farmalloc(64K) returns a pointer with an offset of 8, so we - * must fix the pointer. Warning: the pointer must be put back to its - * original form in order to free it, use zcfree(). - */ - -#define MAX_PTR 10 -/* 10*64K = 640K */ - -local int next_ptr = 0; - -typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; -} ptr_table; - -local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers - * to large buffers (64K). Such pointers are normalized with a zero offset. - * Since MSDOS is not a preemptive multitasking OS, this table is not - * protected from concurrent access. This hack doesn't work anyway on - * a protected system like OS/2. Use Microsoft C instead. - */ - -voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { - voidpf buf; - ulg bsize = (ulg)items*size; - - (void)opaque; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; -} - -void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - int n; - - (void)opaque; - - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - Assert(0, "zcfree: ptr not found"); -} - -#endif /* __TURBOC__ */ - - -#ifdef M_I86 -/* Microsoft C in 16-bit mode */ - -# define MY_ZCALLOC - -#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree -#endif - -voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) { - (void)opaque; - return _halloc((long)items, size); -} - -void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - (void)opaque; - _hfree(ptr); -} - -#endif /* M_I86 */ - -#endif /* SYS16BIT */ - - -#ifndef MY_ZCALLOC /* Any system without a special alloc function */ - -#ifndef STDC -extern voidp malloc(uInt size); -extern voidp calloc(uInt items, uInt size); -extern void free(voidpf ptr); -#endif - -voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { - (void)opaque; - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); -} - -void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { - (void)opaque; - free(ptr); -} - -#endif /* MY_ZCALLOC */ - -#endif /* !Z_SOLO */ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2026 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +z_const char * const z_errmsg[10] = { + (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ + (z_const char *)"stream end", /* Z_STREAM_END 1 */ + (z_const char *)"", /* Z_OK 0 */ + (z_const char *)"file error", /* Z_ERRNO (-1) */ + (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ + (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ + (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ + (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ + (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ + (z_const char *)"" +}; + + +const char * ZEXPORT zlibVersion(void) { + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags(void) { + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef ZLIB_DEBUG + flags += 1 << 8; +#endif + /* +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif + */ +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf +# ifdef ZLIB_INSECURE + flags += 1L << 25; +# else + flags += 1L << 27; +# endif +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf +# ifdef ZLIB_INSECURE + flags += 1L << 25; +# else + flags += 1L << 27; +# endif +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef ZLIB_DEBUG +#include +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error(char *m) { + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(int err) { + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) && _WIN32_WCE < 0x800 + /* The older Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(void FAR *dst, const void FAR *src, z_size_t n) { + uchf *p = dst; + const uchf *q = src; + while (n) { + *p++ = *q++; + n--; + } +} + +int ZLIB_INTERNAL zmemcmp(const void FAR *s1, const void FAR *s2, z_size_t n) { + const uchf *p = s1, *q = s2; + while (n) { + if (*p++ != *q++) + return (int)p[-1] - (int)q[-1]; + n--; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(void FAR *b, z_size_t len) { + uchf *p = b; + while (len) { + *p++ = 0; + len--; + } +} + +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { + voidpf buf; + ulg bsize = (ulg)items*size; + + (void)opaque; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + int n; + + (void)opaque; + + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) { + (void)opaque; + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + (void)opaque; + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc(uInt size); +extern voidp calloc(uInt items, uInt size); +extern void free(voidpf ptr); +#endif + +voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { + (void)opaque; + free(ptr); +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/Minecraft.Client/Common/zlib/zutil.h b/Minecraft.Client/Common/zlib/zutil.h index 179ca92ce..a9bc23ca6 100644 --- a/Minecraft.Client/Common/zlib/zutil.h +++ b/Minecraft.Client/Common/zlib/zutil.h @@ -1,331 +1,331 @@ -/* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#ifdef HAVE_HIDDEN -# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) -#else -# define ZLIB_INTERNAL -#endif - -#include "zlib.h" - -#if defined(STDC) && !defined(Z_SOLO) -# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) -# include -# endif -# include -# include -#endif - -#ifndef local -# define local static -#endif -/* since "static" is used to mean two completely different things in C, we - define "local" for the non-static meaning of "static", for readability - (compile with -Dlocal if your debugger can't find static symbols) */ - -extern const char deflate_copyright[]; -extern const char inflate_copyright[]; -extern const char inflate9_copyright[]; - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -#if !defined(Z_U8) && !defined(Z_SOLO) && defined(STDC) -# include -# if (ULONG_MAX == 0xffffffffffffffff) -# define Z_U8 unsigned long -# elif (ULLONG_MAX == 0xffffffffffffffff) -# define Z_U8 unsigned long long -# elif (ULONG_LONG_MAX == 0xffffffffffffffff) -# define Z_U8 unsigned long long -# elif (UINT_MAX == 0xffffffffffffffff) -# define Z_U8 unsigned -# endif -#endif - -extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ -#if MAX_WBITS < 9 || MAX_WBITS > 15 -# error MAX_WBITS must be in 9..15 -#endif -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# ifndef Z_SOLO -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 1 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 2 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#ifdef __370__ -# if __TARGET_LIB__ < 0x20000000 -# define OS_CODE 4 -# elif __TARGET_LIB__ < 0x40000000 -# define OS_CODE 11 -# else -# define OS_CODE 8 -# endif -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 5 -#endif - -#ifdef OS2 -# define OS_CODE 6 -# if defined(M_I86) && !defined(Z_SOLO) -# include -# endif -#endif - -#if defined(MACOS) -# define OS_CODE 7 -#endif - -#if defined(__acorn) || defined(__riscos) -# define OS_CODE 13 -#endif - -#if defined(WIN32) && !defined(__CYGWIN__) -# define OS_CODE 10 -#endif - -#ifdef _BEOS_ -# define OS_CODE 16 -#endif - -#ifdef __TOS_OS400__ -# define OS_CODE 18 -#endif - -#ifdef __APPLE__ -# define OS_CODE 19 -#endif - -#if defined(__BORLANDC__) && !defined(MSDOS) - #pragma warn -8004 - #pragma warn -8008 - #pragma warn -8066 -#endif - -/* provide prototypes for these when building zlib without LFS */ -#ifndef Z_LARGE64 - ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); - ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 3 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(pyr) || defined(Z_SOLO) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - void ZLIB_INTERNAL zmemcpy(void FAR *, const void FAR *, z_size_t); - int ZLIB_INTERNAL zmemcmp(const void FAR *, const void FAR *, z_size_t); - void ZLIB_INTERNAL zmemzero(void FAR *, z_size_t); -#endif - -/* Diagnostic functions */ -#ifdef ZLIB_DEBUG -# include - extern int ZLIB_INTERNAL z_verbose; - extern void ZLIB_INTERNAL z_error(char *m); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - -#ifndef Z_SOLO - voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, - unsigned size); - void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr); -#endif - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -/* Reverse the bytes in a 32-bit value */ -#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - -#ifdef Z_ONCE -/* - Create a local z_once() function depending on the availability of atomics. - */ - -/* Check for the availability of atomics. */ -#if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \ - !defined(__STDC_NO_ATOMICS__) - -#include -typedef struct { - atomic_flag begun; - atomic_int done; -} z_once_t; -#define Z_ONCE_INIT {ATOMIC_FLAG_INIT, 0} - -/* - Run the provided init() function exactly once, even if multiple threads - invoke once() at the same time. The state must be a once_t initialized with - Z_ONCE_INIT. - */ -local void z_once(z_once_t *state, void (*init)(void)) { - if (!atomic_load(&state->done)) { - if (atomic_flag_test_and_set(&state->begun)) - while (!atomic_load(&state->done)) - ; - else { - init(); - atomic_store(&state->done, 1); - } - } -} - -#else /* no atomics */ - -#warning zlib not thread-safe - -typedef struct z_once_s { - volatile int begun; - volatile int done; -} z_once_t; -#define Z_ONCE_INIT {0, 0} - -/* Test and set. Alas, not atomic, but tries to limit the period of - vulnerability. */ -local int test_and_set(int volatile *flag) { - int was; - - was = *flag; - *flag = 1; - return was; -} - -/* Run the provided init() function once. This is not thread-safe. */ -local void z_once(z_once_t *state, void (*init)(void)) { - if (!state->done) { - if (test_and_set(&state->begun)) - while (!state->done) - ; - else { - init(); - state->done = 1; - } - } -} - -#endif /* ?atomics */ - -#endif /* Z_ONCE */ - -#endif /* ZUTIL_H */ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +extern const char deflate_copyright[]; +extern const char inflate_copyright[]; +extern const char inflate9_copyright[]; + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +#if !defined(Z_U8) && !defined(Z_SOLO) && defined(STDC) +# include +# if (ULONG_MAX == 0xffffffffffffffff) +# define Z_U8 unsigned long +# elif (ULLONG_MAX == 0xffffffffffffffff) +# define Z_U8 unsigned long long +# elif (ULONG_LONG_MAX == 0xffffffffffffffff) +# define Z_U8 unsigned long long +# elif (UINT_MAX == 0xffffffffffffffff) +# define Z_U8 unsigned +# endif +#endif + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ +#if MAX_WBITS < 9 || MAX_WBITS > 15 +# error MAX_WBITS must be in 9..15 +#endif +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 1 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 2 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef __370__ +# if __TARGET_LIB__ < 0x20000000 +# define OS_CODE 4 +# elif __TARGET_LIB__ < 0x40000000 +# define OS_CODE 11 +# else +# define OS_CODE 8 +# endif +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 5 +#endif + +#ifdef OS2 +# define OS_CODE 6 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) +# define OS_CODE 7 +#endif + +#if defined(__acorn) || defined(__riscos) +# define OS_CODE 13 +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) +# define OS_CODE 10 +#endif + +#ifdef _BEOS_ +# define OS_CODE 16 +#endif + +#ifdef __TOS_OS400__ +# define OS_CODE 18 +#endif + +#ifdef __APPLE__ +# define OS_CODE 19 +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#ifndef Z_LARGE64 + ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t); + ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 3 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy(void FAR *, const void FAR *, z_size_t); + int ZLIB_INTERNAL zmemcmp(const void FAR *, const void FAR *, z_size_t); + void ZLIB_INTERNAL zmemzero(void FAR *, z_size_t); +#endif + +/* Diagnostic functions */ +#ifdef ZLIB_DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error(char *m); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, + unsigned size); + void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#ifdef Z_ONCE +/* + Create a local z_once() function depending on the availability of atomics. + */ + +/* Check for the availability of atomics. */ +#if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \ + !defined(__STDC_NO_ATOMICS__) + +#include +typedef struct { + atomic_flag begun; + atomic_int done; +} z_once_t; +#define Z_ONCE_INIT {ATOMIC_FLAG_INIT, 0} + +/* + Run the provided init() function exactly once, even if multiple threads + invoke once() at the same time. The state must be a once_t initialized with + Z_ONCE_INIT. + */ +local void z_once(z_once_t *state, void (*init)(void)) { + if (!atomic_load(&state->done)) { + if (atomic_flag_test_and_set(&state->begun)) + while (!atomic_load(&state->done)) + ; + else { + init(); + atomic_store(&state->done, 1); + } + } +} + +#else /* no atomics */ + +#warning zlib not thread-safe + +typedef struct z_once_s { + volatile int begun; + volatile int done; +} z_once_t; +#define Z_ONCE_INIT {0, 0} + +/* Test and set. Alas, not atomic, but tries to limit the period of + vulnerability. */ +local int test_and_set(int volatile *flag) { + int was; + + was = *flag; + *flag = 1; + return was; +} + +/* Run the provided init() function once. This is not thread-safe. */ +local void z_once(z_once_t *state, void (*init)(void)) { + if (!state->done) { + if (test_and_set(&state->begun)) + while (!state->done) + ; + else { + init(); + state->done = 1; + } + } +} + +#endif /* ?atomics */ + +#endif /* Z_ONCE */ + +#endif /* ZUTIL_H */ diff --git a/Minecraft.Client/CompassTexture.cpp b/Minecraft.Client/CompassTexture.cpp index bba43b783..148069916 100644 --- a/Minecraft.Client/CompassTexture.cpp +++ b/Minecraft.Client/CompassTexture.cpp @@ -7,13 +7,13 @@ #include "Texture.h" #include "CompassTexture.h" -CompassTexture *CompassTexture::instance = NULL; +CompassTexture *CompassTexture::instance = nullptr; CompassTexture::CompassTexture() : StitchedTexture(L"compass",L"compass") { instance = this; - m_dataTexture = NULL; + m_dataTexture = nullptr; m_iPad = XUSER_INDEX_ANY; rot = rota = 0.0; @@ -31,27 +31,27 @@ void CompassTexture::cycleFrames() { Minecraft *mc = Minecraft::GetInstance(); - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != nullptr && mc->localplayers[m_iPad] != nullptr) { updateFromPosition(mc->localplayers[m_iPad]->level, mc->localplayers[m_iPad]->x, mc->localplayers[m_iPad]->z, mc->localplayers[m_iPad]->yRot, false, false); } else { frame = 1; - updateFromPosition(NULL, 0, 0, 0, false, true); + updateFromPosition(nullptr, 0, 0, 0, false, true); } } void CompassTexture::updateFromPosition(Level *level, double x, double z, double yRot, bool noNeedle, bool instant) { double rott = 0; - if (level != NULL && !noNeedle) + if (level != nullptr && !noNeedle) { Pos *spawnPos = level->getSharedSpawnPos(); double xa = spawnPos->x - x; double za = spawnPos->z - z; delete spawnPos; - yRot = (int)yRot % 360; + yRot = static_cast(yRot) % 360; rott = -((yRot - 90) * PI / 180 - atan2(za, xa)); if (!level->dimension->isNaturalDimension()) { @@ -78,9 +78,9 @@ void CompassTexture::updateFromPosition(Level *level, double x, double z, double } // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) + if(m_dataTexture != nullptr) { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); + int newFrame = static_cast(((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); while (newFrame < 0) { newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); @@ -93,7 +93,7 @@ void CompassTexture::updateFromPosition(Level *level, double x, double z, double } else { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); + int newFrame = static_cast(((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); while (newFrame < 0) { newFrame = (newFrame + frames->size()) % frames->size(); @@ -118,7 +118,7 @@ int CompassTexture::getSourceHeight() const int CompassTexture::getFrames() { - if(m_dataTexture == NULL) + if(m_dataTexture == nullptr) { return StitchedTexture::getFrames(); } @@ -130,7 +130,7 @@ int CompassTexture::getFrames() void CompassTexture::freeFrameTextures() { - if(m_dataTexture == NULL) + if(m_dataTexture == nullptr) { StitchedTexture::freeFrameTextures(); } @@ -138,5 +138,5 @@ void CompassTexture::freeFrameTextures() bool CompassTexture::hasOwnData() { - return m_dataTexture == NULL; + return m_dataTexture == nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/ConnectScreen.cpp b/Minecraft.Client/ConnectScreen.cpp index 2cf005b6d..18d50a527 100644 --- a/Minecraft.Client/ConnectScreen.cpp +++ b/Minecraft.Client/ConnectScreen.cpp @@ -12,12 +12,12 @@ ConnectScreen::ConnectScreen(Minecraft *minecraft, const wstring& ip, int port) { aborted = false; // System.out.println("Connecting to " + ip + ", " + port); - minecraft->setLevel(NULL); + minecraft->setLevel(nullptr); #if 1 // 4J - removed from separate thread, but need to investigate what we actually need here connection = new ClientConnection(minecraft, ip, port); if (aborted) return; - connection->send( shared_ptr( new PreLoginPacket(minecraft->user->name) ) ); + connection->send(std::make_shared(minecraft->user->name)); #else new Thread() { @@ -45,7 +45,7 @@ ConnectScreen::ConnectScreen(Minecraft *minecraft, const wstring& ip, int port) void ConnectScreen::tick() { - if (connection != NULL) + if (connection != nullptr) { connection->tick(); } @@ -69,7 +69,7 @@ void ConnectScreen::buttonClicked(Button *button) if (button->id == 0) { aborted = true; - if (connection != NULL) connection->close(); + if (connection != nullptr) connection->close(); minecraft->setScreen(new TitleScreen()); } } @@ -80,7 +80,7 @@ void ConnectScreen::render(int xm, int ym, float a) Language *language = Language::getInstance(); - if (connection == NULL) + if (connection == nullptr) { drawCenteredString(font, language->getElement(L"connect.connecting"), width / 2, height / 2 - 50, 0xffffff); drawCenteredString(font, L"", width / 2, height / 2 - 10, 0xffffff); diff --git a/Minecraft.Client/CreateWorldScreen.cpp b/Minecraft.Client/CreateWorldScreen.cpp index 1a8972035..9c31747a8 100644 --- a/Minecraft.Client/CreateWorldScreen.cpp +++ b/Minecraft.Client/CreateWorldScreen.cpp @@ -70,7 +70,7 @@ wstring CreateWorldScreen::findAvailableFolderName(LevelStorageSource *levelSour wstring folder2 = folder; // 4J - copy input as it is const #if 0 - while (levelSource->getDataTagFor(folder2) != NULL) + while (levelSource->getDataTagFor(folder2) != nullptr) { folder2 = folder2 + L"-"; } @@ -93,7 +93,7 @@ void CreateWorldScreen::buttonClicked(Button *button) else if (button->id == 0) { // note: code copied from SelectWorldScreen - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); if (done) return; done = true; @@ -119,7 +119,7 @@ void CreateWorldScreen::buttonClicked(Button *button) #if 0 minecraft->gameMode = new SurvivalMode(minecraft); minecraft->selectLevel(resultFolder, nameEdit->getValue(), seedValue); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); #endif } diff --git a/Minecraft.Client/CreeperRenderer.cpp b/Minecraft.Client/CreeperRenderer.cpp index a9d16314f..bcec52150 100644 --- a/Minecraft.Client/CreeperRenderer.cpp +++ b/Minecraft.Client/CreeperRenderer.cpp @@ -34,9 +34,9 @@ int CreeperRenderer::getOverlayColor(shared_ptr mob, float br, flo float step = creeper->getSwelling(a); - if ((int) (step * 10) % 2 == 0) return 0; + if (static_cast(step * 10) % 2 == 0) return 0; - int _a = (int) (step * 0.2f * 255) + 25; // 4J - added 25 here as our entities are rendered with alpha test still enabled, and so anything less is invisible + int _a = static_cast(step * 0.2f * 255) + 25; // 4J - added 25 here as our entities are rendered with alpha test still enabled, and so anything less is invisible if (_a < 0) _a = 0; if (_a > 255) _a = 255; diff --git a/Minecraft.Client/CritParticle2.cpp b/Minecraft.Client/CritParticle2.cpp index 363e8f08d..fe64b91e4 100644 --- a/Minecraft.Client/CritParticle2.cpp +++ b/Minecraft.Client/CritParticle2.cpp @@ -11,12 +11,12 @@ void CritParticle2::_init(double xa, double ya, double za, float scale) yd += ya * 0.4; zd += za * 0.4; - rCol = gCol = bCol = (float) (Math::random() * 0.3f + 0.6f); + rCol = gCol = bCol = static_cast(Math::random() * 0.3f + 0.6f); size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (6 / (Math::random() * 0.8 + 0.6)); + lifetime = static_cast(6 / (Math::random() * 0.8 + 0.6)); lifetime *= scale; noPhysics = false; diff --git a/Minecraft.Client/DLCTexturePack.cpp b/Minecraft.Client/DLCTexturePack.cpp index 553128d96..f1304a9ef 100644 --- a/Minecraft.Client/DLCTexturePack.cpp +++ b/Minecraft.Client/DLCTexturePack.cpp @@ -9,6 +9,7 @@ #include "Common\DLC\DLCLocalisationFile.h" #include "..\Minecraft.World\StringHelpers.h" #include "StringTable.h" +#include "Common/UI/UI.h" #include "Common\DLC\DLCAudioFile.h" #if defined _XBOX || defined _WINDOWS64 @@ -16,27 +17,27 @@ #include "Xbox\XML\xmlFilesCallback.h" #endif -DLCTexturePack::DLCTexturePack(DWORD id, DLCPack *pack, TexturePack *fallback) : AbstractTexturePack(id, NULL, pack->getName(), fallback) +DLCTexturePack::DLCTexturePack(DWORD id, DLCPack *pack, TexturePack *fallback) : AbstractTexturePack(id, nullptr, pack->getName(), fallback) { m_dlcInfoPack = pack; - m_dlcDataPack = NULL; + m_dlcDataPack = nullptr; bUILoaded = false; m_bLoadingData = false; m_bHasLoadedData = false; - m_archiveFile = NULL; + m_archiveFile = nullptr; if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); m_bUsingDefaultColourTable = true; - m_stringTable = NULL; + m_stringTable = nullptr; #ifdef _XBOX - m_pStreamedWaveBank=NULL; - m_pSoundBank=NULL; + m_pStreamedWaveBank=nullptr; + m_pSoundBank=nullptr; #endif if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")) { - DLCLocalisationFile *localisationFile = (DLCLocalisationFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc"); + DLCLocalisationFile *localisationFile = static_cast(m_dlcInfoPack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")); m_stringTable = localisationFile->getStringTable(); } @@ -51,7 +52,7 @@ void DLCTexturePack::loadIcon() { if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"icon.png")) { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"icon.png"); + DLCTextureFile *textureFile = static_cast(m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"icon.png")); m_iconData = textureFile->getData(m_iconSize); } else @@ -64,7 +65,7 @@ void DLCTexturePack::loadComparison() { if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"comparison.png")) { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"comparison.png"); + DLCTextureFile *textureFile = static_cast(m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"comparison.png")); m_comparisonData = textureFile->getData(m_comparisonSize); } } @@ -75,7 +76,7 @@ void DLCTexturePack::loadName() if(m_dlcInfoPack->GetPackID()&1024) { - if(m_stringTable != NULL) + if(m_stringTable != nullptr) { texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); m_wsWorldName=m_stringTable->getString(L"IDS_WORLD_NAME"); @@ -83,7 +84,7 @@ void DLCTexturePack::loadName() } else { - if(m_stringTable != NULL) + if(m_stringTable != nullptr) { texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); } @@ -95,7 +96,7 @@ void DLCTexturePack::loadDescription() { desc1 = L""; - if(m_stringTable != NULL) + if(m_stringTable != nullptr) { desc1 = m_stringTable->getString(L"IDS_TP_DESCRIPTION"); } @@ -115,15 +116,15 @@ InputStream *DLCTexturePack::getResourceImplementation(const wstring &name) //th // 4J Stu - We should never call this function #ifndef _CONTENT_PACKAGE __debugbreak(); - if(hasFile(name)) return NULL; + if(hasFile(name)) return nullptr; #endif - return NULL; //resource; + return nullptr; //resource; } bool DLCTexturePack::hasFile(const wstring &name) { bool hasFile = false; - if(m_dlcDataPack != NULL) hasFile = m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_Texture, name); + if(m_dlcDataPack != nullptr) hasFile = m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_Texture, name); return hasFile; } @@ -164,23 +165,23 @@ DLCPack * DLCTexturePack::getDLCPack() void DLCTexturePack::loadColourTable() { // Load the game colours - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, L"colours.col")) + if(m_dlcDataPack != nullptr && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, L"colours.col")) { - DLCColourTableFile *colourFile = (DLCColourTableFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_ColourTable, L"colours.col"); + DLCColourTableFile *colourFile = static_cast(m_dlcDataPack->getFile(DLCManager::e_DLCType_ColourTable, L"colours.col")); m_colourTable = colourFile->getColourTable(); m_bUsingDefaultColourTable = false; } else { // 4J Stu - We can delete the default colour table, but not the one from the DLCColourTableFile - if(!m_bUsingDefaultColourTable) m_colourTable = NULL; + if(!m_bUsingDefaultColourTable) m_colourTable = nullptr; loadDefaultColourTable(); m_bUsingDefaultColourTable = true; } // Load the text colours #ifdef _XBOX - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) + if(m_dlcDataPack != nullptr && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) { DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); @@ -205,7 +206,7 @@ void DLCTexturePack::loadColourTable() swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#xuiscene_colourtable.xur",pbData, dwSize); HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,szResourceLocator, NULL, &hScene); + HRESULT hr = XuiSceneCreate(szResourceLocator,szResourceLocator, nullptr, &hScene); if(HRESULT_SUCCEEDED(hr)) { @@ -274,7 +275,7 @@ wstring DLCTexturePack::getFilePath(DWORD packId, wstring filename, bool bAddDat int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicenceMask) { - DLCTexturePack *texturePack = (DLCTexturePack *)pParam; + DLCTexturePack *texturePack = static_cast(pParam); texturePack->m_bLoadingData = false; if(dwErr!=ERROR_SUCCESS) { @@ -294,11 +295,11 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen if(!app.m_dlcManager.readDLCDataFile(dwFilesProcessed, getFilePath(texturePack->m_dlcInfoPack->GetPackID(), dataFilePath),texturePack->m_dlcDataPack)) { delete texturePack->m_dlcDataPack; - texturePack->m_dlcDataPack = NULL; + texturePack->m_dlcDataPack = nullptr; } // Load the UI data - if(texturePack->m_dlcDataPack != NULL) + if(texturePack->m_dlcDataPack != nullptr) { #ifdef _XBOX File xzpPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), wstring(L"TexturePack.xzp") ) ); @@ -310,10 +311,10 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); if( fileHandle != INVALID_HANDLE_VALUE ) @@ -321,7 +322,7 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen DWORD dwFileSize = xzpPath.length(); DWORD bytesRead; PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL success = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL success = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); CloseHandle(fileHandle); if(success) { @@ -342,12 +343,12 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen */ DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if (levelGen != NULL && !levelGen->hasLoadedData()) + if (levelGen != nullptr && !levelGen->hasLoadedData()) { int gameRulesCount = pack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader); for(int i = 0; i < gameRulesCount; ++i) { - DLCGameRulesHeader *dlcFile = (DLCGameRulesHeader *) pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i); + DLCGameRulesHeader *dlcFile = static_cast(pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i)); if (!dlcFile->getGrfPath().empty()) { @@ -361,10 +362,10 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #else const char *pchFilename=wstringtofilename(grf.getPath()); @@ -372,10 +373,10 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #endif @@ -384,7 +385,7 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen DWORD dwFileSize = grf.length(); DWORD bytesRead; PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); @@ -413,10 +414,10 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #else const char *pchFilename=wstringtofilename(grf.getPath()); @@ -424,18 +425,18 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen pchFilename, // file name GENERIC_READ, // access mode 0, // share mode // TODO 4J Stu - Will we need to share file? Probably not but... - NULL, // Unused + nullptr, // Unused OPEN_EXISTING , // how to create // TODO 4J Stu - Assuming that the file already exists if we are opening to read from it FILE_FLAG_SEQUENTIAL_SCAN, // file attributes - NULL // Unsupported + nullptr // Unsupported ); #endif if( fileHandle != INVALID_HANDLE_VALUE ) { - DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,NULL); + DWORD bytesRead,dwFileSize = GetFileSize(fileHandle,nullptr); PBYTE pbData = (PBYTE) new BYTE[dwFileSize]; - BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,NULL); + BOOL bSuccess = ReadFile(fileHandle,pbData,dwFileSize,&bytesRead,nullptr); if(bSuccess==FALSE) { app.FatalLoadError(); @@ -469,7 +470,7 @@ int DLCTexturePack::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD dwLicen //DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); if(pack->getDLCItemsCount(DLCManager::e_DLCType_Audio)>0) { - DLCAudioFile *dlcFile = (DLCAudioFile *) pack->getFile(DLCManager::e_DLCType_Audio, 0); + DLCAudioFile *dlcFile = static_cast(pack->getFile(DLCManager::e_DLCType_Audio, 0)); texturePack->setHasAudio(true); // init the streaming sound ids for this texture pack int iOverworldStart, iNetherStart, iEndStart; @@ -513,7 +514,7 @@ void DLCTexturePack::loadUI() //L"memory://0123ABCD,21A3#skin_default.xur" // Load new skin - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) + if(m_dlcDataPack != nullptr && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) { DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); @@ -527,7 +528,7 @@ void DLCTexturePack::loadUI() XuiFreeVisuals(L""); - HRESULT hr = app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); + HRESULT hr = app.LoadSkin(szResourceLocator,nullptr);//L"TexturePack"); if(HRESULT_SUCCEEDED(hr)) { bUILoaded = true; @@ -577,7 +578,7 @@ void DLCTexturePack::unloadUI() AbstractTexturePack::unloadUI(); app.m_dlcManager.removePack(m_dlcDataPack); - m_dlcDataPack = NULL; + m_dlcDataPack = nullptr; delete m_archiveFile; m_bHasLoadedData = false; @@ -587,9 +588,9 @@ void DLCTexturePack::unloadUI() wstring DLCTexturePack::getXuiRootPath() { wstring path = L""; - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) + if(m_dlcDataPack != nullptr && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); + DLCUIDataFile *dataFile = static_cast(m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")); DWORD dwSize = 0; PBYTE pbData = dataFile->getData(dwSize); diff --git a/Minecraft.Client/DLCTexturePack.h b/Minecraft.Client/DLCTexturePack.h index 153f3d438..595c47dac 100644 --- a/Minecraft.Client/DLCTexturePack.h +++ b/Minecraft.Client/DLCTexturePack.h @@ -50,7 +50,7 @@ public: bool isTerrainUpdateCompatible(); // 4J Added - virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=NULL); + virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=nullptr); virtual wstring getAnimationString(const wstring &textureName, const wstring &path); virtual BufferedImage *getImageResource(const wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const wstring &drive =L""); virtual void loadColourTable(); diff --git a/Minecraft.Client/DeathScreen.cpp b/Minecraft.Client/DeathScreen.cpp index e7ab13285..0e9cfb191 100644 --- a/Minecraft.Client/DeathScreen.cpp +++ b/Minecraft.Client/DeathScreen.cpp @@ -11,7 +11,7 @@ void DeathScreen::init() buttons.push_back(new Button(1, width / 2 - 100, height / 4 + 24 * 3, L"Respawn")); buttons.push_back(new Button(2, width / 2 - 100, height / 4 + 24 * 4, L"Title menu")); - if (minecraft->user == NULL) + if (minecraft->user == nullptr) { buttons[1]->active = false; } @@ -30,12 +30,12 @@ void DeathScreen::buttonClicked(Button *button) if (button->id == 1) { minecraft->player->respawn(); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft.setScreen(new NewLevelScreen(this)); } if (button->id == 2) { - minecraft->setLevel(NULL); + minecraft->setLevel(nullptr); minecraft->setScreen(new TitleScreen()); } } diff --git a/Minecraft.Client/DefaultRenderer.h b/Minecraft.Client/DefaultRenderer.h index 04b953907..28630de29 100644 --- a/Minecraft.Client/DefaultRenderer.h +++ b/Minecraft.Client/DefaultRenderer.h @@ -5,5 +5,5 @@ class DefaultRenderer : public EntityRenderer { public: virtual void render(shared_ptr entity, double x, double y, double z, float rot, float a); - virtual ResourceLocation *getTextureLocation(shared_ptr mob) { return NULL; }; + virtual ResourceLocation *getTextureLocation(shared_ptr mob) { return nullptr; }; }; \ No newline at end of file diff --git a/Minecraft.Client/DefaultTexturePack.cpp b/Minecraft.Client/DefaultTexturePack.cpp index d2974b6d0..d2712404b 100644 --- a/Minecraft.Client/DefaultTexturePack.cpp +++ b/Minecraft.Client/DefaultTexturePack.cpp @@ -4,7 +4,7 @@ #include "..\Minecraft.World\StringHelpers.h" -DefaultTexturePack::DefaultTexturePack() : AbstractTexturePack(0, NULL, L"Minecraft", NULL) +DefaultTexturePack::DefaultTexturePack() : AbstractTexturePack(0, nullptr, L"Minecraft", nullptr) { // 4J Stu - These calls need to be in the most derived version of the class loadIcon(); @@ -20,7 +20,7 @@ void DefaultTexturePack::loadIcon() 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); UINT size = 0; @@ -102,7 +102,7 @@ InputStream *DefaultTexturePack::getResourceImplementation(const wstring &name)/ #endif InputStream *resource = InputStream::getResourceAsStream(wDrive + name); //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) + //if (stream == nullptr) //{ // throw new FileNotFoundException(name); //} diff --git a/Minecraft.Client/DefaultTexturePack.h b/Minecraft.Client/DefaultTexturePack.h index 9aa87a07a..5fd0b40c4 100644 --- a/Minecraft.Client/DefaultTexturePack.h +++ b/Minecraft.Client/DefaultTexturePack.h @@ -5,7 +5,7 @@ class DefaultTexturePack : public AbstractTexturePack { public: DefaultTexturePack(); - DLCPack * getDLCPack() {return NULL;} + DLCPack * getDLCPack() {return nullptr;} protected: //@Override diff --git a/Minecraft.Client/DerivedServerLevel.cpp b/Minecraft.Client/DerivedServerLevel.cpp index a67408d70..78de818de 100644 --- a/Minecraft.Client/DerivedServerLevel.cpp +++ b/Minecraft.Client/DerivedServerLevel.cpp @@ -10,7 +10,7 @@ DerivedServerLevel::DerivedServerLevel(MinecraftServer *server, shared_ptrsavedDataStorage) { delete this->savedDataStorage; - this->savedDataStorage=NULL; + this->savedDataStorage=nullptr; } this->savedDataStorage = wrapped->savedDataStorage; levelData = new DerivedLevelData(wrapped->getLevelData()); @@ -19,7 +19,7 @@ DerivedServerLevel::DerivedServerLevel(MinecraftServer *server, shared_ptrsavedDataStorage=NULL; + this->savedDataStorage=nullptr; } void DerivedServerLevel::saveLevelData() diff --git a/Minecraft.Client/DisconnectedScreen.cpp b/Minecraft.Client/DisconnectedScreen.cpp index b445e4d07..800df73f4 100644 --- a/Minecraft.Client/DisconnectedScreen.cpp +++ b/Minecraft.Client/DisconnectedScreen.cpp @@ -9,7 +9,7 @@ DisconnectedScreen::DisconnectedScreen(const wstring& title, const wstring reaso Language *language = Language::getInstance(); this->title = language->getElement(title); - if (reasonObjects != NULL) + if (reasonObjects != nullptr) { this->reason = language->getElement(reason, reasonObjects); } diff --git a/Minecraft.Client/DragonBreathParticle.cpp b/Minecraft.Client/DragonBreathParticle.cpp index 0d0f75f33..3fd90806b 100644 --- a/Minecraft.Client/DragonBreathParticle.cpp +++ b/Minecraft.Client/DragonBreathParticle.cpp @@ -24,8 +24,8 @@ void DragonBreathParticle::init(Level *level, double x, double y, double z, doub size *= scale; oSize = size; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = static_cast(20 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(lifetime * scale); noPhysics = false; m_bHasHitGround = false; diff --git a/Minecraft.Client/DragonModel.cpp b/Minecraft.Client/DragonModel.cpp index 9e0499a9f..f1f36743a 100644 --- a/Minecraft.Client/DragonModel.cpp +++ b/Minecraft.Client/DragonModel.cpp @@ -159,7 +159,7 @@ void DragonModel::render(shared_ptr entity, float time, float r, float b rr = (float) Mth::cos(i * 0.45f + roff) * 0.15f; neck->yRot = rotWrap(dragon->getHeadPartYRotDiff(i, start, p)) * PI / 180.0f * rotScale; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - neck->xRot = rr + (float) (dragon->getHeadPartYOffset(i, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J replaced "p[1] - start[1]" with call to getHeadPartYOffset + neck->xRot = rr + static_cast(dragon->getHeadPartYOffset(i, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J replaced "p[1] - start[1]" with call to getHeadPartYOffset neck->zRot = -rotWrap(p[0] - rot) * PI / 180.0f * rotScale; neck->y = yy; @@ -176,7 +176,7 @@ void DragonModel::render(shared_ptr entity, float time, float r, float b head->x = xx; dragon->getLatencyPos(p, 0, a); head->yRot = rotWrap(dragon->getHeadPartYRotDiff(6, start, p)) * PI / 180.0f * 1; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - head->xRot = (float) (dragon->getHeadPartYOffset(6, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J Added + head->xRot = static_cast(dragon->getHeadPartYOffset(6, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J Added head->zRot = -rotWrap(p[0] - rot) * PI / 180 * 1; head->render(scale,usecompiled); glPushMatrix(); @@ -226,7 +226,7 @@ void DragonModel::render(shared_ptr entity, float time, float r, float b dragon->getLatencyPos(p, 12 + i, a); rr += Mth::sin(i * 0.45f + roff) * 0.05f; neck->yRot = (rotWrap(p[0] - start[0]) * rotScale + 180) * PI / 180; - neck->xRot = rr + (float) (p[1] - start[1]) * PI / 180 * rotScale * 5; + neck->xRot = rr + static_cast(p[1] - start[1]) * PI / 180 * rotScale * 5; neck->zRot = rotWrap(p[0] - rot) * PI / 180 * rotScale; neck->y = yy; neck->z = zz; @@ -244,5 +244,5 @@ float DragonModel::rotWrap(double d) d -= 360; while (d < -180) d += 360; - return (float) d; + return static_cast(d); } \ No newline at end of file diff --git a/Minecraft.Client/DripParticle.cpp b/Minecraft.Client/DripParticle.cpp index 9463976e6..d7202b078 100644 --- a/Minecraft.Client/DripParticle.cpp +++ b/Minecraft.Client/DripParticle.cpp @@ -30,7 +30,7 @@ DripParticle::DripParticle(Level *level, double x, double y, double z, Material this->material = material; stuckTime = 40; - lifetime = (int) (64 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(64 / (Math::random() * 0.8 + 0.2)); xd = yd = zd = 0; } diff --git a/Minecraft.Client/Durango/4JLibs/inc/4J_Input.h b/Minecraft.Client/Durango/4JLibs/inc/4J_Input.h index 884f281e1..a24d61169 100644 --- a/Minecraft.Client/Durango/4JLibs/inc/4J_Input.h +++ b/Minecraft.Client/Durango/4JLibs/inc/4J_Input.h @@ -61,8 +61,8 @@ STRING_VERIFY_RESPONSE; class C4JStringTable { public: - LPCWSTR Lookup(LPCWSTR szId) {return NULL;} - LPCWSTR Lookup(UINT nIndex) {return NULL;} + LPCWSTR Lookup(LPCWSTR szId) {return nullptr;} + LPCWSTR Lookup(UINT nIndex) {return nullptr;} void Clear(); HRESULT Load(LPCWSTR szId) {return S_OK;} }; @@ -126,8 +126,8 @@ public: void SetMenuDisplayed(int iPad, bool bVal); -// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); -// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); +// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); +// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); EKeyboardResult RequestKeyboard(LPCWSTR Title, LPCWSTR Text, DWORD dwPad, int iMaxChars, int( *Func)(LPVOID,const bool),LPVOID lpParam,C_4JInput::EKeyboardMode eMode); void DestroyKeyboard(); diff --git a/Minecraft.Client/Durango/4JLibs/inc/4J_Profile.h b/Minecraft.Client/Durango/4JLibs/inc/4J_Profile.h index dab464171..961b5d2a7 100644 --- a/Minecraft.Client/Durango/4JLibs/inc/4J_Profile.h +++ b/Minecraft.Client/Durango/4JLibs/inc/4J_Profile.h @@ -132,7 +132,7 @@ public: // ACHIEVEMENTS & AWARDS //void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - // CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); + // CXuiStringTable*pStringTable=nullptr, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=nullptr, unsigned int uiThemeSize=0L); //int GetAwardId(int iAwardNumber); eAwardType GetAwardType(int iAwardNumber); bool CanBeAwarded(int iQuadrant, int iAwardNumber); diff --git a/Minecraft.Client/Durango/4JLibs/inc/4J_Render.h b/Minecraft.Client/Durango/4JLibs/inc/4J_Render.h index 737caa98b..fb16ccb32 100644 --- a/Minecraft.Client/Durango/4JLibs/inc/4J_Render.h +++ b/Minecraft.Client/Durango/4JLibs/inc/4J_Render.h @@ -16,8 +16,8 @@ public: int GetType() { return m_type; } void *GetBufferPointer() { return m_pBuffer; } int GetBufferSize() { return m_bufferSize; } - void Release() { free(m_pBuffer); m_pBuffer = NULL; } - bool Allocated() { return m_pBuffer != NULL; } + void Release() { free(m_pBuffer); m_pBuffer = nullptr; } + bool Allocated() { return m_pBuffer != nullptr; } }; typedef struct @@ -60,7 +60,7 @@ public: void StartFrame(); void DoScreenGrabOnNextPresent(); void Present(); - void Clear(int flags, D3D11_RECT *pRect = NULL); + void Clear(int flags, D3D11_RECT *pRect = nullptr); void SetClearColour(const float colourRGBA[4]); bool IsWidescreen(); bool IsHiDef(); diff --git a/Minecraft.Client/Durango/4JLibs/inc/4J_Storage.h b/Minecraft.Client/Durango/4JLibs/inc/4J_Storage.h index be5d57fd7..624939520 100644 --- a/Minecraft.Client/Durango/4JLibs/inc/4J_Storage.h +++ b/Minecraft.Client/Durango/4JLibs/inc/4J_Storage.h @@ -378,7 +378,7 @@ public: // Get details of existing savedata C4JStorage::ESaveGameState GetSavesInfo(int iPad,int ( *Func)(LPVOID lpParam,SAVE_DETAILS *pSaveDetails,const bool),LPVOID lpParam,char *pszSavePackName); // Start search - PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or NULL if not yet received) + PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or nullptr if not yet received) void ClearSavesInfo(); // Clears results C4JStorage::ESaveGameState LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo,int( *Func)(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes), LPVOID lpParam, bool force=false); // Get the thumbnail for an individual save referenced by pSaveInfo @@ -442,8 +442,8 @@ public: void SetLicenseChangeFn(void( *Func)(void)); XCONTENT_DATA& GetDLC(DWORD dw); - DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPWSTR szMountDrive = NULL); - DWORD UnmountInstalledDLC(LPWSTR szMountDrive = NULL); + DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPWSTR szMountDrive = nullptr); + DWORD UnmountInstalledDLC(LPWSTR szMountDrive = nullptr); void GetMountedDLCFileList(const char* szMountDrive, std::vector& fileList); std::wstring GetMountedPath(std::wstring szMount); XCONTENT_DATA * GetInstalledDLC(WCHAR *wszProductID); @@ -470,10 +470,10 @@ public: // TMS++ C4JStorage::ETMSStatus TMSPP_GetUserQuotaInfo(C4JStorage::eGlobalStorage eStorageFacility,int iPad);//,TMSCLIENT_CALLBACK Func,LPVOID lpParam, int iUserData=0); - eTitleStorageState TMSPP_WriteFile(int iQuadrant,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPWSTR wszFilename,BYTE *pbBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0); + eTitleStorageState TMSPP_WriteFile(int iQuadrant,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPWSTR wszFilename,BYTE *pbBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); eTitleStorageState TMSPP_ReadFile(int iQuadrant,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPWSTR wszFilename,int( *Func)(LPVOID,int,int,LPVOID, WCHAR *),LPVOID lpParam, int iUserData); eTitleStorageState TMSPP_DeleteFile(int iQuadrant,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPWSTR wszFilename,int( *Func)(LPVOID,int,int),LPVOID lpParam, int iUserData); - eTitleStorageState TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,int( *Func)(LPVOID,int,int,LPVOID,WCHAR *)=NULL,LPVOID lpParam=NULL, int iUserData=0); + eTitleStorageState TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,int( *Func)(LPVOID,int,int,LPVOID,WCHAR *)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); bool TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const wstring &Filename); eTitleStorageState TMSPP_GetTitleStorageState(int iPad); diff --git a/Minecraft.Client/Durango/ApplicationView.cpp b/Minecraft.Client/Durango/ApplicationView.cpp index 2af864960..6c1959381 100644 --- a/Minecraft.Client/Durango/ApplicationView.cpp +++ b/Minecraft.Client/Durango/ApplicationView.cpp @@ -22,7 +22,7 @@ ApplicationView::ApplicationView() XALLOC_ATTRIBUTES ExpandAllocAttributes( _In_ LONGLONG dwAttributes ) { XALLOC_ATTRIBUTES attr; - attr = *((XALLOC_ATTRIBUTES *)&dwAttributes); + attr = *static_cast(&dwAttributes); return attr; } @@ -247,7 +247,7 @@ void ApplicationView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; float fElapsedTime = 0.0f; QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + float fSecsPerTick = 1.0f / static_cast(qwTicksPerSec.QuadPart); // Save the start time QueryPerformanceCounter( &qwTime ); @@ -275,7 +275,7 @@ void ApplicationView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs QueryPerformanceCounter( &qwNewTime ); qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + fElapsedTime = fSecsPerTick * static_cast(qwDeltaTime.QuadPart); app.DebugPrintf("Entire suspend process: Elapsed time %f\n", fElapsedTime); } diff --git a/Minecraft.Client/Durango/DurangoExtras/DurangoStubs.cpp b/Minecraft.Client/Durango/DurangoExtras/DurangoStubs.cpp index 81b9d7cf1..463756bc9 100644 --- a/Minecraft.Client/Durango/DurangoExtras/DurangoStubs.cpp +++ b/Minecraft.Client/Durango/DurangoExtras/DurangoStubs.cpp @@ -32,7 +32,7 @@ DWORD XGetLanguage() WCHAR wchLocaleName[LOCALE_NAME_MAX_LENGTH]; GetUserDefaultLocaleName(wchLocaleName,LOCALE_NAME_MAX_LENGTH); - eMCLang eLang=(eMCLang)app.get_eMCLang(wchLocaleName); + eMCLang eLang=static_cast(app.get_eMCLang(wchLocaleName)); #ifdef _DEBUG app.DebugPrintf("XGetLanguage() ==> '%ls'\n", wchLocaleName); diff --git a/Minecraft.Client/Durango/Durango_App.cpp b/Minecraft.Client/Durango/Durango_App.cpp index 672d6435c..efef93b44 100644 --- a/Minecraft.Client/Durango/Durango_App.cpp +++ b/Minecraft.Client/Durango/Durango_App.cpp @@ -12,6 +12,7 @@ #include "ServiceConfig\Events-XBLA.8-149E11AEEvents.h" #include "..\..\Minecraft.World\DurangoStats.h" #include "..\..\Minecraft.Client\Durango\XML\xmlFilesCallback.h" +#include "Common/UI/UI.h" CConsoleMinecraftApp app; @@ -42,7 +43,7 @@ void CConsoleMinecraftApp::HandleDLCLicenseChange() XCONTENT_DATA *pContentData=StorageManager.GetInstalledDLC(xOffer.wszProductID); - if((pContentData!=NULL) &&(pContentData->bTrialLicense==false)) + if((pContentData!=nullptr) &&(pContentData->bTrialLicense==false)) { DLCPack *pack = app.m_dlcManager.getPackFromProductID(xOffer.wszProductID); if(pack) @@ -193,7 +194,7 @@ void CConsoleMinecraftApp::FreeLocalDLCImages() { free(pDLCInfo->pbImageData); pDLCInfo->dwImageBytes=0; - pDLCInfo->pbImageData=NULL; + pDLCInfo->pbImageData=nullptr; } } } @@ -207,7 +208,7 @@ int CConsoleMinecraftApp::LoadLocalDLCImage(WCHAR *wchName,PBYTE *ppbImageData,D // 4J-PB - Read the file containing the product codes. This will be different for the SCEE/SCEA/SCEJ builds swprintf(wchFilename,L"DLCImages/%s",wchName); - HANDLE hFile = CreateFile(wchFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hFile = CreateFile(wchFilename, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( hFile == INVALID_HANDLE_VALUE ) { @@ -221,9 +222,9 @@ int CConsoleMinecraftApp::LoadLocalDLCImage(WCHAR *wchName,PBYTE *ppbImageData,D if(*pdwBytes!=0) { DWORD dwBytesRead; - PBYTE pbImageData=(PBYTE)malloc(*pdwBytes); + PBYTE pbImageData=static_cast(malloc(*pdwBytes)); - if(ReadFile(hFile,pbImageData,*pdwBytes,&dwBytesRead,NULL)==FALSE) + if(ReadFile(hFile,pbImageData,*pdwBytes,&dwBytesRead,nullptr)==FALSE) { // failed free(pbImageData); @@ -244,7 +245,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() { ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // From CScene_Main::RunPlayGame Minecraft *pMinecraft=Minecraft::GetInstance(); @@ -273,7 +274,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() NetworkGameInitData *param = new NetworkGameInitData(); param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; app.SetGameHostOption(eGameHostOption_Difficulty,0); app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); @@ -299,7 +300,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave time app.SetAutosaveTimerTime(); @@ -386,7 +387,7 @@ bool CConsoleMinecraftApp::UpdateProductId(XCONTENT_DATA &Data) // Do we have a product id for this? DLC_INFO *pDLCInfo=app.GetDLCInfoForProductName(Data.wszDisplayName); - if(pDLCInfo!=NULL) + if(pDLCInfo!=nullptr) { app.DebugPrintf("Updating product id for %ls\n",Data.wszDisplayName); swprintf_s(Data.wszProductID, 64,L"%ls",pDLCInfo->wsProductId.c_str()); @@ -454,9 +455,9 @@ bool CConsoleMinecraftApp::TMSPP_ReadBannedList(int iPad,eTMSAction NextAction) int CConsoleMinecraftApp::Callback_TMSPPReadBannedList(void *pParam,int iPad, int iUserData, LPVOID lpvData,WCHAR *wchFilename) { app.DebugPrintf("CConsoleMinecraftApp::Callback_TMSPPReadBannedList\n"); - C4JStorage::PTMSPP_FILEDATA pFileData=(C4JStorage::PTMSPP_FILEDATA)lpvData; + C4JStorage::PTMSPP_FILEDATA pFileData=static_cast(lpvData); - CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; + CConsoleMinecraftApp* pClass = static_cast(pParam); if(pFileData) { @@ -486,7 +487,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadBannedList(void *pParam,int iPad, in } // change the state to the next action - pClass->SetTMSAction(iPad,(eTMSAction)iUserData); + pClass->SetTMSAction(iPad,static_cast(iUserData)); return 0; } @@ -555,11 +556,11 @@ void CConsoleMinecraftApp::TMSPP_RetrieveFileList(int iPad,C4JStorage::eGlobalSt int CConsoleMinecraftApp::Callback_TMSPPRetrieveFileList(void *pParam,int iPad, int iUserData, LPVOID lpvData, WCHAR *wchFilename) { - CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; + CConsoleMinecraftApp* pClass = static_cast(pParam); app.DebugPrintf("CConsoleMinecraftApp::Callback_TMSPPRetrieveFileList\n"); - if(lpvData!=NULL) + if(lpvData!= nullptr) { - vector *pvTmsFileDetails=(vector *)lpvData; + vector *pvTmsFileDetails=static_cast *>(lpvData); if(pvTmsFileDetails->size()>0) { @@ -578,7 +579,7 @@ int CConsoleMinecraftApp::Callback_TMSPPRetrieveFileList(void *pParam,int iPad, } } // change the state to the next action - pClass->SetTMSAction(iPad,(eTMSAction)iUserData); + pClass->SetTMSAction(iPad,static_cast(iUserData)); return 0; } @@ -586,8 +587,8 @@ int CConsoleMinecraftApp::Callback_TMSPPRetrieveFileList(void *pParam,int iPad, int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int iUserData, LPVOID lpvData ,WCHAR *pwchFilename) { app.DebugPrintf("CConsoleMinecraftApp::Callback_TMSPPReadDLCFile\n"); - C4JStorage::PTMSPP_FILEDATA pFileData= (C4JStorage::PTMSPP_FILEDATA)lpvData; - CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; + C4JStorage::PTMSPP_FILEDATA pFileData= static_cast(lpvData); + CConsoleMinecraftApp* pClass = static_cast(pParam); #ifdef WRITE_DLCINFO if(0) @@ -635,7 +636,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i // hack for now to upload the file // open the local file - file = CreateFile(L"DLCXbox1.cmp", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile(L"DLCXbox1.cmp", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { DWORD error = GetLastError(); @@ -653,12 +654,12 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i PBYTE pbData= new BYTE [dwFileSize]; - ReadFile(file,pbData,dwFileSize,&bytesRead,NULL); + ReadFile(file,pbData,dwFileSize,&bytesRead,nullptr); if(bytesRead==dwFileSize) { - //StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"DLCXbox1.cmp",(PBYTE) pbData, dwFileSize,NULL,NULL, 0); - StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.cmp",(PBYTE) pbData, dwFileSize,NULL,NULL, 0); + //StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"DLCXbox1.cmp",(PBYTE) pbData, dwFileSize,nullptr,nullptr, 0); + StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.cmp",(PBYTE) pbData, dwFileSize,nullptr,nullptr, 0); } Sleep(5000); } @@ -667,7 +668,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i /* // now the icon - file = CreateFile(L"TP06.png", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile(L"TP06.png", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { DWORD error = GetLastError(); @@ -684,11 +685,11 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i PBYTE pbData= new BYTE [dwFileSize]; - ReadFile(file,pbData,dwFileSize,&bytesRead,NULL); + ReadFile(file,pbData,dwFileSize,&bytesRead,nullptr); if(bytesRead==dwFileSize) { - StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.png",(PBYTE) pbData, dwFileSize,NULL,NULL, 0); + StorageManager.TMSPP_WriteFile(iPad,C4JStorage::eGlobalStorage_TitleUser,C4JStorage::TMS_FILETYPE_BINARY,L"TP06.png",(PBYTE) pbData, dwFileSize,nullptr,nullptr, 0); } Sleep(5000); } @@ -698,14 +699,14 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i } // change the state to the next action - pClass->SetTMSAction(iPad,(eTMSAction)iUserData); + pClass->SetTMSAction(iPad,static_cast(iUserData)); return 0; } void CConsoleMinecraftApp::Callback_SaveGameIncomplete(void *pParam, C4JStorage::ESaveIncompleteType saveIncompleteType) { - CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; + CConsoleMinecraftApp* pClass = static_cast(pParam); if ( saveIncompleteType == C4JStorage::ESaveIncomplete_OutOfQuota || saveIncompleteType == C4JStorage::ESaveIncomplete_OutOfLocalStorage ) @@ -740,7 +741,7 @@ void CConsoleMinecraftApp::Callback_SaveGameIncomplete(void *pParam, C4JStorage: int CConsoleMinecraftApp::Callback_SaveGameIncompleteMessageBoxReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; + CConsoleMinecraftApp* pClass = static_cast(pParam); switch(result) { @@ -757,7 +758,7 @@ int CConsoleMinecraftApp::Callback_SaveGameIncompleteMessageBoxReturned(void *pP StorageManager.CancelIncompleteOperation(); break; case C4JStorage::EMessage_ResultThirdOption: - ui.NavigateToScene(iPad, eUIScene_InGameSaveManagementMenu, NULL, eUILayer_Error, eUIGroup_Fullscreen); + ui.NavigateToScene(iPad, eUIScene_InGameSaveManagementMenu, nullptr, eUILayer_Error, eUIGroup_Fullscreen); break; } return 0; diff --git a/Minecraft.Client/Durango/Durango_App.h b/Minecraft.Client/Durango/Durango_App.h index 6e0212329..ba4b26fb9 100644 --- a/Minecraft.Client/Durango/Durango_App.h +++ b/Minecraft.Client/Durango/Durango_App.h @@ -37,7 +37,7 @@ public: virtual int GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT=eFileExtensionType_PNG); // BANNED LEVEL LIST - virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} + virtual void ReadBannedList(int iPad, eTMSAction action=static_cast(0), bool bCallback=false) {} // TMS++ void TMSPP_RetrieveFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,eTMSAction NextAction); @@ -58,7 +58,7 @@ public: static void Callback_SaveGameIncomplete(void *pParam, C4JStorage::ESaveIncompleteType saveIncompleteType); static int Callback_SaveGameIncompleteMessageBoxReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable *GetStringTable() { return nullptr;} // original code virtual void TemporaryCreateGameStart(); diff --git a/Minecraft.Client/Durango/Durango_Minecraft.cpp b/Minecraft.Client/Durango/Durango_Minecraft.cpp index 78bb4f50e..b0b91ddd4 100644 --- a/Minecraft.Client/Durango/Durango_Minecraft.cpp +++ b/Minecraft.Client/Durango/Durango_Minecraft.cpp @@ -275,7 +275,7 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, return pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, - NULL, + nullptr, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, pd3dPP, ppDevice ); @@ -294,7 +294,7 @@ void MemSect(int sect) #endif -HINSTANCE g_hInst = NULL; +HINSTANCE g_hInst = nullptr; Platform::Agile g_window; Windows::Foundation::Rect g_windowBounds; @@ -477,7 +477,7 @@ void oldWinMainInit() MSG msg = {0}; while( WM_QUIT != msg.message ) { - if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) + if( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); @@ -549,7 +549,7 @@ void oldWinMainInit() } // Create an XAudio2 mastering voice (utilized by XHV2 when voice data is mixed to main speakers) - hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, NULL); + hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, nullptr); if ( FAILED( hr ) ) { app.DebugPrintf( "Creating XAudio2 mastering voice failed (err = 0x%08x)!\n", hr ); @@ -586,7 +586,7 @@ void oldWinMainInit() app.ReadLocalDLCList(); // initialise the storage manager with a default save display name, a Minimum save size, and a callback for displaying the saving message - StorageManager.Init(0,app.GetString(IDS_DEFAULT_SAVENAME),"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,(LPVOID)&app, app.UpdateProductId,SERVICE_CONFIG_ID,TITLE_PRODUCT_ID); + StorageManager.Init(0,app.GetString(IDS_DEFAULT_SAVENAME),"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,static_cast(&app), app.UpdateProductId,SERVICE_CONFIG_ID,TITLE_PRODUCT_ID); StorageManager.SetMaxSaves(99); @@ -599,21 +599,21 @@ void oldWinMainInit() app.GAME_DEFINED_PROFILE_DATA_BYTES*XUSER_MAX_COUNT, &app.uiGameDefinedDataChangedBitmask); - StorageManager.SetDefaultImages((PBYTE)baSaveThumbnail.data, baSaveThumbnail.length); + StorageManager.SetDefaultImages(static_cast(baSaveThumbnail.data), baSaveThumbnail.length); // Set function to be called if a save game operation can't complete due to running out of storage space etc. - StorageManager.SetIncompleteSaveCallback(CConsoleMinecraftApp::Callback_SaveGameIncomplete, (LPVOID)&app); + StorageManager.SetIncompleteSaveCallback(CConsoleMinecraftApp::Callback_SaveGameIncomplete, static_cast(&app)); // 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); // Set a callback for the default player options to be set - when there is no profile data for the player - StorageManager.SetDefaultOptionsCallback(&CConsoleMinecraftApp::DefaultOptionsCallback,(LPVOID)&app); - StorageManager.SetOptionsDataCallback(&CConsoleMinecraftApp::OptionsDataCallback,(LPVOID)&app); + StorageManager.SetDefaultOptionsCallback(&CConsoleMinecraftApp::DefaultOptionsCallback,static_cast(&app)); + StorageManager.SetOptionsDataCallback(&CConsoleMinecraftApp::OptionsDataCallback,static_cast(&app)); // Set a callback to deal with old profile versions needing updated to new versions - StorageManager.SetOldProfileVersionCallback(&CConsoleMinecraftApp::OldProfileVersionCallback,(LPVOID)&app); + StorageManager.SetOldProfileVersionCallback(&CConsoleMinecraftApp::OldProfileVersionCallback,static_cast(&app)); g_NetworkManager.Initialise(); @@ -788,7 +788,7 @@ void oldWinMainTick() else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); diff --git a/Minecraft.Client/Durango/Durango_UIController.cpp b/Minecraft.Client/Durango/Durango_UIController.cpp index 446ab87e3..e27d91d23 100644 --- a/Minecraft.Client/Durango/Durango_UIController.cpp +++ b/Minecraft.Client/Durango/Durango_UIController.cpp @@ -75,7 +75,7 @@ void ConsoleUIController::render() example, no resolve targets are required. */ gdraw_D3D11_SetTileOrigin( m_pRenderTargetView.Get(), m_pDepthStencilView.Get(), - NULL, + nullptr, 0, 0 ); @@ -153,7 +153,7 @@ void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) { gdraw_D3D11_SetTileOrigin( m_pRenderTargetView.Get(), m_pDepthStencilView.Get(), - NULL, + nullptr, xPos, yPos ); } @@ -169,7 +169,7 @@ GDrawTexture *ConsoleUIController::getSubstitutionTexture(int textureId) ID3D11ShaderResourceView *tex = RenderManager.TextureGetTexture(textureId); ID3D11Resource *resource; tex->GetResource(&resource); - ID3D11Texture2D *tex2d = (ID3D11Texture2D *)resource; + ID3D11Texture2D *tex2d = static_cast(resource); D3D11_TEXTURE2D_DESC desc; tex2d->GetDesc(&desc); GDrawTexture *gdrawTex = gdraw_D3D11_WrappedTextureCreate(tex); diff --git a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d10_shaders.inl b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d10_shaders.inl index d4d2bb229..6ea0d142f 100644 --- a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d10_shaders.inl +++ b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d10_shaders.inl @@ -1364,7 +1364,7 @@ static DWORD pshader_exceptional_blend_12[276] = { }; static ProgramWithCachedVariableLocations pshader_exceptional_blend_arr[13] = { - { NULL, 0, }, + { nullptr, 0, }, { pshader_exceptional_blend_1, 1340, }, { pshader_exceptional_blend_2, 1444, }, { pshader_exceptional_blend_3, 1424, }, @@ -2672,10 +2672,10 @@ static ProgramWithCachedVariableLocations pshader_filter_arr[32] = { { pshader_filter_9, 708, }, { pshader_filter_10, 1644, }, { pshader_filter_11, 1372, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, { pshader_filter_16, 1740, }, { pshader_filter_17, 1732, }, { pshader_filter_18, 1820, }, @@ -2688,10 +2688,10 @@ static ProgramWithCachedVariableLocations pshader_filter_arr[32] = { { pshader_filter_25, 1468, }, { pshader_filter_26, 1820, }, { pshader_filter_27, 1548, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, }; static DWORD pshader_blur_2[320] = { @@ -3193,8 +3193,8 @@ static DWORD pshader_blur_9[621] = { }; static ProgramWithCachedVariableLocations pshader_blur_arr[10] = { - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, { pshader_blur_2, 1280, }, { pshader_blur_3, 1452, }, { pshader_blur_4, 1624, }, diff --git a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.cpp b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.cpp index 0c106b3fd..b5bfe1f69 100644 --- a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.cpp +++ b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.cpp @@ -64,7 +64,7 @@ static void *map_buffer(ID3D1XContext *ctx, ID3D11Buffer *buf, bool discard) HRESULT hr = ctx->Map(buf, 0, discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE, 0, &msr); if (FAILED(hr)) { report_d3d_error(hr, "Map", "of buffer"); - return NULL; + return nullptr; } else return msr.pData; } @@ -76,12 +76,12 @@ static void unmap_buffer(ID3D1XContext *ctx, ID3D11Buffer *buf) static RADINLINE void set_pixel_shader(ID3D11DeviceContext *ctx, ID3D11PixelShader *shader) { - ctx->PSSetShader(shader, NULL, 0); + ctx->PSSetShader(shader, nullptr, 0); } static RADINLINE void set_vertex_shader(ID3D11DeviceContext *ctx, ID3D11VertexShader *shader) { - ctx->VSSetShader(shader, NULL, 0); + ctx->VSSetShader(shader, nullptr, 0); } static ID3D11BlendState *create_blend_state(ID3D11Device *dev, BOOL blend, D3D11_BLEND src, D3D11_BLEND dst) @@ -100,7 +100,7 @@ static ID3D11BlendState *create_blend_state(ID3D11Device *dev, BOOL blend, D3D11 HRESULT hr = dev->CreateBlendState(&desc, &res); if (FAILED(hr)) { report_d3d_error(hr, "CreateBlendState", ""); - res = NULL; + res = nullptr; } return res; @@ -113,10 +113,10 @@ static void create_pixel_shader(ProgramWithCachedVariableLocations *p, ProgramWi { *p = *src; if(p->bytecode) { - HRESULT hr = gdraw->d3d_device->CreatePixelShader(p->bytecode, p->size, NULL, &p->pshader); + HRESULT hr = gdraw->d3d_device->CreatePixelShader(p->bytecode, p->size, nullptr, &p->pshader); if (FAILED(hr)) { report_d3d_error(hr, "CreatePixelShader", ""); - p->pshader = NULL; + p->pshader = nullptr; return; } } @@ -126,10 +126,10 @@ static void create_vertex_shader(ProgramWithCachedVariableLocations *p, ProgramW { *p = *src; if(p->bytecode) { - HRESULT hr = gdraw->d3d_device->CreateVertexShader(p->bytecode, p->size, NULL, &p->vshader); + HRESULT hr = gdraw->d3d_device->CreateVertexShader(p->bytecode, p->size, nullptr, &p->vshader); if (FAILED(hr)) { report_d3d_error(hr, "CreateVertexShader", ""); - p->vshader = NULL; + p->vshader = nullptr; return; } } diff --git a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.h b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.h index c8db492a6..f8a5dc6d9 100644 --- a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.h +++ b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d11.h @@ -41,7 +41,7 @@ IDOC extern GDrawFunctions * gdraw_D3D11_CreateContext(ID3D11Device *dev, ID3D11 There can only be one D3D GDraw context active at any one time. If initialization fails for some reason (the main reason would be an out of memory condition), - NULL is returned. Otherwise, you can pass the return value to IggySetGDraw. */ + nullptr is returned. Otherwise, you can pass the return value to IggySetGDraw. */ IDOC extern void gdraw_D3D11_DestroyContext(void); /* Destroys the current GDraw context, if any. */ @@ -69,7 +69,7 @@ IDOC extern void gdraw_D3D11_SetTileOrigin(ID3D11RenderTargetView *main_rt, ID3D If your rendertarget uses multisampling, you also need to specify a shader resource view for a non-MSAA rendertarget texture (identically sized to main_rt) in non_msaa_rt. This is only used if the Flash content includes non-standard - blend modes which have to use a special blend shader, so you can leave it NULL + blend modes which have to use a special blend shader, so you can leave it nullptr if you forbid such content. You need to call this before Iggy calls any rendering functions. */ diff --git a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d1x_shared.inl b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d1x_shared.inl index 1ab1f13f7..1cbac10fa 100644 --- a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d1x_shared.inl +++ b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_d3d1x_shared.inl @@ -196,16 +196,16 @@ static void safe_release(T *&p) { if (p) { p->Release(); - p = NULL; + p = nullptr; } } static void report_d3d_error(HRESULT hr, char *call, char *context) { if (hr == E_OUTOFMEMORY) - IggyGDrawSendWarning(NULL, "GDraw D3D out of memory in %s%s", call, context); + IggyGDrawSendWarning(nullptr, "GDraw D3D out of memory in %s%s", call, context); else - IggyGDrawSendWarning(NULL, "GDraw D3D error in %s%s: 0x%08x", call, context, hr); + IggyGDrawSendWarning(nullptr, "GDraw D3D error in %s%s: 0x%08x", call, context, hr); } static void unbind_resources(void) @@ -215,12 +215,12 @@ static void unbind_resources(void) // unset active textures and vertex/index buffers, // to make sure there are no dangling refs static ID3D1X(ShaderResourceView) *no_views[3] = { 0 }; - ID3D1X(Buffer) *no_vb = NULL; + ID3D1X(Buffer) *no_vb = nullptr; UINT no_offs = 0; d3d->PSSetShaderResources(0, 3, no_views); d3d->IASetVertexBuffers(0, 1, &no_vb, &no_offs, &no_offs); - d3d->IASetIndexBuffer(NULL, DXGI_FORMAT_UNKNOWN, 0); + d3d->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0); } static void api_free_resource(GDrawHandle *r) @@ -251,11 +251,11 @@ static void RADLINK gdraw_UnlockHandles(GDrawStats * /*stats*/) static void *start_write_dyn(DynBuffer *buf, U32 size) { - U8 *ptr = NULL; + U8 *ptr = nullptr; if (size > buf->size) { - IggyGDrawSendWarning(NULL, "GDraw dynamic vertex buffer usage of %d bytes in one call larger than buffer size %d", size, buf->size); - return NULL; + IggyGDrawSendWarning(nullptr, "GDraw dynamic vertex buffer usage of %d bytes in one call larger than buffer size %d", size, buf->size); + return nullptr; } // update statistics @@ -373,19 +373,19 @@ extern GDrawTexture *gdraw_D3D1X_(WrappedTextureCreate)(ID3D1X(ShaderResourceVie { GDrawStats stats={0}; GDrawHandle *p = gdraw_res_alloc_begin(gdraw->texturecache, 0, &stats); // it may need to free one item to give us a handle - p->handle.tex.d3d = NULL; + p->handle.tex.d3d = nullptr; p->handle.tex.d3d_view = tex_view; - p->handle.tex.d3d_rtview = NULL; + p->handle.tex.d3d_rtview = nullptr; p->handle.tex.w = 1; p->handle.tex.h = 1; - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); return (GDrawTexture *) p; } extern void gdraw_D3D1X_(WrappedTextureChange)(GDrawTexture *tex, ID3D1X(ShaderResourceView) *tex_view) { GDrawHandle *p = (GDrawHandle *) tex; - p->handle.tex.d3d = NULL; + p->handle.tex.d3d = nullptr; p->handle.tex.d3d_view = tex_view; } @@ -407,12 +407,12 @@ static void RADLINK gdraw_SetTextureUniqueID(GDrawTexture *tex, void *old_id, vo static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format format, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; DXGI_FORMAT dxgi_fmt; S32 bpp, size = 0, nmips = 0; if (width >= 16384 || height >= 16384) { - IggyGDrawSendWarning(NULL, "GDraw texture size too large (%d x %d), dimension limit is 16384", width, height); + IggyGDrawSendWarning(nullptr, "GDraw texture size too large (%d x %d), dimension limit is 16384", width, height); return false; } @@ -433,7 +433,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, // try to allocate memory for the client to write to p->texture_data = (U8 *) IggyGDrawMalloc(size); if (!p->texture_data) { - IggyGDrawSendWarning(NULL, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); + IggyGDrawSendWarning(nullptr, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); return false; } @@ -446,9 +446,9 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, t->handle.tex.w = width; t->handle.tex.h = height; - t->handle.tex.d3d = NULL; - t->handle.tex.d3d_view = NULL; - t->handle.tex.d3d_rtview = NULL; + t->handle.tex.d3d = nullptr; + t->handle.tex.d3d_view = nullptr; + t->handle.tex.d3d_rtview = nullptr; p->texture_type = GDRAW_TEXTURE_TYPE_rgba; p->p0 = t; @@ -512,7 +512,7 @@ static GDrawTexture * RADLINK gdraw_MakeTextureEnd(GDraw_MakeTexture_ProcessingI // and create a corresponding shader resource view failed_call = "CreateShaderResourceView"; - hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_view); + hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_view); done: if (!FAILED(hr)) { @@ -525,7 +525,7 @@ done: safe_release(t->handle.tex.d3d_view); gdraw_HandleCacheAllocateFail(t); - t = NULL; + t = nullptr; report_d3d_error(hr, failed_call, " while creating texture"); } @@ -554,8 +554,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *t, void * /*unique_id*/ static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *stats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); // @GDRAW_ASSERT - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); // @GDRAW_ASSERT + if (t->owner == unique_id || unique_id == nullptr) { if (t->cache == &gdraw->rendertargets) { gdraw_HandleCacheUnlock(t); // cache it by simply not freeing it @@ -595,7 +595,7 @@ static void RADLINK gdraw_SetAntialiasTexture(S32 width, U8 *rgba) return; } - hr = gdraw->d3d_device->CreateShaderResourceView(gdraw->aa_tex, NULL, &gdraw->aa_tex_view); + hr = gdraw->d3d_device->CreateShaderResourceView(gdraw->aa_tex, nullptr, &gdraw->aa_tex_view); if (FAILED(hr)) { report_d3d_error(hr, "CreateShaderResourceView", " while creating texture"); safe_release(gdraw->aa_tex); @@ -616,8 +616,8 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat if (p->vertex_data && p->index_data) { GDrawHandle *vb = gdraw_res_alloc_begin(gdraw->vbufcache, vbuf_size + ibuf_size, stats); if (vb) { - vb->handle.vbuf.verts = NULL; - vb->handle.vbuf.inds = NULL; + vb->handle.vbuf.verts = nullptr; + vb->handle.vbuf.inds = nullptr; p->vertex_data_length = vbuf_size; p->index_data_length = ibuf_size; @@ -661,7 +661,7 @@ static GDrawVertexBuffer * RADLINK gdraw_MakeVertexBufferEnd(GDraw_MakeVertexBuf safe_release(vb->handle.vbuf.inds); gdraw_HandleCacheAllocateFail(vb); - vb = NULL; + vb = nullptr; report_d3d_error(hr, "CreateBuffer", " creating vertex buffer"); } else { @@ -682,7 +682,7 @@ static rrbool RADLINK gdraw_TryLockVertexBuffer(GDrawVertexBuffer *vb, void *uni static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); // @GDRAW_ASSERT + assert(h != nullptr); // @GDRAW_ASSERT if (h->owner == unique_id) gdraw_res_free(h, stats); } @@ -712,31 +712,31 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) // ran out of RTs, allocate a new one S32 size = gdraw->frametex_width * gdraw->frametex_height * 4; if (gdraw->rendertargets.bytes_free < size) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit size limit of %d bytes", gdraw->rendertargets.total_bytes); - return NULL; + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit size limit of %d bytes", gdraw->rendertargets.total_bytes); + return nullptr; } t = gdraw_HandleCacheAllocateBegin(&gdraw->rendertargets); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit handle limit"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit handle limit"); return t; } D3D1X_(TEXTURE2D_DESC) desc = { gdraw->frametex_width, gdraw->frametex_height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, { 1, 0 }, D3D1X_(USAGE_DEFAULT), D3D1X_(BIND_SHADER_RESOURCE) | D3D1X_(BIND_RENDER_TARGET), 0, 0 }; - t->handle.tex.d3d = NULL; - t->handle.tex.d3d_view = NULL; - t->handle.tex.d3d_rtview = NULL; + t->handle.tex.d3d = nullptr; + t->handle.tex.d3d_view = nullptr; + t->handle.tex.d3d_rtview = nullptr; - HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, NULL, &t->handle.tex.d3d); + HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, nullptr, &t->handle.tex.d3d); failed_call = "CreateTexture2D"; if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_view); + hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_view); failed_call = "CreateTexture2D"; } if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateRenderTargetView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_rtview); + hr = gdraw->d3d_device->CreateRenderTargetView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_rtview); failed_call = "CreateRenderTargetView"; } @@ -748,7 +748,7 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) report_d3d_error(hr, failed_call, " creating rendertarget"); - return NULL; + return nullptr; } gdraw_HandleCacheAllocateEnd(t, size, (void *) 1, GDRAW_HANDLE_STATE_locked); @@ -768,10 +768,10 @@ static ID3D1X(DepthStencilView) *get_rendertarget_depthbuffer(GDrawStats *stats) D3D1X_(TEXTURE2D_DESC) desc = { gdraw->frametex_width, gdraw->frametex_height, 1, 1, DXGI_FORMAT_D24_UNORM_S8_UINT, { 1, 0 }, D3D1X_(USAGE_DEFAULT), D3D1X_(BIND_DEPTH_STENCIL), 0, 0 }; - HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, NULL, &gdraw->rt_depth_buffer); + HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, nullptr, &gdraw->rt_depth_buffer); failed_call = "CreateTexture2D"; if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateDepthStencilView(gdraw->rt_depth_buffer, NULL, &gdraw->depth_buffer[1]); + hr = gdraw->d3d_device->CreateDepthStencilView(gdraw->rt_depth_buffer, nullptr, &gdraw->depth_buffer[1]); failed_call = "CreateDepthStencilView while creating rendertarget"; } @@ -1110,7 +1110,7 @@ static void set_render_target(GDrawStats *stats) gdraw->d3d_context->OMSetRenderTargets(1, &target, gdraw->depth_buffer[0]); gdraw->d3d_context->RSSetState(gdraw->raster_state[gdraw->main_msaa]); } else { - ID3D1X(DepthStencilView) *depth = NULL; + ID3D1X(DepthStencilView) *depth = nullptr; if (gdraw->cur->flags & (GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_id | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_stencil)) depth = get_rendertarget_depthbuffer(stats); @@ -1125,15 +1125,15 @@ static void set_render_target(GDrawStats *stats) static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_texture_format /*format*/, U32 flags, void *owner, GDrawStats *stats) { GDrawFramebufferState *n = gdraw->cur+1; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (gdraw->tw == 0 || gdraw->th == 0) { - IggyGDrawSendWarning(NULL, "GDraw warning: w=0,h=0 rendertarget"); + IggyGDrawSendWarning(nullptr, "GDraw warning: w=0,h=0 rendertarget"); return false; } if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) { assert(0); - IggyGDrawSendWarning(NULL, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); return false; } @@ -1147,10 +1147,10 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex n->flags = flags; n->color_buffer = t; - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT ++gdraw->cur; - gdraw->cur->cached = owner != NULL; + gdraw->cur->cached = owner != nullptr; if (owner) { gdraw->cur->base_x = region->x0; gdraw->cur->base_y = region->y0; @@ -1229,9 +1229,9 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) assert(m >= gdraw->frame); // bug in Iggy -- unbalanced if (m != gdraw->frame) { - assert(m->color_buffer != NULL); // @GDRAW_ASSERT + assert(m->color_buffer != nullptr); // @GDRAW_ASSERT } - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT // switch back to old render target set_render_target(stats); @@ -1288,8 +1288,8 @@ static void set_texture(S32 texunit, GDrawTexture *tex, rrbool nearest, S32 wrap { ID3D1XContext *d3d = gdraw->d3d_context; - if (tex == NULL) { - ID3D1X(ShaderResourceView) *notex = NULL; + if (tex == nullptr) { + ID3D1X(ShaderResourceView) *notex = nullptr; d3d->PSSetShaderResources(texunit, 1, ¬ex); } else { GDrawHandle *h = (GDrawHandle *) tex; @@ -1300,7 +1300,7 @@ static void set_texture(S32 texunit, GDrawTexture *tex, rrbool nearest, S32 wrap static void RADLINK gdraw_Set3DTransform(F32 *mat) { - if (mat == NULL) + if (mat == nullptr) gdraw->use_3d = 0; else { gdraw->use_3d = 1; @@ -1363,9 +1363,9 @@ static int set_renderstate_full(S32 vertex_format, GDrawRenderState *r, GDrawSta // in stencil set mode, prefer not doing any shading at all // but if alpha test is on, we need to make an exception -#ifndef GDRAW_D3D11_LEVEL9 // level9 can't do NULL PS it seems +#ifndef GDRAW_D3D11_LEVEL9 // level9 can't do nullptr PS it seems if (which != GDRAW_TEXTURE_alpha_test) - program = NULL; + program = nullptr; else #endif { @@ -1475,7 +1475,7 @@ static int vertsize[GDRAW_vformat__basic_count] = { // Draw triangles with a given renderstate // -static void tag_resources(void *r1, void *r2=NULL, void *r3=NULL, void *r4=NULL) +static void tag_resources(void *r1, void *r2=nullptr, void *r3=nullptr, void *r4=nullptr) { U64 now = gdraw->frame_counter; if (r1) ((GDrawHandle *) r1)->fence.value = now; @@ -1687,7 +1687,7 @@ static void set_clamp_constant(F32 *constant, GDrawTexture *tex) static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbevel, GDrawStats *stats) { - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, stats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, stats)) return; set_texture(0, r->tex[0], false, GDRAW_WRAP_clamp); @@ -1775,7 +1775,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 assert(0); } } else { - GDrawHandle *blend_tex = NULL; + GDrawHandle *blend_tex = nullptr; // for crazy blend modes, we need to read back from the framebuffer // and do the blending in the pixel shader. we do this with copies @@ -1859,18 +1859,18 @@ static void destroy_shader(ProgramWithCachedVariableLocations *p) { if (p->pshader) { p->pshader->Release(); - p->pshader = NULL; + p->pshader = nullptr; } } static ID3D1X(Buffer) *create_dynamic_buffer(U32 size, U32 bind) { D3D1X_(BUFFER_DESC) desc = { size, D3D1X_(USAGE_DYNAMIC), bind, D3D1X_(CPU_ACCESS_WRITE), 0 }; - ID3D1X(Buffer) *buf = NULL; - HRESULT hr = gdraw->d3d_device->CreateBuffer(&desc, NULL, &buf); + ID3D1X(Buffer) *buf = nullptr; + HRESULT hr = gdraw->d3d_device->CreateBuffer(&desc, nullptr, &buf); if (FAILED(hr)) { report_d3d_error(hr, "CreateBuffer", " creating dynamic vertex buffer"); - buf = NULL; + buf = nullptr; } return buf; } @@ -1907,7 +1907,7 @@ static void create_all_shaders_and_state(void) HRESULT hr = d3d->CreateInputLayout(vformats[i].desc, vformats[i].nelem, vsh->bytecode, vsh->size, &gdraw->inlayout[i]); if (FAILED(hr)) { report_d3d_error(hr, "CreateInputLayout", ""); - gdraw->inlayout[i] = NULL; + gdraw->inlayout[i] = nullptr; } } @@ -2026,11 +2026,11 @@ static void create_all_shaders_and_state(void) hr = gdraw->d3d_device->CreateBuffer(&bufdesc, &data, &gdraw->quad_ib); if (FAILED(hr)) { report_d3d_error(hr, "CreateBuffer", " for constants"); - gdraw->quad_ib = NULL; + gdraw->quad_ib = nullptr; } IggyGDrawFree(inds); } else - gdraw->quad_ib = NULL; + gdraw->quad_ib = nullptr; } static void destroy_all_shaders_and_state() @@ -2103,7 +2103,7 @@ static void free_gdraw() if (gdraw->texturecache) IggyGDrawFree(gdraw->texturecache); if (gdraw->vbufcache) IggyGDrawFree(gdraw->vbufcache); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } static bool alloc_dynbuffer(U32 size) @@ -2139,7 +2139,7 @@ static bool alloc_dynbuffer(U32 size) gdraw->max_quad_vert_count = RR_MIN(size / sizeof(gswf_vertex_xyst), QUAD_IB_COUNT * 4); gdraw->max_quad_vert_count &= ~3; // must be multiple of four - return gdraw->dyn_vb.buffer != NULL && gdraw->dyn_ib.buffer != NULL; + return gdraw->dyn_vb.buffer != nullptr && gdraw->dyn_ib.buffer != nullptr; } int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S32 num_bytes) @@ -2178,7 +2178,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 IggyGDrawFree(gdraw->texturecache); } gdraw->texturecache = make_handle_cache(GDRAW_D3D1X_(RESOURCE_texture)); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_D3D1X_(RESOURCE_vertexbuffer): if (gdraw->vbufcache) { @@ -2186,7 +2186,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 IggyGDrawFree(gdraw->vbufcache); } gdraw->vbufcache = make_handle_cache(GDRAW_D3D1X_(RESOURCE_vertexbuffer)); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; case GDRAW_D3D1X_(RESOURCE_dynbuffer): unbind_resources(); @@ -2202,7 +2202,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 static GDrawFunctions *create_context(ID3D1XDevice *dev, ID3D1XContext *ctx, S32 w, S32 h) { gdraw = (GDraw *) IggyGDrawMalloc(sizeof(*gdraw)); - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -2217,7 +2217,7 @@ static GDrawFunctions *create_context(ID3D1XDevice *dev, ID3D1XContext *ctx, S32 if (!gdraw->texturecache || !gdraw->vbufcache || !alloc_dynbuffer(gdraw_limits[GDRAW_D3D1X_(RESOURCE_dynbuffer)].num_bytes)) { free_gdraw(); - return NULL; + return nullptr; } create_all_shaders_and_state(); @@ -2288,7 +2288,7 @@ void gdraw_D3D1X_(DestroyContext)(void) if (gdraw->texturecache) gdraw_res_flush(gdraw->texturecache, &stats); if (gdraw->vbufcache) gdraw_res_flush(gdraw->vbufcache, &stats); - gdraw->d3d_device = NULL; + gdraw->d3d_device = nullptr; } free_gdraw(); @@ -2351,7 +2351,7 @@ void RADLINK gdraw_D3D1X_(GetResourceUsageStats)(gdraw_resourcetype type, S32 *h case GDRAW_D3D1X_(RESOURCE_texture): cache = gdraw->texturecache; break; case GDRAW_D3D1X_(RESOURCE_vertexbuffer): cache = gdraw->vbufcache; break; case GDRAW_D3D1X_(RESOURCE_dynbuffer): *handles_used = 0; *bytes_used = gdraw->last_dyn_maxalloc; return; - default: cache = NULL; break; + default: cache = nullptr; break; } *handles_used = *bytes_used = 0; @@ -2408,7 +2408,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, case IFT_FORMAT_DXT3 : size=16; d3dfmt = DXGI_FORMAT_BC2_UNORM; blk = 4; break; case IFT_FORMAT_DXT5 : size=16; d3dfmt = DXGI_FORMAT_BC3_UNORM; blk = 4; break; default: { - IggyGDrawSendWarning(NULL, "GDraw .iggytex raw texture format %d not supported by hardware", texture->format); + IggyGDrawSendWarning(nullptr, "GDraw .iggytex raw texture format %d not supported by hardware", texture->format); goto done; } } @@ -2424,7 +2424,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, free_data = (U8 *) IggyGDrawMalloc(total_size); if (!free_data) { - IggyGDrawSendWarning(NULL, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); + IggyGDrawSendWarning(nullptr, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); goto done; } @@ -2457,7 +2457,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, if (FAILED(hr)) goto done; failed_call = "CreateShaderResourceView for texture creation"; - hr = gdraw->d3d_device->CreateShaderResourceView(tex, NULL, &view); + hr = gdraw->d3d_device->CreateShaderResourceView(tex, nullptr, &view); if (FAILED(hr)) goto done; t = gdraw_D3D1X_(WrappedTextureCreate)(view); diff --git a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_shared.inl b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_shared.inl index a60fa520c..1790de77e 100644 --- a/Minecraft.Client/Durango/Iggy/gdraw/gdraw_shared.inl +++ b/Minecraft.Client/Durango/Iggy/gdraw/gdraw_shared.inl @@ -226,7 +226,7 @@ static void debug_check_raw_values(GDrawHandleCache *c) s = s->next; } s = c->active; - while (s != NULL) { + while (s != nullptr) { assert(s->raw_ptr != t->raw_ptr); s = s->next; } @@ -368,7 +368,7 @@ static void gdraw_HandleTransitionInsertBefore(GDrawHandle *t, GDrawHandleState { check_lists(t->cache); assert(t->state != GDRAW_HANDLE_STATE_sentinel); // sentinels should never get here! - assert(t->state != (U32) new_state); // code should never call "transition" if it's not transitioning! + assert(t->state != static_cast(new_state)); // code should never call "transition" if it's not transitioning! // unlink from prev state t->prev->next = t->next; t->next->prev = t->prev; @@ -433,7 +433,7 @@ static rrbool gdraw_HandleCacheLockStats(GDrawHandle *t, void *owner, GDrawStats static rrbool gdraw_HandleCacheLock(GDrawHandle *t, void *owner) { - return gdraw_HandleCacheLockStats(t, owner, NULL); + return gdraw_HandleCacheLockStats(t, owner, nullptr); } static void gdraw_HandleCacheUnlock(GDrawHandle *t) @@ -461,11 +461,11 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->is_thrashing = false; c->did_defragment = false; for (i=0; i < GDRAW_HANDLE_STATE__count; i++) { - c->state[i].owner = NULL; - c->state[i].cache = NULL; // should never follow cache link from sentinels! + c->state[i].owner = nullptr; + c->state[i].cache = nullptr; // should never follow cache link from sentinels! c->state[i].next = c->state[i].prev = &c->state[i]; #ifdef GDRAW_MANAGE_MEM - c->state[i].raw_ptr = NULL; + c->state[i].raw_ptr = nullptr; #endif c->state[i].fence.value = 0; c->state[i].bytes = 0; @@ -478,7 +478,7 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->handle[i].bytes = 0; c->handle[i].state = GDRAW_HANDLE_STATE_free; #ifdef GDRAW_MANAGE_MEM - c->handle[i].raw_ptr = NULL; + c->handle[i].raw_ptr = nullptr; #endif } c->state[GDRAW_HANDLE_STATE_free].next = &c->handle[0]; @@ -486,10 +486,10 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->prev_frame_start.value = 0; c->prev_frame_end.value = 0; #ifdef GDRAW_MANAGE_MEM - c->alloc = NULL; + c->alloc = nullptr; #endif #ifdef GDRAW_MANAGE_MEM_TWOPOOL - c->alloc_other = NULL; + c->alloc_other = nullptr; #endif check_lists(c); } @@ -497,14 +497,14 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte static GDrawHandle *gdraw_HandleCacheAllocateBegin(GDrawHandleCache *c) { GDrawHandle *free_list = &c->state[GDRAW_HANDLE_STATE_free]; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (free_list->next != free_list) { t = free_list->next; gdraw_HandleTransitionTo(t, GDRAW_HANDLE_STATE_alloc); t->bytes = 0; t->owner = 0; #ifdef GDRAW_MANAGE_MEM - t->raw_ptr = NULL; + t->raw_ptr = nullptr; #endif #ifdef GDRAW_CORRUPTION_CHECK t->has_check_value = false; @@ -558,7 +558,7 @@ static GDrawHandle *gdraw_HandleCacheGetLRU(GDrawHandleCache *c) // at the front of the LRU list are the oldest ones, since in-use resources // will get appended on every transition from "locked" to "live". GDrawHandle *sentinel = &c->state[GDRAW_HANDLE_STATE_live]; - return (sentinel->next != sentinel) ? sentinel->next : NULL; + return (sentinel->next != sentinel) ? sentinel->next : nullptr; } static void gdraw_HandleCacheTick(GDrawHandleCache *c, GDrawFence now) @@ -773,7 +773,7 @@ static GDrawTexture *gdraw_BlurPass(GDrawFunctions *g, GDrawBlurInfo *c, GDrawRe if (!g->TextureDrawBufferBegin(draw_bounds, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, gstats)) return r->tex[0]; - c->BlurPass(r, taps, data, draw_bounds, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, draw_bounds, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -825,7 +825,7 @@ static GDrawTexture *gdraw_BlurPassDownsample(GDrawFunctions *g, GDrawBlurInfo * assert(clamp[0] <= clamp[2]); assert(clamp[1] <= clamp[3]); - c->BlurPass(r, taps, data, &z, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, &z, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -837,7 +837,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR GDrawTexture *t; F32 data[MAX_TAPS][4]; S32 off_axis = 1-axis; - S32 w = ((S32) ceil((blur_width-1)/2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 + S32 w = static_cast(ceil((blur_width - 1) / 2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 F32 edge_weight = 1 - (w - blur_width)/2; // 3 => 0 => 1; 1.2 => 1.8 => 0.9 => 0.1 F32 inverse_weight = 1.0f / blur_width; @@ -944,7 +944,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR // max coverage is 25 samples, or a filter width of 13. with 7 taps, we sample // 13 samples in one pass, max coverage is 13*13 samples or (13*13-1)/2 width, // which is ((2T-1)*(2T-1)-1)/2 or (4T^2 - 4T + 1 -1)/2 or 2T^2 - 2T or 2T*(T-1) - S32 w_mip = (S32) ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS)); + S32 w_mip = static_cast(ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS))); S32 downsample = w_mip; F32 sample_spacing = texel; if (downsample < 2) downsample = 2; @@ -1090,7 +1090,7 @@ static void make_pool_aligned(void **start, S32 *num_bytes, U32 alignment) if (addr_aligned != addr_orig) { S32 diff = (S32) (addr_aligned - addr_orig); if (*num_bytes < diff) { - *start = NULL; + *start = nullptr; *num_bytes = 0; return; } else { @@ -1127,7 +1127,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) UINTa remaining = arena->end - arena->current; UINTa total_size = (ptr - arena->current) + size; if (remaining < total_size) // doesn't fit - return NULL; + return nullptr; arena->current = ptr + size; return ptr; @@ -1152,7 +1152,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // (i.e. block->next->prev == block->prev->next == block) // - All allocated blocks are also kept in a hash table, indexed by their // pointer (to allow free to locate the corresponding block_info quickly). -// There's a single-linked, NULL-terminated list of elements in each hash +// There's a single-linked, nullptr-terminated list of elements in each hash // bucket. // - The physical block list is ordered. It always contains all currently // active blocks and spans the whole managed memory range. There are no @@ -1161,7 +1161,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // they are coalesced immediately. // - The maximum number of blocks that could ever be necessary is allocated // on initialization. All block_infos not currently in use are kept in a -// single-linked, NULL-terminated list of unused blocks. Every block is either +// single-linked, nullptr-terminated list of unused blocks. Every block is either // in the physical block list or the unused list, and the total number of // blocks is constant. // These invariants always hold before and after an allocation/free. @@ -1379,7 +1379,7 @@ static void gfxalloc_check2(gfx_allocator *alloc) static gfx_block_info *gfxalloc_pop_unused(gfx_allocator *alloc) { - GFXALLOC_ASSERT(alloc->unused_list != NULL); + GFXALLOC_ASSERT(alloc->unused_list != nullptr); GFXALLOC_ASSERT(alloc->unused_list->is_unused); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_unused);) @@ -1452,7 +1452,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma U32 i, max_blocks, size; if (!align || (align & (align - 1)) != 0) // align must be >0 and a power of 2 - return NULL; + return nullptr; // for <= max_allocs live allocs, there's <= 2*max_allocs+1 blocks. worst case: // [free][used][free] .... [free][used][free] @@ -1460,7 +1460,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma size = sizeof(gfx_allocator) + max_blocks * sizeof(gfx_block_info); a = (gfx_allocator *) IggyGDrawMalloc(size); if (!a) - return NULL; + return nullptr; memset(a, 0, size); @@ -1501,16 +1501,16 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma a->blocks[i].is_unused = 1; gfxalloc_check(a); - debug_complete_check(a, NULL, 0,0); + debug_complete_check(a, nullptr, 0,0); return a; } static void *gfxalloc_alloc(gfx_allocator *alloc, U32 size_in_bytes) { - gfx_block_info *cur, *best = NULL; + gfx_block_info *cur, *best = nullptr; U32 i, best_wasted = ~0u; U32 size = size_in_bytes; -debug_complete_check(alloc, NULL, 0,0); +debug_complete_check(alloc, nullptr, 0,0); gfxalloc_check(alloc); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_blocks == alloc->num_alloc + alloc->num_free + alloc->num_unused);) GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_free <= alloc->num_blocks+1);) @@ -1560,7 +1560,7 @@ gfxalloc_check(alloc); debug_check_overlap(alloc->cache, best->ptr, best->size); return best->ptr; } else - return NULL; // not enough space! + return nullptr; // not enough space! } static void gfxalloc_free(gfx_allocator *alloc, void *ptr) @@ -1730,7 +1730,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta // (unused for allocated blocks, we'll use it to store a back-pointer to the corresponding handle) for (b = alloc->blocks[0].next_phys; b != alloc->blocks; b=b->next_phys) if (!b->is_free) - b->prev = NULL; + b->prev = nullptr; // go through all handles and store a pointer to the handle in the corresponding memory block for (i=0; i < c->max_handles; i++) @@ -1743,7 +1743,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta break; } - GFXALLOC_ASSERT(b != NULL); // didn't find this block anywhere! + GFXALLOC_ASSERT(b != nullptr); // didn't find this block anywhere! } // clear alloc hash table (we rebuild it during defrag) @@ -1905,7 +1905,7 @@ static rrbool gdraw_CanDefragment(GDrawHandleCache *c) static rrbool gdraw_MigrateResource(GDrawHandle *t, GDrawStats *stats) { GDrawHandleCache *c = t->cache; - void *ptr = NULL; + void *ptr = nullptr; assert(t->state == GDRAW_HANDLE_STATE_live || t->state == GDRAW_HANDLE_STATE_locked || t->state == GDRAW_HANDLE_STATE_pinned); // anything we migrate should be in the "other" (old) pool @@ -2295,7 +2295,7 @@ static void gdraw_bufring_init(gdraw_bufring * RADRESTRICT ring, void *ptr, U32 static void gdraw_bufring_shutdown(gdraw_bufring * RADRESTRICT ring) { - ring->cur = NULL; + ring->cur = nullptr; ring->seg_size = 0; } @@ -2305,7 +2305,7 @@ static void *gdraw_bufring_alloc(gdraw_bufring * RADRESTRICT ring, U32 size, U32 gdraw_bufring_seg *seg; if (size > ring->seg_size) - return NULL; // nope, won't fit + return nullptr; // nope, won't fit assert(align <= ring->align); @@ -2410,7 +2410,7 @@ static rrbool gdraw_res_free_lru(GDrawHandleCache *c, GDrawStats *stats) // was it referenced since end of previous frame (=in this frame)? // if some, we're thrashing; report it to the user, but only once per frame. if (c->prev_frame_end.value < r->fence.value && !c->is_thrashing) { - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); c->is_thrashing = true; } @@ -2430,8 +2430,8 @@ static GDrawHandle *gdraw_res_alloc_outofmem(GDrawHandleCache *c, GDrawHandle *t { if (t) gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); - return NULL; + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); + return nullptr; } #ifndef GDRAW_MANAGE_MEM @@ -2440,7 +2440,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt { GDrawHandle *t; if (size > c->total_bytes) - gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); else { // given how much data we're going to allocate, throw out // data until there's "room" (this basically lets us use @@ -2448,7 +2448,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // packing it and being exact) while (c->bytes_free < size) { if (!gdraw_res_free_lru(c, stats)) { - gdraw_res_alloc_outofmem(c, NULL, "memory"); + gdraw_res_alloc_outofmem(c, nullptr, "memory"); break; } } @@ -2463,8 +2463,8 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // we'd trade off cost of regenerating) if (gdraw_res_free_lru(c, stats)) { t = gdraw_HandleCacheAllocateBegin(c); - if (t == NULL) { - gdraw_res_alloc_outofmem(c, NULL, "handles"); + if (t == nullptr) { + gdraw_res_alloc_outofmem(c, nullptr, "handles"); } } } @@ -2508,7 +2508,7 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) { GDRAW_FENCE_FLUSH(); // dead list is sorted by fence index - make sure all fence values are current. - r->owner = NULL; + r->owner = nullptr; gdraw_HandleCacheInsertDead(r); gdraw_res_reap(r->cache, stats); } @@ -2516,11 +2516,11 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawStats *stats) { GDrawHandle *t; - void *ptr = NULL; + void *ptr = nullptr; gdraw_res_reap(c, stats); // NB this also does GDRAW_FENCE_FLUSH(); if (size > c->total_bytes) - return gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + return gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); // now try to allocate a handle t = gdraw_HandleCacheAllocateBegin(c); @@ -2532,7 +2532,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt gdraw_res_free_lru(c, stats); t = gdraw_HandleCacheAllocateBegin(c); if (!t) - return gdraw_res_alloc_outofmem(c, NULL, "handles"); + return gdraw_res_alloc_outofmem(c, nullptr, "handles"); } // try to allocate first diff --git a/Minecraft.Client/Durango/Iggy/include/gdraw.h b/Minecraft.Client/Durango/Iggy/include/gdraw.h index 404a2642b..7cc4ddd0e 100644 --- a/Minecraft.Client/Durango/Iggy/include/gdraw.h +++ b/Minecraft.Client/Durango/Iggy/include/gdraw.h @@ -356,13 +356,13 @@ IDOC typedef struct GDrawPrimitive IDOC typedef void RADLINK gdraw_draw_indexed_triangles(GDrawRenderState *r, GDrawPrimitive *prim, GDrawVertexBuffer *buf, GDrawStats *stats); /* Draws a collection of indexed triangles, ignoring special filters or blend modes. - If buf is NULL, then the pointers in 'prim' are machine pointers, and + If buf is nullptr, then the pointers in 'prim' are machine pointers, and you need to make a copy of the data (note currently all triangles implementing strokes (wide lines) go this path). - If buf is non-NULL, then use the appropriate vertex buffer, and the + If buf is non-nullptr, then use the appropriate vertex buffer, and the pointers in prim are actually offsets from the beginning of the - vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) NULL; + vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) nullptr; (note there are separate spaces for vertices and indices; e.g. the first mesh in a given vertex buffer will normally have a 0 offset for the vertices and a 0 offset for the indices) @@ -455,7 +455,7 @@ IDOC typedef GDrawTexture * RADLINK gdraw_make_texture_end(GDraw_MakeTexture_Pro /* Ends specification of a new texture. $:info The same handle initially passed to $gdraw_make_texture_begin - $:return Handle for the newly created texture, or NULL if an error occured + $:return Handle for the newly created texture, or nullptr if an error occured */ IDOC typedef rrbool RADLINK gdraw_update_texture_begin(GDrawTexture *tex, void *unique_id, GDrawStats *stats); diff --git a/Minecraft.Client/Durango/Iggy/include/iggyexpruntime.h b/Minecraft.Client/Durango/Iggy/include/iggyexpruntime.h index 1f1a90a1c..a42ccbfff 100644 --- a/Minecraft.Client/Durango/Iggy/include/iggyexpruntime.h +++ b/Minecraft.Client/Durango/Iggy/include/iggyexpruntime.h @@ -25,8 +25,8 @@ IDOC RADEXPFUNC HIGGYEXP RADEXPLINK IggyExpCreate(char *ip_address, S32 port, vo $:storage A small block of storage that needed to store the $HIGGYEXP, must be at least $IGGYEXP_MIN_STORAGE $:storage_size_in_bytes The size of the block pointer to by storage -Returns a NULL HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer -can be contacted at the specified address/port. Otherwise returns a non-NULL $HIGGYEXP +Returns a nullptr HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer +can be contacted at the specified address/port. Otherwise returns a non-nullptr $HIGGYEXP which you can pass to $IggyUseExplorer. */ IDOC RADEXPFUNC void RADEXPLINK IggyExpDestroy(HIGGYEXP p); diff --git a/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp b/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp index 46b046068..cc19b7382 100644 --- a/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp +++ b/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp @@ -14,7 +14,7 @@ DurangoLeaderboardManager::DurangoLeaderboardManager() m_openSessions = 0; m_xboxLiveContext = nullptr; - m_scores = NULL; + m_scores = nullptr; m_readCount = 0; m_maxRank = 0; m_waitingForProfiles = false; @@ -160,7 +160,7 @@ void DurangoLeaderboardManager::Tick() m_displayNames.clear(); } - //assert(m_scores != NULL || m_readCount == 0); + //assert(m_scores != nullptr || m_readCount == 0); view.m_numQueries = m_readCount; view.m_queries = m_scores; @@ -170,7 +170,7 @@ void DurangoLeaderboardManager::Tick() eStatsReturn ret = view.m_numQueries > 0 ? eStatsReturn_Success : eStatsReturn_NoResults; - if (m_readListener != NULL) + if (m_readListener != nullptr) { app.DebugPrintf("[LeaderboardManager] OnStatsReadComplete(%i, %i, _)\n", ret, m_readCount); m_readListener->OnStatsReadComplete(ret, m_maxRank, view); @@ -178,7 +178,7 @@ void DurangoLeaderboardManager::Tick() app.DebugPrintf("[LeaderboardManager] Deleting scores\n"); delete [] m_scores; - m_scores = NULL; + m_scores = nullptr; setState(eStatsState_Idle); } @@ -186,9 +186,9 @@ void DurangoLeaderboardManager::Tick() case eStatsState_Failed: view.m_numQueries = 0; - view.m_queries = NULL; + view.m_queries = nullptr; - if ( m_readListener != NULL ) + if ( m_readListener != nullptr ) { m_readListener->OnStatsReadComplete(eStatsReturn_NetworkError, 0, view); } @@ -371,7 +371,7 @@ void DurangoLeaderboardManager::FlushStats() //Cancel the current operation void DurangoLeaderboardManager::CancelOperation() { - m_readListener = NULL; + m_readListener = nullptr; setState(eStatsState_Canceled); if(m_leaderboardAsyncOp) m_leaderboardAsyncOp->Cancel(); @@ -428,7 +428,7 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperationDisplayName->Data(), - LeaderboardManager::filterNames[ (int) filter ].c_str(), + LeaderboardManager::filterNames[ static_cast(filter) ].c_str(), lastResult->Rows->Size, lastResult->TotalRowCount, readCount ); @@ -458,7 +458,7 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperationTotalRowCount; m_readCount = lastResult->Rows->Size; - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_scores = new ReadScore[m_readCount]; ZeroMemory(m_scores, sizeof(ReadScore) * m_readCount); @@ -480,10 +480,10 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperationGamertag->Data(); m_scores[index].m_rank = row->Rank; - m_scores[index].m_uid = PlayerUID(row->XboxUserId->Data()); + m_scores[index].m_uid = static_cast(row->XboxUserId->Data()); // 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(row->Values->GetAt(0)->Data()); + m_scores[index].m_totalScore = static_cast(_fromString(row->Values->GetAt(0)->Data())); m_xboxUserIds->Append(row->XboxUserId); } @@ -493,7 +493,7 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperation xuids = vector(); for(int i = 0; i < lastResult->Rows->Size; i++) { - xuids.push_back(PlayerUID(lastResult->Rows->GetAt(i)->XboxUserId->Data())); + xuids.push_back(static_cast(lastResult->Rows->GetAt(i)->XboxUserId->Data())); } m_waitingForProfiles = true; ProfileManager.GetProfiles(xuids, &GetProfilesCallback, this); @@ -579,7 +579,7 @@ void DurangoLeaderboardManager::updateStatsInfo(int userIndex, int difficulty, E void DurangoLeaderboardManager::GetProfilesCallback(LPVOID param, std::vector profiles) { - DurangoLeaderboardManager *dlm = (DurangoLeaderboardManager *)param; + DurangoLeaderboardManager *dlm = static_cast(param); app.DebugPrintf("[LeaderboardManager] GetProfilesCallback, profiles.size() == %d.\n", profiles.size()); diff --git a/Minecraft.Client/Durango/Leaderboards/DurangoStatsDebugger.cpp b/Minecraft.Client/Durango/Leaderboards/DurangoStatsDebugger.cpp index caa5857e9..5ac711417 100644 --- a/Minecraft.Client/Durango/Leaderboards/DurangoStatsDebugger.cpp +++ b/Minecraft.Client/Durango/Leaderboards/DurangoStatsDebugger.cpp @@ -84,7 +84,7 @@ vector *StatParam::getStats() return out; } -DurangoStatsDebugger *DurangoStatsDebugger::instance = NULL; +DurangoStatsDebugger *DurangoStatsDebugger::instance = nullptr; DurangoStatsDebugger::DurangoStatsDebugger() { @@ -320,7 +320,7 @@ DurangoStatsDebugger *DurangoStatsDebugger::Initialize() void DurangoStatsDebugger::PrintStats(int iPad) { - if (instance == NULL) instance = Initialize(); + if (instance == nullptr) instance = Initialize(); vector *tmp = instance->getStats(); instance->m_printQueue.insert(instance->m_printQueue.end(), tmp->begin(), tmp->end()); diff --git a/Minecraft.Client/Durango/Leaderboards/GameProgress.cpp b/Minecraft.Client/Durango/Leaderboards/GameProgress.cpp index dd07f3e96..f97f9bb33 100644 --- a/Minecraft.Client/Durango/Leaderboards/GameProgress.cpp +++ b/Minecraft.Client/Durango/Leaderboards/GameProgress.cpp @@ -10,11 +10,11 @@ namespace WFC = Windows::Foundation::Collections; namespace MXSA = Microsoft::Xbox::Services::Achievements; namespace CC = concurrency; -GameProgress *GameProgress::instance = NULL; +GameProgress *GameProgress::instance = nullptr; void GameProgress::Flush(int iPad) { - if (instance == NULL) + if (instance == nullptr) instance = new GameProgress(); instance->updatePlayer(iPad); @@ -22,7 +22,7 @@ void GameProgress::Flush(int iPad) void GameProgress::Tick() { - if (instance == NULL) + if (instance == nullptr) instance = new GameProgress(); long long currentTime = System::currentTimeMillis(); @@ -103,5 +103,5 @@ void GameProgress::updatePlayer(int iPad) float GameProgress::calcGameProgress(int achievementsUnlocked) { - return (float) achievementsUnlocked / 0.60f; + return static_cast(achievementsUnlocked) / 0.60f; } \ No newline at end of file diff --git a/Minecraft.Client/Durango/Network/ChatIntegrationLayer.h b/Minecraft.Client/Durango/Network/ChatIntegrationLayer.h index 80b4e10a3..f81a0f1f1 100644 --- a/Minecraft.Client/Durango/Network/ChatIntegrationLayer.h +++ b/Minecraft.Client/Durango/Network/ChatIntegrationLayer.h @@ -238,7 +238,7 @@ private: __in ChatPacketType chatPacketType ); Concurrency::critical_section m_chatPacketStatsLock; - int m_chatVoicePacketsStatistic[2][(int)Microsoft::Xbox::GameChat::ChatMessageType::InvalidMessage+1]; + int m_chatVoicePacketsStatistic[2][static_cast(Microsoft::Xbox::GameChat::ChatMessageType::InvalidMessage)+1]; }; std::shared_ptr GetChatIntegrationLayer(); \ No newline at end of file diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp b/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp index 39dc53a93..9e9e78c0c 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp @@ -25,7 +25,7 @@ int DQRNetworkManager::m_bootUserIndex; wstring DQRNetworkManager::m_bootSessionName; wstring DQRNetworkManager::m_bootServiceConfig; wstring DQRNetworkManager::m_bootSessionTemplate; -DQRNetworkManager * DQRNetworkManager::s_pDQRManager = NULL; +DQRNetworkManager * DQRNetworkManager::s_pDQRManager = nullptr; //using namespace Windows::Xbox::Networking; @@ -87,16 +87,16 @@ DQRNetworkManager::DQRNetworkManager(IDQRNetworkManagerListener *listener) memset(&m_roomSyncData, 0, sizeof(m_roomSyncData)); memset(m_players, 0, sizeof(m_players)); - m_CreateSessionThread = NULL; - m_GetFriendPartyThread = NULL; - m_UpdateCustomSessionDataThread = NULL; + m_CreateSessionThread = nullptr; + m_GetFriendPartyThread = nullptr; + m_UpdateCustomSessionDataThread = nullptr; - m_CheckPartyInviteThread = NULL; + m_CheckPartyInviteThread = nullptr; m_notifyForFullParty = false; m_customDataDirtyUpdateTicks = 0; m_sessionResultCount = 0; - m_sessionSearchResults = NULL; + m_sessionSearchResults = nullptr; m_joinSessionUserMask = 0; m_cancelJoinFromSearchResult = false; @@ -274,7 +274,7 @@ void DQRNetworkManager::JoinSession(int playerMask) // If we found the session, then set the status of this member to be active (should be reserved). This will stop our slot timing out and us being dropped out of the session. if( session != nullptr ) { - if(!IsPlayerInSession(joiningUser->XboxUserId, session, NULL) ) + if(!IsPlayerInSession(joiningUser->XboxUserId, session, nullptr) ) { app.DebugPrintf("DNM_INT_STATE_JOINING_FAILED didn't find required player in session\n"); SetState(DNM_INT_STATE_JOINING_FAILED); @@ -515,7 +515,7 @@ bool DQRNetworkManager::AddLocalPlayerByUserIndex(int userIndex) pPlayer->SetSmallId(smallId); pPlayer->SetName(ProfileManager.GetUser(userIndex)->DisplayInfo->Gamertag->Data()); pPlayer->SetDisplayName(ProfileManager.GetDisplayName(userIndex)); - pPlayer->SetUID(PlayerUID(ProfileManager.GetUser(userIndex)->XboxUserId->Data())); + pPlayer->SetUID(static_cast(ProfileManager.GetUser(userIndex)->XboxUserId->Data())); // Also add to the party so that our friends can find us. The host will get notified of this additional player in the party, but we should ignore since we're already in the session m_partyController->AddLocalUsersToParty(1 << userIndex, ProfileManager.GetUser(0)); @@ -550,7 +550,7 @@ bool DQRNetworkManager::AddLocalPlayerByUserIndex(int userIndex) pPlayer->SetSmallId(m_currentSmallId++); pPlayer->SetName(ProfileManager.GetUser(userIndex)->DisplayInfo->Gamertag->Data()); pPlayer->SetDisplayName(ProfileManager.GetDisplayName(userIndex)); - pPlayer->SetUID(PlayerUID(ProfileManager.GetUser(userIndex)->XboxUserId->Data())); + pPlayer->SetUID(static_cast(ProfileManager.GetUser(userIndex)->XboxUserId->Data())); // TODO - could this add fail? if(AddRoomSyncPlayer( pPlayer, 0, userIndex)) @@ -600,7 +600,7 @@ bool DQRNetworkManager::AddLocalPlayerByUserIndex(int userIndex) m_joinSessionXUIDs[userIndex] = ProfileManager.GetUser(userIndex)->XboxUserId; m_partyController->AddLocalUsersToParty(1 << userIndex, ProfileManager.GetUser(0)); - m_addLocalPlayerSuccessPlayer = NULL; + m_addLocalPlayerSuccessPlayer = nullptr; m_addLocalPlayerState = DNM_ADD_PLAYER_STATE_COMPLETE_SUCCESS; } } @@ -763,7 +763,7 @@ DQRNetworkPlayer *DQRNetworkManager::GetPlayerBySmallId(int idx) } } } - return NULL; + return nullptr; } DQRNetworkPlayer *DQRNetworkManager::GetPlayerByXuid(PlayerUID xuid) @@ -778,7 +778,7 @@ DQRNetworkPlayer *DQRNetworkManager::GetPlayerByXuid(PlayerUID xuid) } } } - return NULL; + return nullptr; } // Retrieve player display name by gamertag @@ -809,7 +809,7 @@ DQRNetworkPlayer *DQRNetworkManager::GetLocalPlayerByUserIndex(int idx) } } } - return NULL; + return nullptr; } DQRNetworkPlayer *DQRNetworkManager::GetHostPlayer() @@ -892,7 +892,7 @@ void DQRNetworkManager::Tick_VoiceChat() #endif // If we have to inform the chat integration layer of any players that have joined, do that now EnterCriticalSection(&m_csVecChatPlayers); - for( int i = 0; i < m_vecChatPlayersJoined.size(); i++ ) + for( size_t i = 0; i < m_vecChatPlayersJoined.size(); i++ ) { int idx = m_vecChatPlayersJoined[i]; if( m_chat ) @@ -967,19 +967,19 @@ void DQRNetworkManager::Tick_Party() void DQRNetworkManager::Tick_CustomSessionData() { // If there was a thread updaing our custom session data, then clear it up if it is done - if( m_UpdateCustomSessionDataThread != NULL ) + if( m_UpdateCustomSessionDataThread != nullptr ) { if( !m_UpdateCustomSessionDataThread->isRunning() ) { delete m_UpdateCustomSessionDataThread; - m_UpdateCustomSessionDataThread = NULL; + m_UpdateCustomSessionDataThread = nullptr; } } // If our custom data is dirty, and we aren't currently updating, then kick off a thread to update it if( m_isHosting && ( !m_isOfflineGame ) ) { - if( m_UpdateCustomSessionDataThread == NULL ) + if( m_UpdateCustomSessionDataThread == nullptr ) { if( m_customDataDirtyUpdateTicks ) { @@ -1003,7 +1003,7 @@ void DQRNetworkManager::Tick_AddAndRemoveLocalPlayers() // A lot of handling adding local players is handled asynchronously. Trying to avoid having the callbacks that may result from this being called from the task threads, so handling this aspect of it here in the tick if( m_addLocalPlayerState == DNM_ADD_PLAYER_STATE_COMPLETE_SUCCESS ) { - // If we've completed, and we're the host, then we should have the new player to create stored here in m_localPlayerSuccessCreated. For clients, this will just be NULL as the actual + // If we've completed, and we're the host, then we should have the new player to create stored here in m_localPlayerSuccessCreated. For clients, this will just be nullptr as the actual // adding of the player happens as part of a longer process of the host creating us a reserved slot etc. etc. if( m_addLocalPlayerSuccessPlayer ) { @@ -1201,7 +1201,7 @@ void DQRNetworkManager::Tick_StateMachine() break; case DNM_INT_STATE_HOSTING_WAITING_TO_PLAY: delete m_CreateSessionThread; - m_CreateSessionThread = NULL; + m_CreateSessionThread = nullptr; // If the game is offline we can transition straight to playing if (m_isOfflineGame) StartGame(); break; @@ -1247,10 +1247,10 @@ void DQRNetworkManager::Tick_CheckInviteParty() if( !m_CheckPartyInviteThread->isRunning() ) { delete m_CheckPartyInviteThread; - m_CheckPartyInviteThread = NULL; + m_CheckPartyInviteThread = nullptr; } } - if( m_CheckPartyInviteThread == NULL ) + if( m_CheckPartyInviteThread == nullptr ) { m_inviteReceived = false; m_CheckPartyInviteThread = new C4JThread(&DQRNetworkManager::_CheckInviteThreadProc, this, "Check invite thread"); @@ -1326,11 +1326,11 @@ void DQRNetworkManager::HandleSessionChange(MXSM::MultiplayerSession^ multiplaye { // 4J-JEV: This id is needed to link stats together. // I thought setting the value from here would be less intrusive than adding an accessor. - ((DurangoStats*)GenericStats::getInstance())->setMultiplayerCorrelationId(multiplayerSession->MultiplayerCorrelationId); + static_cast(GenericStats::getInstance())->setMultiplayerCorrelationId(multiplayerSession->MultiplayerCorrelationId); } else { - ((DurangoStats*)GenericStats::getInstance())->setMultiplayerCorrelationId( nullptr ); + static_cast(GenericStats::getInstance())->setMultiplayerCorrelationId( nullptr ); } m_multiplayerSession = multiplayerSession; @@ -1403,7 +1403,7 @@ bool DQRNetworkManager::IsPlayerInSession( Platform::String^ xboxUserId, MXSM::M { Windows::Data::Json::JsonObject^ customConstant = Windows::Data::Json::JsonObject::Parse(member->MemberCustomConstantsJson); Windows::Data::Json::JsonValue^ customValue = customConstant->GetNamedValue(L"smallId"); - *smallId = (int)(customValue->GetNumber()) & 255; + *smallId = static_cast(customValue->GetNumber()) & 255; } catch (Platform::COMException^ ex) { @@ -1449,7 +1449,7 @@ void DQRNetworkManager::UpdateRoomSyncPlayers(RoomSyncData *pNewSyncData) for( int j = 0; j < m_roomSyncData.playerCount; j++ ) { tempPlayers.push_back(m_players[j]); - m_players[j] = NULL; + m_players[j] = nullptr; } // For each new player, it's either: @@ -1509,12 +1509,12 @@ void DQRNetworkManager::UpdateRoomSyncPlayers(RoomSyncData *pNewSyncData) } memcpy(&m_roomSyncData, pNewSyncData, sizeof(m_roomSyncData)); - for( int i = 0; i < tempPlayers.size(); i++ ) + for( size_t i = 0; i < tempPlayers.size(); i++ ) { m_listener->HandlePlayerLeaving(tempPlayers[i]); delete tempPlayers[i]; } - for( int i = 0; i < newPlayers.size(); i++ ) + for( size_t i = 0; i < newPlayers.size(); i++ ) { m_listener->HandlePlayerJoined(newPlayers[i]); // For clients, this is where we get notified of local and remote players joining } @@ -1592,12 +1592,12 @@ void DQRNetworkManager::RemoveRoomSyncPlayersWithSessionAddress(unsigned int ses } m_roomSyncData.playerCount = iWriteIdx; - for( int i = 0; i < removedPlayers.size(); i++ ) + for( size_t i = 0; i < removedPlayers.size(); i++ ) { m_listener->HandlePlayerLeaving(removedPlayers[i]); delete removedPlayers[i]; memset(&m_roomSyncData.players[m_roomSyncData.playerCount + i], 0, sizeof(PlayerSyncData)); - m_players[m_roomSyncData.playerCount + i] = NULL; + m_players[m_roomSyncData.playerCount + i] = nullptr; } LeaveCriticalSection(&m_csRoomSyncData); } @@ -1623,12 +1623,12 @@ void DQRNetworkManager::RemoveRoomSyncPlayer(DQRNetworkPlayer *pPlayer) } m_roomSyncData.playerCount = iWriteIdx; - for( int i = 0; i < removedPlayers.size(); i++ ) + for( size_t i = 0; i < removedPlayers.size(); i++ ) { m_listener->HandlePlayerLeaving(removedPlayers[i]); delete removedPlayers[i]; memset(&m_roomSyncData.players[m_roomSyncData.playerCount + i], 0, sizeof(PlayerSyncData)); - m_players[m_roomSyncData.playerCount + i] = NULL; + m_players[m_roomSyncData.playerCount + i] = nullptr; } } @@ -1643,7 +1643,7 @@ void DQRNetworkManager::SendRoomSyncInfo() // (2) A single byte internal data tag // (3) An unsigned int encoding the size of the combined size of all the strings in stage (5) // (4) The RoomSyncData structure itself - // (5) A wchar NULL terminated string for every active player to encode the XUID + // (5) A wchar nullptr terminated string for every active player to encode the XUID unsigned int xuidBytes = 0; for( int i = 0 ; i < m_roomSyncData.playerCount; i++ ) { @@ -1689,7 +1689,7 @@ void DQRNetworkManager::SendAddPlayerFailed(Platform::String^ xuid) // (1) 2 byte general header // (2) A single byte internal data tag // (3) An unsigned int encoding the size size of the string - // (5) A wchar NULL terminated string storing the xuid of the player which has failed to join + // (5) A wchar nullptr terminated string storing the xuid of the player which has failed to join unsigned int xuidBytes = sizeof(wchar_t) * ( xuid->Length() + 1 ); @@ -1745,7 +1745,7 @@ void DQRNetworkManager::SendSmallId(bool reliableAndSequential, int playerMask) { Windows::Data::Json::JsonObject^ customConstant = Windows::Data::Json::JsonObject::Parse(member->MemberCustomConstantsJson); Windows::Data::Json::JsonValue^ customValue = customConstant->GetNamedValue(L"smallId"); - smallId = (BYTE)(customValue->GetNumber()); + smallId = static_cast(customValue->GetNumber()); bFound = true; } catch (Platform::COMException^ ex) @@ -1797,7 +1797,7 @@ int DQRNetworkManager::GetSessionIndexForSmallId(unsigned char smallId) { Windows::Data::Json::JsonObject^ customConstant = Windows::Data::Json::JsonObject::Parse(member->MemberCustomConstantsJson); Windows::Data::Json::JsonValue^ customValue = customConstant->GetNamedValue(L"smallId"); - smallIdMember = (BYTE)(customValue->GetNumber()); + smallIdMember = static_cast(customValue->GetNumber()); } catch (Platform::COMException^ ex) { @@ -1830,7 +1830,7 @@ int DQRNetworkManager::GetSessionIndexAndSmallIdForHost(unsigned char *smallId) } if( smallIdMember > 255 ) { - *smallId = (BYTE)(smallIdMember); + *smallId = static_cast(smallIdMember); return i; } } @@ -1877,7 +1877,7 @@ Platform::String^ DQRNetworkManager::GetNextSmallIdAsJsonString() int DQRNetworkManager::_HostGameThreadProc( void* lpParameter ) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->HostGameThreadProc(); } @@ -2190,7 +2190,7 @@ int DQRNetworkManager::HostGameThreadProc() pPlayer->SetSmallId(smallId); pPlayer->SetName(user->DisplayInfo->Gamertag->Data()); pPlayer->SetDisplayName(displayName); - pPlayer->SetUID(PlayerUID(user->XboxUserId->Data())); + pPlayer->SetUID(static_cast(user->XboxUserId->Data())); AddRoomSyncPlayer( pPlayer, localSessionAddress, i); @@ -2208,7 +2208,7 @@ int DQRNetworkManager::HostGameThreadProc() int DQRNetworkManager::_LeaveRoomThreadProc( void* lpParameter ) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->LeaveRoomThreadProc(); } @@ -2311,7 +2311,7 @@ int DQRNetworkManager::LeaveRoomThreadProc() int DQRNetworkManager::_TidyUpJoinThreadProc( void* lpParameter ) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->TidyUpJoinThreadProc(); } @@ -2416,7 +2416,7 @@ int DQRNetworkManager::TidyUpJoinThreadProc() int DQRNetworkManager::_UpdateCustomSessionDataThreadProc( void* lpParameter ) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->UpdateCustomSessionDataThreadProc(); } @@ -2491,7 +2491,7 @@ int DQRNetworkManager::UpdateCustomSessionDataThreadProc() int DQRNetworkManager::_CheckInviteThreadProc(void* lpParameter) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->CheckInviteThreadProc(); } @@ -2614,7 +2614,7 @@ void DQRNetworkManager::LeaveRoom() for( int i = 0; i < m_roomSyncData.playerCount; i++ ) { delete m_players[i]; - m_players[i] = NULL; + m_players[i] = nullptr; } memset(&m_roomSyncData, 0, sizeof(m_roomSyncData)); m_displayNames.clear(); @@ -3026,8 +3026,8 @@ void DQRNetworkManager::RequestDisplayName(DQRNetworkPlayer *player) void DQRNetworkManager::GetProfileCallback(LPVOID pParam, Microsoft::Xbox::Services::Social::XboxUserProfile^ profile) { - DQRNetworkManager *dqnm = (DQRNetworkManager *)pParam; - dqnm->SetDisplayName(PlayerUID(profile->XboxUserId->Data()), profile->GameDisplayName->Data()); + DQRNetworkManager *dqnm = static_cast(pParam); + dqnm->SetDisplayName(static_cast(profile->XboxUserId->Data()), profile->GameDisplayName->Data()); } // Set player display name diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager.h b/Minecraft.Client/Durango/Network/DQRNetworkManager.h index 3c4a742cf..b74e079c1 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager.h +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager.h @@ -221,7 +221,7 @@ public: class SessionSearchResult { public: - SessionSearchResult() { m_extData = NULL; } + SessionSearchResult() { m_extData = nullptr; } ~SessionSearchResult() { free(m_extData); } wstring m_partyId; wstring m_sessionName; diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager_FriendSessions.cpp b/Minecraft.Client/Durango/Network/DQRNetworkManager_FriendSessions.cpp index 3a14a2d59..0822a93c6 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager_FriendSessions.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager_FriendSessions.cpp @@ -49,7 +49,7 @@ bool DQRNetworkManager::FriendPartyManagerSearch() m_sessionResultCount = 0; delete [] m_sessionSearchResults; - m_sessionSearchResults = NULL; + m_sessionSearchResults = nullptr; m_GetFriendPartyThread = new C4JThread(&_GetFriendsThreadProc,this,"GetFriendsThreadProc"); m_GetFriendPartyThread->Run(); @@ -61,7 +61,7 @@ bool DQRNetworkManager::FriendPartyManagerSearch() void DQRNetworkManager::FriendPartyManagerGetSessionInfo(int idx, SessionSearchResult *searchResult) { assert( idx < m_sessionResultCount ); - assert( ( m_GetFriendPartyThread == NULL ) || ( !m_GetFriendPartyThread->isRunning()) ); + assert( ( m_GetFriendPartyThread == nullptr ) || ( !m_GetFriendPartyThread->isRunning()) ); // Need to make sure that copied data has independently allocated m_extData, so both copies can be freed *searchResult = m_sessionSearchResults[idx]; @@ -71,7 +71,7 @@ void DQRNetworkManager::FriendPartyManagerGetSessionInfo(int idx, SessionSearchR int DQRNetworkManager::_GetFriendsThreadProc(void* lpParameter) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->GetFriendsThreadProc(); } @@ -410,7 +410,7 @@ int DQRNetworkManager::GetFriendsThreadProc() for( int j = 0; j < nameResolveVector[i]->Size; j++ ) { m_sessionSearchResults[i].m_playerNames[j] = nameResolveVector[i]->GetAt(j)->GameDisplayName->Data(); - m_sessionSearchResults[i].m_playerXuids[j] = PlayerUID(nameResolveVector[i]->GetAt(j)->XboxUserId->Data()); + m_sessionSearchResults[i].m_playerXuids[j] = static_cast(nameResolveVector[i]->GetAt(j)->XboxUserId->Data()); } m_sessionSearchResults[i].m_playerCount = nameResolveVector[i]->Size; m_sessionSearchResults[i].m_usedSlotCount = newSessionVector[i]->Members->Size; @@ -556,7 +556,7 @@ bool DQRNetworkManager::IsSessionFriendsOfFriends(MXSM::MultiplayerSession^ sess if (result) { - friendsOfFriends = app.GetGameHostOption(((GameSessionData *)gameSessionData)->m_uiGameHostSettings, eGameHostOption_FriendsOfFriends); + friendsOfFriends = app.GetGameHostOption(static_cast(gameSessionData)->m_uiGameHostSettings, eGameHostOption_FriendsOfFriends); } free(gameSessionData); @@ -577,7 +577,7 @@ bool DQRNetworkManager::GetGameSessionData(MXSM::MultiplayerSession^ session, vo Platform::String ^customValueString = customValue->GetString(); if( customValueString ) { - base64_decode( customValueString, (unsigned char *)gameSessionData, sizeof(GameSessionData) ); + base64_decode( customValueString, static_cast(gameSessionData), sizeof(GameSessionData) ); return true; } } diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager_SendReceive.cpp b/Minecraft.Client/Durango/Network/DQRNetworkManager_SendReceive.cpp index 9232d0959..eed3e8511 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager_SendReceive.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager_SendReceive.cpp @@ -24,7 +24,7 @@ void DQRNetworkManager::BytesReceived(int smallId, BYTE *bytes, int byteCount) DQRNetworkPlayer *host = GetPlayerBySmallId(m_hostSmallId); DQRNetworkPlayer *client = GetPlayerBySmallId(smallId); - if( ( host == NULL ) || ( client == NULL ) ) + if( ( host == nullptr ) || ( client == nullptr ) ) { return; } @@ -113,7 +113,7 @@ void DQRNetworkManager::BytesReceivedInternal(DQRConnectionInfo *connectionInfo, case DQRConnectionInfo::ConnectionState_InternalAssignSmallId2: case DQRConnectionInfo::ConnectionState_InternalAssignSmallId3: { - int channel = ((int)connectionInfo->m_internalDataState) - DQRConnectionInfo::ConnectionState_InternalAssignSmallId0; + int channel = static_cast(connectionInfo->m_internalDataState) - DQRConnectionInfo::ConnectionState_InternalAssignSmallId0; if( ( connectionInfo->m_smallIdReadMask & ( 1 << channel ) ) && ( !connectionInfo->m_channelActive[channel] ) ) { @@ -137,7 +137,7 @@ void DQRNetworkManager::BytesReceivedInternal(DQRConnectionInfo *connectionInfo, DQRNetworkPlayer *pPlayer = new DQRNetworkPlayer(this, DQRNetworkPlayer::DNP_TYPE_REMOTE, true, 0, sessionAddress); pPlayer->SetSmallId(byte); - pPlayer->SetUID(PlayerUID(m_multiplayerSession->Members->GetAt(sessionIndex)->XboxUserId->Data())); + pPlayer->SetUID(static_cast(m_multiplayerSession->Members->GetAt(sessionIndex)->XboxUserId->Data())); HostGamertagResolveDetails *resolveDetails = new HostGamertagResolveDetails(); resolveDetails->m_pPlayer = pPlayer; @@ -238,7 +238,7 @@ void DQRNetworkManager::BytesReceivedInternal(DQRConnectionInfo *connectionInfo, UpdateRoomSyncPlayers((RoomSyncData *)connectionInfo->m_pucRoomSyncData); delete connectionInfo->m_pucRoomSyncData; - connectionInfo->m_pucRoomSyncData = NULL; + connectionInfo->m_pucRoomSyncData = nullptr; connectionInfo->m_internalDataState = DQRConnectionInfo::ConnectionState_InternalHeaderByte; // If we haven't actually established a connection yet for this channel, then this is the point where we can consider this active @@ -267,7 +267,7 @@ void DQRNetworkManager::BytesReceivedInternal(DQRConnectionInfo *connectionInfo, { if( m_currentUserMask & ( 1 << i ) ) { - if( GetLocalPlayerByUserIndex(i) == NULL ) + if( GetLocalPlayerByUserIndex(i) == nullptr ) { allLocalPlayersHere = false; } @@ -307,7 +307,7 @@ void DQRNetworkManager::BytesReceivedInternal(DQRConnectionInfo *connectionInfo, // XUID fully read, can now handle what to do with it AddPlayerFailed(ref new Platform::String( (wchar_t *)connectionInfo->m_pucAddFailedPlayerData ) ); delete [] connectionInfo->m_pucAddFailedPlayerData; - connectionInfo->m_pucAddFailedPlayerData = NULL; + connectionInfo->m_pucAddFailedPlayerData = nullptr; connectionInfo->m_internalDataState = DQRConnectionInfo::ConnectionState_InternalHeaderByte; } @@ -371,7 +371,7 @@ void DQRNetworkManager::SendBytesChat(unsigned int address, BYTE *bytes, int byt void DQRNetworkManager::SendBytes(int smallId, BYTE *bytes, int byteCount) { EnterCriticalSection(&m_csSendBytes); - unsigned char *tempSendBuffer = (unsigned char *)malloc(8191 + 2); + unsigned char *tempSendBuffer = static_cast(malloc(8191 + 2)); BYTE *data = bytes; BYTE *dataEnd = bytes + byteCount; @@ -381,7 +381,7 @@ void DQRNetworkManager::SendBytes(int smallId, BYTE *bytes, int byteCount) // blocks of this size. do { - int bytesToSend = (int)(dataEnd - data); + int bytesToSend = static_cast(dataEnd - data); if( bytesToSend > 8191 ) bytesToSend = 8191; // Send header with data sending mode - see full comment in DQRNetworkManagerEventHandlers::DataReceivedHandler diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager_XRNSEvent.cpp b/Minecraft.Client/Durango/Network/DQRNetworkManager_XRNSEvent.cpp index c985a191f..ae7094fb3 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager_XRNSEvent.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager_XRNSEvent.cpp @@ -84,7 +84,7 @@ void DQRNetworkManagerEventHandlers::DataReceivedHandler(Platform::Object^ sessi } rtsMessage.m_sessionAddress = args->SessionAddress; rtsMessage.m_dataSize = args->Data->Length; - rtsMessage.m_pucData = (unsigned char *)malloc(rtsMessage.m_dataSize); + rtsMessage.m_pucData = static_cast(malloc(rtsMessage.m_dataSize)); memcpy( rtsMessage.m_pucData, args->Data->Data, rtsMessage.m_dataSize ); m_pDQRNet->m_RTSMessageQueueIncoming.push(rtsMessage); LeaveCriticalSection(&m_pDQRNet->m_csRTSMessageQueueIncoming); @@ -311,7 +311,7 @@ void DQRNetworkManager::Process_RTS_MESSAGE_DATA_RECEIVED(RTS_Message &message) break; case DQRConnectionInfo::ConnectionState_ReadBytes: // At this stage we can send up to connectionInfo->m_bytesRemaining bytes, or the number of bytes that we have remaining in the data received, whichever is lowest. - int bytesInBuffer = (int)(pEndByte - pNextByte); + int bytesInBuffer = static_cast(pEndByte - pNextByte); int bytesToReceive = ( ( connectionInfo->m_bytesRemaining < bytesInBuffer ) ? connectionInfo->m_bytesRemaining : bytesInBuffer ); if( connectionInfo->m_internalFlag ) @@ -438,7 +438,7 @@ void DQRNetworkManager::Process_RTS_MESSAGE_STATUS_TERMINATED(RTS_Message &messa int DQRNetworkManager::_RTSDoWorkThread(void* lpParameter) { - DQRNetworkManager *pDQR = (DQRNetworkManager *)lpParameter; + DQRNetworkManager *pDQR = static_cast(lpParameter); return pDQR->RTSDoWorkThread(); } @@ -603,7 +603,7 @@ void DQRNetworkManager::RTS_StartCient() EnterCriticalSection(&m_csRTSMessageQueueOutgoing); RTS_Message message; message.m_eType = eRTSMessageType::RTS_MESSAGE_START_CLIENT; - message.m_pucData = NULL; + message.m_pucData = nullptr; message.m_dataSize = 0; m_RTSMessageQueueOutgoing.push(message); LeaveCriticalSection(&m_csRTSMessageQueueOutgoing); @@ -614,7 +614,7 @@ void DQRNetworkManager::RTS_StartHost() EnterCriticalSection(&m_csRTSMessageQueueOutgoing); RTS_Message message; message.m_eType = eRTSMessageType::RTS_MESSAGE_START_HOST; - message.m_pucData = NULL; + message.m_pucData = nullptr; message.m_dataSize = 0; m_RTSMessageQueueOutgoing.push(message); LeaveCriticalSection(&m_csRTSMessageQueueOutgoing); @@ -625,7 +625,7 @@ void DQRNetworkManager::RTS_Terminate() EnterCriticalSection(&m_csRTSMessageQueueOutgoing); RTS_Message message; message.m_eType = eRTSMessageType::RTS_MESSAGE_TERMINATE; - message.m_pucData = NULL; + message.m_pucData = nullptr; message.m_dataSize = 0; m_RTSMessageQueueOutgoing.push(message); LeaveCriticalSection(&m_csRTSMessageQueueOutgoing); @@ -636,7 +636,7 @@ void DQRNetworkManager::RTS_SendData(unsigned char *pucData, unsigned int dataSi EnterCriticalSection(&m_csRTSMessageQueueOutgoing); RTS_Message message; message.m_eType = eRTSMessageType::RTS_MESSAGE_SEND_DATA; - message.m_pucData = (unsigned char *)malloc(dataSize); + message.m_pucData = static_cast(malloc(dataSize)); memcpy(message.m_pucData, pucData, dataSize); message.m_dataSize = dataSize; message.m_sessionAddress = sessionAddress; diff --git a/Minecraft.Client/Durango/Network/DQRNetworkPlayer.cpp b/Minecraft.Client/Durango/Network/DQRNetworkPlayer.cpp index e2d82a902..a8140764c 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkPlayer.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkPlayer.cpp @@ -97,7 +97,7 @@ bool DQRNetworkPlayer::HasVoice() Microsoft::Xbox::GameChat::ChatUser^ chatUser = m_manager->m_chat->GetChatUserByXboxUserId(ref new Platform::String(m_UID.toString().c_str())); if( chatUser == nullptr ) return false; - if( ((int)chatUser->ParticipantType) & ((int)Windows::Xbox::Chat::ChatParticipantTypes::Talker) ) + if( static_cast(chatUser->ParticipantType) & static_cast(Windows::Xbox::Chat::ChatParticipantTypes::Talker) ) { return true; } diff --git a/Minecraft.Client/Durango/Network/NetworkPlayerDurango.cpp b/Minecraft.Client/Durango/Network/NetworkPlayerDurango.cpp index fd2181df9..84a34a97e 100644 --- a/Minecraft.Client/Durango/Network/NetworkPlayerDurango.cpp +++ b/Minecraft.Client/Durango/Network/NetworkPlayerDurango.cpp @@ -4,7 +4,7 @@ NetworkPlayerDurango::NetworkPlayerDurango(DQRNetworkPlayer *qnetPlayer) { m_dqrPlayer = qnetPlayer; - m_pSocket = NULL; + m_pSocket = nullptr; } unsigned char NetworkPlayerDurango::GetSmallId() @@ -14,12 +14,12 @@ unsigned char NetworkPlayerDurango::GetSmallId() void NetworkPlayerDurango::SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority) { - m_dqrPlayer->SendData( ((NetworkPlayerDurango *)player)->m_dqrPlayer, pvData, dataSize ); + m_dqrPlayer->SendData( static_cast(player)->m_dqrPlayer, pvData, dataSize ); } bool NetworkPlayerDurango::IsSameSystem(INetworkPlayer *player) { - return m_dqrPlayer->IsSameSystem(((NetworkPlayerDurango *)player)->m_dqrPlayer); + return m_dqrPlayer->IsSameSystem(static_cast(player)->m_dqrPlayer); } int NetworkPlayerDurango::GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ) diff --git a/Minecraft.Client/Durango/Network/PartyController.cpp b/Minecraft.Client/Durango/Network/PartyController.cpp index 753a71aca..1dfd5eb0a 100644 --- a/Minecraft.Client/Durango/Network/PartyController.cpp +++ b/Minecraft.Client/Durango/Network/PartyController.cpp @@ -103,7 +103,7 @@ void PartyController::RefreshPartyView() } catch ( Platform::Exception^ ex ) { - if( ex->HResult != (int)Windows::Xbox::Multiplayer::PartyErrorStatus::EmptyParty ) + if( ex->HResult != static_cast(Windows::Xbox::Multiplayer::PartyErrorStatus::EmptyParty) ) { // LogCommentWithError( L"GetPartyView failed", ex->HResult ); } @@ -181,7 +181,7 @@ bool PartyController::AddLocalUsersToParty(int userMask, Windows::Xbox::System:: bool alreadyInSession = false; if( session ) { - if( m_pDQRNet->IsPlayerInSession( ProfileManager.GetUser(i, true)->XboxUserId, session, NULL ) ) + if( m_pDQRNet->IsPlayerInSession( ProfileManager.GetUser(i, true)->XboxUserId, session, nullptr ) ) { alreadyInSession = true; } @@ -577,7 +577,7 @@ void PartyController::OnPartyRosterChanged( PartyRosterChangedEventArgs^ eventAr // Still a party, find out who left for( int i = 0; i < eventArgs->RemovedMembers->Size; i++ ) { - DQRNetworkPlayer *player = m_pDQRNet->GetPlayerByXuid(PlayerUID(eventArgs->RemovedMembers->GetAt(i)->Data())); + DQRNetworkPlayer *player = m_pDQRNet->GetPlayerByXuid(static_cast(eventArgs->RemovedMembers->GetAt(i)->Data())); if( player ) { if( player->IsLocal() ) @@ -621,7 +621,7 @@ void PartyController::AddAvailableGamePlayers(IVectorView^ availabl } #endif - if( m_pDQRNet->IsPlayerInSession(player->XboxUserId, currentSession, NULL)) + if( m_pDQRNet->IsPlayerInSession(player->XboxUserId, currentSession, nullptr)) { DQRNetworkManager::LogComment( L"Player is already in session; skipping join request: " + player->XboxUserId->ToString() ); continue; @@ -639,7 +639,7 @@ void PartyController::AddAvailableGamePlayers(IVectorView^ availabl { bFoundLocal = true; // Check that they aren't in the game already (don't see how this could be the case anyway) - if( m_pDQRNet->GetPlayerByXuid( PlayerUID(player->XboxUserId->Data()) ) == NULL ) + if( m_pDQRNet->GetPlayerByXuid( static_cast(player->XboxUserId->Data()) ) == nullptr ) { // And check whether they are signed in yet or not int userIdx = -1; @@ -838,7 +838,7 @@ void PartyController::OnGameSessionReady( GameSessionReadyEventArgs^ eventArgs ) if( !isAJoiningXuid ) // Isn't someone we are actively trying to join { if( (!bInSession) || // If not in a game session at all - ( ( m_pDQRNet->GetState() == DQRNetworkManager::DNM_INT_STATE_PLAYING ) && ( m_pDQRNet->GetPlayerByXuid( PlayerUID(memberXUID->Data()) ) == NULL ) ) // Or we're fully in, and this player isn't in it + ( ( m_pDQRNet->GetState() == DQRNetworkManager::DNM_INT_STATE_PLAYING ) && ( m_pDQRNet->GetPlayerByXuid( static_cast(memberXUID->Data()) ) == nullptr ) ) // Or we're fully in, and this player isn't in it ) { for( int j = 4; j < 12; j++ ) // Final check that we have a gamepad for this xuid so that we might possibly be able to pair someone up @@ -1201,5 +1201,5 @@ double PartyController::GetTimeBetweenInSeconds(Windows::Foundation::DateTime dt { const uint64 tickPerSecond = 10000000i64; uint64 deltaTime = dt2.UniversalTime - dt1.UniversalTime; - return (double)deltaTime / (double)tickPerSecond; + return static_cast(deltaTime) / static_cast(tickPerSecond); } \ No newline at end of file diff --git a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp index 925a37a8e..5e3a08245 100644 --- a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp +++ b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp @@ -87,7 +87,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl bool createFakeSocket = false; bool localPlayer = false; - NetworkPlayerDurango *networkPlayer = (NetworkPlayerDurango *)addNetworkPlayer(pDQRPlayer); + NetworkPlayerDurango *networkPlayer = static_cast(addNetworkPlayer(pDQRPlayer)); // Request full display name for this player m_pDQRNet->RequestDisplayName(pDQRPlayer); @@ -166,7 +166,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); } @@ -175,7 +175,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pDQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pDQRNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -198,7 +198,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP { // Get our wrapper object associated with this player. Socket *socket = networkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { // If we are in game then remove this player from the game as well. // We may get here either from the player requesting to exit the game, @@ -214,14 +214,14 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP // We need this as long as the game server still needs to communicate with the player //delete socket; - networkPlayer->SetSocket( NULL ); + networkPlayer->SetSocket( nullptr ); } if( m_pDQRNet->IsHost() && !m_bHostChanged ) { if( isSystemPrimaryPlayer(pDQRPlayer) ) { - DQRNetworkPlayer *pNewDQRPrimaryPlayer = NULL; + DQRNetworkPlayer *pNewDQRPrimaryPlayer = nullptr; for(unsigned int i = 0; i < m_pDQRNet->GetPlayerCount(); ++i ) { DQRNetworkPlayer *pDQRPlayer2 = m_pDQRNet->GetPlayerByIndex( i ); @@ -238,7 +238,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP m_machineDQRPrimaryPlayers.erase( it ); } - if( pNewDQRPrimaryPlayer != NULL ) + if( pNewDQRPrimaryPlayer != nullptr ) m_machineDQRPrimaryPlayers.push_back( pNewDQRPrimaryPlayer ); } @@ -251,7 +251,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, true ); } @@ -260,7 +260,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pDQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pDQRNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -289,7 +289,7 @@ void CPlatformNetworkManagerDurango::HandleDataReceived(DQRNetworkPlayer *player INetworkPlayer *pPlayerFrom = getNetworkPlayer(playerFrom); Socket *socket = pPlayerFrom->GetSocket(); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(data, dataSize, false); } else @@ -298,7 +298,7 @@ void CPlatformNetworkManagerDurango::HandleDataReceived(DQRNetworkPlayer *player INetworkPlayer *pPlayerTo = getNetworkPlayer(playerTo); Socket *socket = pPlayerTo->GetSocket(); //app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", apPlayersTo[dwPlayer]->GetGamertag()); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(data, dataSize); } } @@ -319,7 +319,7 @@ bool CPlatformNetworkManagerDurango::Initialise(CGameNetworkManager *pGameNetwor g_pPlatformNetworkManager = this; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - playerChangedCallback[ i ] = NULL; + playerChangedCallback[ i ] = nullptr; } m_bLeavingGame = false; @@ -330,14 +330,14 @@ bool CPlatformNetworkManagerDurango::Initialise(CGameNetworkManager *pGameNetwor m_bSearchPending = false; m_bIsOfflineGame = false; - m_pSearchParam = NULL; - m_SessionsUpdatedCallback = NULL; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; m_searchResultsCount = 0; m_lastSearchStartTime = 0; // The results that will be filled in with the current search - m_pSearchResults = NULL; + m_pSearchResults = nullptr; Windows::Networking::Connectivity::NetworkInformation::NetworkStatusChanged += ref new Windows::Networking::Connectivity::NetworkStatusChangedEventHandler( []( Platform::Object^ pxObject ) { @@ -585,8 +585,8 @@ void CPlatformNetworkManagerDurango::UnRegisterPlayerChangedCallback(int iPad, v { if(playerChangedCallbackParam[iPad] == callbackParam) { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; + playerChangedCallback[iPad] = nullptr; + playerChangedCallbackParam[iPad] = nullptr; } } @@ -613,12 +613,12 @@ bool CPlatformNetworkManagerDurango::_RunNetworkGame() return true; } -void CPlatformNetworkManagerDurango::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) +void CPlatformNetworkManagerDurango::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= nullptr*/) { if( this->m_bLeavingGame ) return; - if( GetHostPlayer() == NULL ) + if( GetHostPlayer() == nullptr ) return; m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); @@ -628,18 +628,18 @@ void CPlatformNetworkManagerDurango::UpdateAndSetGameSessionData(INetworkPlayer int CPlatformNetworkManagerDurango::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) { - INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; + INetworkPlayer *pNetworkPlayer = static_cast(lpParam); Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); socket->m_socketClosedEvent->WaitForSignal(INFINITE); //printf("Socket closed event has fired\n"); // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); + pNetworkPlayer->SetSocket( nullptr ); delete socket; } @@ -712,7 +712,7 @@ void CPlatformNetworkManagerDurango::SystemFlagReset() void CPlatformNetworkManagerDurango::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; + if( pNetworkPlayer == nullptr ) return; for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) { @@ -728,7 +728,7 @@ void CPlatformNetworkManagerDurango::SystemFlagSet(INetworkPlayer *pNetworkPlaye bool CPlatformNetworkManagerDurango::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) + if( pNetworkPlayer == nullptr ) { return false; } @@ -769,7 +769,7 @@ void CPlatformNetworkManagerDurango::TickSearch() } m_bSearchPending = false; - if( m_SessionsUpdatedCallback != NULL ) m_SessionsUpdatedCallback(m_pSearchParam); + if( m_SessionsUpdatedCallback != nullptr ) m_SessionsUpdatedCallback(m_pSearchParam); } } else @@ -777,7 +777,7 @@ void CPlatformNetworkManagerDurango::TickSearch() if( !m_pDQRNet->FriendPartyManagerIsBusy() ) { // Don't start searches unless we have registered a callback - if( m_SessionsUpdatedCallback != NULL && (m_lastSearchStartTime + MINECRAFT_DURANGO_PARTY_SEARCH_DELAY_MILLISECONDS) < GetTickCount() ) + if( m_SessionsUpdatedCallback != nullptr && (m_lastSearchStartTime + MINECRAFT_DURANGO_PARTY_SEARCH_DELAY_MILLISECONDS) < GetTickCount() ) { if( m_pDQRNet->FriendPartyManagerSearch() ); { @@ -794,13 +794,13 @@ vector *CPlatformNetworkManagerDurango::GetSessionList(int vector *filteredList = new vector(); for( int i = 0; i < m_searchResultsCount; i++ ) { - GameSessionData *gameSessionData = (GameSessionData *)m_pSearchResults[i].m_extData; + GameSessionData *gameSessionData = static_cast(m_pSearchResults[i].m_extData); if( ( gameSessionData->netVersion == MINECRAFT_NET_VERSION ) && ( gameSessionData->isReadyToJoin ) ) { FriendSessionInfo *session = new FriendSessionInfo(); session->searchResult = m_pSearchResults[i]; - session->searchResult.m_extData = NULL; // We have another copy of the GameSessionData, so don't need to make another copy of this here + session->searchResult.m_extData = nullptr; // We have another copy of the GameSessionData, so don't need to make another copy of this here session->displayLabelLength = session->searchResult.m_playerNames[0].size(); session->displayLabel = new wchar_t[ session->displayLabelLength + 1 ]; memcpy(&session->data, gameSessionData, sizeof(GameSessionData)); @@ -832,7 +832,7 @@ void CPlatformNetworkManagerDurango::ForceFriendsSessionRefresh() m_lastSearchStartTime = 0; m_searchResultsCount = 0; delete [] m_pSearchResults; - m_pSearchResults = NULL; + m_pSearchResults = nullptr; } INetworkPlayer *CPlatformNetworkManagerDurango::addNetworkPlayer(DQRNetworkPlayer *pDQRPlayer) @@ -858,7 +858,7 @@ void CPlatformNetworkManagerDurango::removeNetworkPlayer(DQRNetworkPlayer *pDQRP INetworkPlayer *CPlatformNetworkManagerDurango::getNetworkPlayer(DQRNetworkPlayer *pDQRPlayer) { - return pDQRPlayer ? (INetworkPlayer *)(pDQRPlayer->GetCustomDataValue()) : NULL; + return pDQRPlayer ? (INetworkPlayer *)(pDQRPlayer->GetCustomDataValue()) : nullptr; } diff --git a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.h b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.h index 558072275..5626b0120 100644 --- a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.h +++ b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.h @@ -87,7 +87,7 @@ private: bool m_hostGameSessionIsJoinable; CGameNetworkManager *m_pGameNetworkManager; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr); private: // TODO 4J Stu - Do we need to be able to have more than one of these? diff --git a/Minecraft.Client/Durango/Network/base64.cpp b/Minecraft.Client/Durango/Network/base64.cpp index c5af745c4..c916725f1 100644 --- a/Minecraft.Client/Durango/Network/base64.cpp +++ b/Minecraft.Client/Durango/Network/base64.cpp @@ -109,13 +109,13 @@ void base64_decode(Platform::String ^encoded_string, unsigned char *output, unsi while (in_len-- && ( encoded_string->Data()[in_] != L'=') && is_base64(encoded_string->Data()[in_])) { - char_array_4[i++] = (unsigned char)(encoded_string->Data()[in_]); + char_array_4[i++] = static_cast(encoded_string->Data()[in_]); in_++; if (i ==4) { for (i = 0; i <4; i++) { - char_array_4[i] = (unsigned char )base64_chars.find(char_array_4[i]); + char_array_4[i] = static_cast(base64_chars.find(char_array_4[i])); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); @@ -140,7 +140,7 @@ void base64_decode(Platform::String ^encoded_string, unsigned char *output, unsi for (j = 0; j <4; j++) { - char_array_4[j] = (unsigned char )base64_chars.find(char_array_4[j]); + char_array_4[j] = static_cast(base64_chars.find(char_array_4[j])); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); diff --git a/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp b/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp index 2386a3484..31ab9d64b 100644 --- a/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp +++ b/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp @@ -64,7 +64,7 @@ bool CDurangoTelemetryManager::RecordPlayerSessionExit(int iPad, int exitStatus) // 4J-JEV: Still needed to flush cached travel stats. DurangoStats::playerSessionEnd(iPad); - if (plr != NULL && plr->level != NULL && plr->level->getLevelData() != NULL) + if (plr != nullptr && plr->level != nullptr && plr->level->getLevelData() != nullptr) { ULONG hr = EventWritePlayerSessionEnd( DurangoStats::getUserId(iPad), @@ -131,7 +131,7 @@ bool CDurangoTelemetryManager::RecordLevelStart(int iPad, ESen_FriendOrMatch fri ProfileManager.GetXUID(iPad, &puid, true); plr = Minecraft::GetInstance()->localplayers[iPad]; - if (plr != NULL && plr->level != NULL && plr->level->getLevelData() != NULL) + if (plr != nullptr && plr->level != nullptr && plr->level->getLevelData() != nullptr) { hr = EventWritePlayerSessionStart( DurangoStats::getUserId(iPad), @@ -968,7 +968,7 @@ bool CDurangoTelemetryManager::RecordUnBanLevel(int iPad) DurangoStats *CDurangoTelemetryManager::durangoStats() { - return (DurangoStats*) GenericStats::getInstance(); + return static_cast(GenericStats::getInstance()); } wstring CDurangoTelemetryManager::guid2str(LPCGUID guid) diff --git a/Minecraft.Client/Durango/ServiceConfig/Events-XBLA.8-149E11AEEvents.h b/Minecraft.Client/Durango/ServiceConfig/Events-XBLA.8-149E11AEEvents.h index 5fc804385..8bd113549 100644 --- a/Minecraft.Client/Durango/ServiceConfig/Events-XBLA.8-149E11AEEvents.h +++ b/Minecraft.Client/Durango/ServiceConfig/Events-XBLA.8-149E11AEEvents.h @@ -195,7 +195,7 @@ EventWriteAchievementGet(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, _ EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &AchievementId, sizeof(AchievementId)); @@ -216,7 +216,7 @@ EventWriteAchievemntUnlocked(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionI EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -246,7 +246,7 @@ EventWriteBanLevel(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in co EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -274,7 +274,7 @@ EventWriteBlockBroken(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[4], &BlockId, sizeof(BlockId)); @@ -298,7 +298,7 @@ EventWriteBlockPlaced(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[4], &BlockId, sizeof(BlockId)); @@ -322,7 +322,7 @@ EventWriteChestfulOfCobblestone(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessi EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &Cobblecount, sizeof(Cobblecount)); @@ -343,7 +343,7 @@ EventWriteEnteredNewBiome(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &BiomeId, sizeof(BiomeId)); @@ -364,7 +364,7 @@ EventWriteGameProgress(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __i EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &CompletionPercent, sizeof(CompletionPercent)); @@ -385,7 +385,7 @@ EventWriteIncDistanceTravelled(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessio EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[4], &Distance, sizeof(Distance)); @@ -408,7 +408,7 @@ EventWriteIncTimePlayed(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __ EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[4], &TimePlayed, sizeof(TimePlayed)); @@ -430,7 +430,7 @@ EventWriteLeaderboardTotals(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[4], &LeaderboardId, sizeof(LeaderboardId)); @@ -453,7 +453,7 @@ EventWriteLevelExit(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in c EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -482,7 +482,7 @@ EventWriteLevelResume(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -516,7 +516,7 @@ EventWriteLevelSaveOrCheckpoint(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessi EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -546,7 +546,7 @@ EventWriteLevelStart(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -579,10 +579,10 @@ EventWriteMcItemAcquired(__in_opt PCWSTR UserId, __in const signed int SectionId EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], &SectionId, sizeof(SectionId)); EventDataDescCreate(&EventData[3], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[5], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[6], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[7], &ItemId, sizeof(ItemId)); @@ -610,10 +610,10 @@ EventWriteMcItemUsed(__in_opt PCWSTR UserId, __in const signed int SectionId, __ EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], &SectionId, sizeof(SectionId)); EventDataDescCreate(&EventData[3], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[5], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[6], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[7], &ItemId, sizeof(ItemId)); @@ -641,7 +641,7 @@ EventWriteMenuShown(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in c EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -671,7 +671,7 @@ EventWriteMobInteract(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &MobId, sizeof(MobId)); EventDataDescCreate(&EventData[4], &InteractionId, sizeof(InteractionId)); @@ -693,10 +693,10 @@ EventWriteMobKilled(__in_opt PCWSTR UserId, __in const signed int SectionId, __i EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], &SectionId, sizeof(SectionId)); EventDataDescCreate(&EventData[3], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[4], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[5], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[6], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[7], RoundId, sizeof(GUID)); @@ -728,11 +728,11 @@ EventWriteMultiplayerRoundEnd(__in_opt PCWSTR UserId, __in LPCGUID RoundId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], RoundId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SectionId, sizeof(SectionId)); EventDataDescCreate(&EventData[4], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[5], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[5], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[6], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[7], &MatchTypeId, sizeof(MatchTypeId)); EventDataDescCreate(&EventData[8], &DifficultyLevelId, sizeof(DifficultyLevelId)); @@ -756,11 +756,11 @@ EventWriteMultiplayerRoundStart(__in_opt PCWSTR UserId, __in LPCGUID RoundId, __ EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], RoundId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SectionId, sizeof(SectionId)); EventDataDescCreate(&EventData[4], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[5], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[5], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[6], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[7], &MatchTypeId, sizeof(MatchTypeId)); EventDataDescCreate(&EventData[8], &DifficultyLevelId, sizeof(DifficultyLevelId)); @@ -782,7 +782,7 @@ EventWriteOnARail(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in con EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &Distance, sizeof(Distance)); @@ -803,7 +803,7 @@ EventWriteOverkill(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in co EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &Damage, sizeof(Damage)); @@ -824,7 +824,7 @@ EventWritePauseOrInactive(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -852,7 +852,7 @@ EventWritePlayedMusicDisc(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &DiscId, sizeof(DiscId)); @@ -873,7 +873,7 @@ EventWritePlayerDiedOrFailed(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionI EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -908,9 +908,9 @@ EventWritePlayerSessionEnd(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[4], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[5], &DifficultyLevelId, sizeof(DifficultyLevelId)); EventDataDescCreate(&EventData[6], &ExitStatusId, sizeof(ExitStatusId)); @@ -932,9 +932,9 @@ EventWritePlayerSessionPause(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionI EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); return EtxEventWrite(&XBLA_149E11AEEvents[28], &XBLA_149E11AEProvider, XBLA_149E11AEHandle, ARGUMENT_COUNT_XBLA_149E11AE_PlayerSessionPause, EventData); } @@ -953,9 +953,9 @@ EventWritePlayerSessionResume(__in_opt PCWSTR UserId, __in LPCGUID PlayerSession EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[4], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[5], &DifficultyLevelId, sizeof(DifficultyLevelId)); @@ -976,9 +976,9 @@ EventWritePlayerSessionStart(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionI EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); - EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != NULL) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != NULL) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[3], (MultiplayerCorrelationId != nullptr) ? MultiplayerCorrelationId : L"", (MultiplayerCorrelationId != nullptr) ? (ULONG)((wcslen(MultiplayerCorrelationId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[4], &GameplayModeId, sizeof(GameplayModeId)); EventDataDescCreate(&EventData[5], &DifficultyLevelId, sizeof(DifficultyLevelId)); @@ -999,7 +999,7 @@ EventWriteRecordMediaShareUpload(__in_opt PCWSTR UserId, __in LPCGUID PlayerSess EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1027,7 +1027,7 @@ EventWriteRichPresenceState(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &ContextID, sizeof(ContextID)); @@ -1048,7 +1048,7 @@ EventWriteSkinChanged(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1077,7 +1077,7 @@ EventWriteTexturePackLoaded(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1107,7 +1107,7 @@ EventWriteUnbanLevel(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, __in EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1135,7 +1135,7 @@ EventWriteUnpauseOrActive(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1163,7 +1163,7 @@ EventWriteUpsellPresented(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); @@ -1193,7 +1193,7 @@ EventWriteUpsellResponded(__in_opt PCWSTR UserId, __in LPCGUID PlayerSessionId, EtxFillCommonFields_v7(&EventData[0], scratch, 64); - EventDataDescCreate(&EventData[1], (UserId != NULL) ? UserId : L"", (UserId != NULL) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); + EventDataDescCreate(&EventData[1], (UserId != nullptr) ? UserId : L"", (UserId != nullptr) ? (ULONG)((wcslen(UserId) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"")); EventDataDescCreate(&EventData[2], PlayerSessionId, sizeof(GUID)); EventDataDescCreate(&EventData[3], &SecondsSinceInitialize, sizeof(SecondsSinceInitialize)); EventDataDescCreate(&EventData[4], &Mode, sizeof(Mode)); diff --git a/Minecraft.Client/Durango/XML/ATGXmlParser.cpp b/Minecraft.Client/Durango/XML/ATGXmlParser.cpp index 771ba2682..89ca77141 100644 --- a/Minecraft.Client/Durango/XML/ATGXmlParser.cpp +++ b/Minecraft.Client/Durango/XML/ATGXmlParser.cpp @@ -27,7 +27,7 @@ XMLParser::XMLParser() { m_pWritePtr = m_pWriteBuf; m_pReadPtr = m_pReadBuf; - m_pISAXCallback = NULL; + m_pISAXCallback = nullptr; m_hFile = INVALID_HANDLE_VALUE; } @@ -49,7 +49,7 @@ VOID XMLParser::FillBuffer() m_pReadPtr = m_pReadBuf; - if( m_hFile == NULL ) + if( m_hFile == nullptr ) { if( m_uInXMLBufferCharsLeft > XML_READ_BUFFER_SIZE ) NChars = XML_READ_BUFFER_SIZE; @@ -62,15 +62,15 @@ VOID XMLParser::FillBuffer() } else { - if( !ReadFile( m_hFile, m_pReadBuf, XML_READ_BUFFER_SIZE, &NChars, NULL )) + if( !ReadFile( m_hFile, m_pReadBuf, XML_READ_BUFFER_SIZE, &NChars, nullptr )) { return; } } m_dwCharsConsumed += NChars; - int64_t iProgress = m_dwCharsTotal ? (( (int64_t)m_dwCharsConsumed * 1000 ) / (int64_t)m_dwCharsTotal) : 0; - m_pISAXCallback->SetParseProgress( (DWORD)iProgress ); + int64_t iProgress = m_dwCharsTotal ? (( static_cast(m_dwCharsConsumed) * 1000 ) / static_cast(m_dwCharsTotal)) : 0; + m_pISAXCallback->SetParseProgress( static_cast(iProgress) ); m_pReadBuf[ NChars ] = '\0'; m_pReadBuf[ NChars + 1] = '\0'; @@ -198,7 +198,7 @@ HRESULT XMLParser::ConvertEscape() if( FAILED( hr = AdvanceName() ) ) return hr; - EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal ); + EntityRefLen = static_cast(m_pWritePtr - pEntityRefVal); m_pWritePtr = pEntityRefVal; if ( EntityRefLen == 0 ) @@ -359,7 +359,7 @@ HRESULT XMLParser::AdvanceCharacter( BOOL bOkToFail ) // Read more from the file FillBuffer(); - // We are at EOF if it is still NULL + // We are at EOF if it is still nullptr if ( ( m_pReadPtr[0] == '\0' ) && ( m_pReadPtr[1] == '\0' ) ) { if( !bOkToFail ) @@ -497,8 +497,8 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceName() ) ) return hr; - if( FAILED( m_pISAXCallback->ElementEnd( pEntityRefVal, - (UINT) ( m_pWritePtr - pEntityRefVal ) ) ) ) + if (FAILED(m_pISAXCallback->ElementEnd( pEntityRefVal, + static_cast(m_pWritePtr - pEntityRefVal) ))) return E_ABORT; if( FAILED( hr = ConsumeSpace() ) ) @@ -541,7 +541,7 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceName() ) ) return hr; - EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal ); + EntityRefLen = static_cast(m_pWritePtr - pEntityRefVal); if( FAILED( hr = ConsumeSpace() ) ) return hr; @@ -566,7 +566,7 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceName() ) ) return hr; - Attributes[ NumAttrs ].NameLen = (UINT)( m_pWritePtr - Attributes[ NumAttrs ].strName ); + Attributes[ NumAttrs ].NameLen = static_cast(m_pWritePtr - Attributes[NumAttrs].strName); if( FAILED( hr = ConsumeSpace() ) ) return hr; @@ -588,8 +588,8 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceAttrVal() ) ) return hr; - Attributes[ NumAttrs ].ValueLen = (UINT)( m_pWritePtr - - Attributes[ NumAttrs ].strValue ); + Attributes[ NumAttrs ].ValueLen = static_cast(m_pWritePtr - + Attributes[NumAttrs].strValue); ++NumAttrs; @@ -663,13 +663,13 @@ HRESULT XMLParser::AdvanceCDATA() if( m_pWritePtr - m_pWriteBuf >= XML_WRITE_BUFFER_SIZE ) { - if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), TRUE ) ) ) + if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), TRUE ) ) ) return E_ABORT; m_pWritePtr = m_pWriteBuf; } } - if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; m_pWritePtr = m_pWriteBuf; @@ -782,11 +782,10 @@ HRESULT XMLParser::MainParseLoop() { if( FAILED( AdvanceCharacter( TRUE ) ) ) { - if ( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) ) + if ( ( static_cast(m_pWritePtr - m_pWriteBuf) != 0 ) && ( !bWhiteSpaceOnly ) ) { - if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; - bWhiteSpaceOnly = TRUE; } @@ -798,9 +797,10 @@ HRESULT XMLParser::MainParseLoop() if( m_Ch == '<' ) { - if( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) ) +\ + if( ( static_cast(m_pWritePtr - m_pWriteBuf) != 0 ) && ( !bWhiteSpaceOnly ) ) { - if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; bWhiteSpaceOnly = TRUE; @@ -838,8 +838,7 @@ HRESULT XMLParser::MainParseLoop() if( !bWhiteSpaceOnly ) { if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, - ( UINT ) ( m_pWritePtr - m_pWriteBuf ), - TRUE ) ) ) + static_cast(m_pWritePtr - m_pWriteBuf), TRUE ) ) ) { return E_ABORT; } @@ -861,7 +860,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) { HRESULT hr; - if( m_pISAXCallback == NULL ) + if( m_pISAXCallback == nullptr ) return E_NOINTERFACE; m_pISAXCallback->m_LineNum = 1; @@ -872,16 +871,17 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) m_pReadPtr = m_pReadBuf; m_pReadBuf[ 0 ] = '\0'; + m_pReadBuf[ 1 ] = '\0'; - m_pInXMLBuffer = NULL; + m_pInXMLBuffer = nullptr; m_uInXMLBufferCharsLeft = 0; WCHAR wchFilename[ 64 ]; swprintf_s(wchFilename,64,L"%s",strFilename); - m_hFile = CreateFile( wchFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + m_hFile = CreateFile(wchFilename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if( m_hFile == INVALID_HANDLE_VALUE ) { @@ -893,7 +893,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) { LARGE_INTEGER iFileSize; GetFileSizeEx( m_hFile, &iFileSize ); - m_dwCharsTotal = (DWORD)iFileSize.QuadPart; + m_dwCharsTotal = static_cast(iFileSize.QuadPart); m_dwCharsConsumed = 0; hr = MainParseLoop(); } @@ -904,8 +904,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) m_hFile = INVALID_HANDLE_VALUE; // we no longer own strFilename, so un-set it - m_pISAXCallback->m_strFilename = NULL; - + m_pISAXCallback->m_strFilename = nullptr; return hr; } @@ -917,7 +916,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) { HRESULT hr; - if( m_pISAXCallback == NULL ) + if( m_pISAXCallback == nullptr ) return E_NOINTERFACE; m_pISAXCallback->m_LineNum = 1; @@ -930,7 +929,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) m_pReadBuf[ 0 ] = '\0'; m_pReadBuf[ 1 ] = '\0'; - m_hFile = NULL; + m_hFile = nullptr; m_pInXMLBuffer = strBuffer; m_uInXMLBufferCharsLeft = uBufferSize; m_dwCharsTotal = uBufferSize; @@ -939,7 +938,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) hr = MainParseLoop(); // we no longer own strFilename, so un-set it - m_pISAXCallback->m_strFilename = NULL; + m_pISAXCallback->m_strFilename = nullptr; return hr; } diff --git a/Minecraft.Client/Durango/XML/ATGXmlParser.h b/Minecraft.Client/Durango/XML/ATGXmlParser.h index 75142e3e3..12f597372 100644 --- a/Minecraft.Client/Durango/XML/ATGXmlParser.h +++ b/Minecraft.Client/Durango/XML/ATGXmlParser.h @@ -138,7 +138,7 @@ private: DWORD m_dwCharsTotal; DWORD m_dwCharsConsumed; - BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing NULL + BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing nullptr WCHAR m_pWriteBuf[ XML_WRITE_BUFFER_SIZE ]; BYTE* m_pReadPtr; diff --git a/Minecraft.Client/Durango/XML/xmlFilesCallback.h b/Minecraft.Client/Durango/XML/xmlFilesCallback.h index deba843d6..161493404 100644 --- a/Minecraft.Client/Durango/XML/xmlFilesCallback.h +++ b/Minecraft.Client/Durango/XML/xmlFilesCallback.h @@ -47,7 +47,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - xuid=_wcstoui64(wTemp,NULL,10); + xuid=_wcstoui64(wTemp,nullptr,10); } } else if (_wcsicmp(wAttName,L"cape")==0) @@ -138,7 +138,7 @@ public: #ifdef _XBOX iValue=_wtoi(wValue); #else - iValue=wcstol(wValue, NULL, 10); + iValue=wcstol(wValue, nullptr, 10); #endif } } @@ -220,7 +220,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - uiSortIndex=wcstoul(wTemp,NULL,10); + uiSortIndex=wcstoul(wTemp,nullptr,10); } } else if (_wcsicmp(wAttName,L"Banner")==0) @@ -269,7 +269,7 @@ public: #ifdef _XBOX iConfig=_wtoi(wConfig); #else - iConfig=wcstol(wConfig, NULL, 10); + iConfig=wcstol(wConfig, nullptr, 10); #endif } } diff --git a/Minecraft.Client/DurangoMedia/4J_strings.h b/Minecraft.Client/DurangoMedia/4J_strings.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/Minecraft.Client/DurangoMedia/Layout/Contributors/015236CEB96771670B67A93104CDDD.filestate.xml b/Minecraft.Client/DurangoMedia/Layout/Contributors/015236CEB96771670B67A93104CDDD.filestate.xml deleted file mode 100644 index c74214041..000000000 --- a/Minecraft.Client/DurangoMedia/Layout/Contributors/015236CEB96771670B67A93104CDDD.filestate.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/AppxManifest.xml b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/AppxManifest.xml deleted file mode 100644 index ae7d93e52..000000000 --- a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/AppxManifest.xml +++ /dev/null @@ -1,113 +0,0 @@ - - - - - Minecraft: Xbox One Edition - Microsoft Studios - StoreLogo.png - Minecraft - - - 6.2 - 6.2 - title - era - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - windows.xbox.networking.realtimesession.dll - - - - - - Microsoft.Xbox.GameChat.dll - - - - - - Microsoft.Xbox.Services.dll - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.GameChat.dll b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.GameChat.dll deleted file mode 100644 index 3d83ce3f6..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.GameChat.dll and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.Services.dll b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.Services.dll deleted file mode 100644 index 853404c19..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Microsoft.Xbox.Services.dll and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Minecraft.Client.exe b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Minecraft.Client.exe deleted file mode 100644 index e505c5214..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/Minecraft.Client.exe and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SmallLogo.png b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SmallLogo.png deleted file mode 100644 index 00b540716..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SmallLogo.png and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SplashScreen.png b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SplashScreen.png deleted file mode 100644 index 948fdad77..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/SplashScreen.png and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/StoreLogo.png b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/StoreLogo.png deleted file mode 100644 index 679b33daa..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/StoreLogo.png and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/appdata.bin b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/appdata.bin deleted file mode 100644 index 42e51480a..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/appdata.bin and /dev/null differ diff --git a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/windows.xbox.networking.realtimesession.dll b/Minecraft.Client/DurangoMedia/Layout/Image/Loose/windows.xbox.networking.realtimesession.dll deleted file mode 100644 index 7ff53c86b..000000000 Binary files a/Minecraft.Client/DurangoMedia/Layout/Image/Loose/windows.xbox.networking.realtimesession.dll and /dev/null differ diff --git a/Minecraft.Client/EchantmentTableParticle.cpp b/Minecraft.Client/EchantmentTableParticle.cpp index 5af7ef365..95bd3dbc7 100644 --- a/Minecraft.Client/EchantmentTableParticle.cpp +++ b/Minecraft.Client/EchantmentTableParticle.cpp @@ -21,22 +21,22 @@ EchantmentTableParticle::EchantmentTableParticle(Level *level, double x, double oSize = size = random->nextFloat() * 0.5f + 0.2f; - lifetime = (int) (Math::random() * 10) + 30; + lifetime = static_cast(Math::random() * 10) + 30; noPhysics = true; - setMiscTex( (int) (Math::random() * 26 + 1 + 14 * 16) ); + setMiscTex( static_cast(Math::random() * 26 + 1 + 14 * 16) ); } int EchantmentTableParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age / (float) lifetime; + float pos = age / static_cast(lifetime); pos = pos * pos; pos = pos * pos; int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += static_cast(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } @@ -44,7 +44,7 @@ int EchantmentTableParticle::getLightColor(float a) float EchantmentTableParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age / (float) lifetime; + float pos = age / static_cast(lifetime); pos = pos * pos; pos = pos * pos; return br * (1 - pos) + pos; @@ -56,7 +56,7 @@ void EchantmentTableParticle::tick() yo = y; zo = z; - float pos = age / (float) lifetime; + float pos = age / static_cast(lifetime); pos = 1 - pos; diff --git a/Minecraft.Client/EnchantTableRenderer.cpp b/Minecraft.Client/EnchantTableRenderer.cpp index ff539fcd5..e188529b9 100644 --- a/Minecraft.Client/EnchantTableRenderer.cpp +++ b/Minecraft.Client/EnchantTableRenderer.cpp @@ -28,7 +28,7 @@ void EnchantTableRenderer::render(shared_ptr _table, double x, doubl #endif glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y + 12 / 16.0f, (float) z + 0.5f); + glTranslatef(static_cast(x) + 0.5f, static_cast(y) + 12 / 16.0f, static_cast(z) + 0.5f); float tt = table->time + a; diff --git a/Minecraft.Client/EnderChestRenderer.cpp b/Minecraft.Client/EnderChestRenderer.cpp index 52fdede94..71804a5a1 100644 --- a/Minecraft.Client/EnderChestRenderer.cpp +++ b/Minecraft.Client/EnderChestRenderer.cpp @@ -23,7 +23,7 @@ void EnderChestRenderer::render(shared_ptr _chest, double x, double glEnable(GL_RESCALE_NORMAL); //glColor4f(1, 1, 1, 1); if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); + glTranslatef(static_cast(x), static_cast(y) + 1, static_cast(z) + 1); glScalef(1, -1, -1); glTranslatef(0.5f, 0.5f, 0.5f); diff --git a/Minecraft.Client/EnderCrystalRenderer.cpp b/Minecraft.Client/EnderCrystalRenderer.cpp index d2eba5e83..2dde12467 100644 --- a/Minecraft.Client/EnderCrystalRenderer.cpp +++ b/Minecraft.Client/EnderCrystalRenderer.cpp @@ -25,7 +25,7 @@ void EnderCrystalRenderer::render(shared_ptr _crystal, double x, double float tt = crystal->time + a; glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); bindTexture(&ENDER_CRYSTAL_LOCATION); float hh = sin(tt * 0.2f) / 2 + 0.5f; hh = hh * hh + hh; diff --git a/Minecraft.Client/EnderDragonRenderer.cpp b/Minecraft.Client/EnderDragonRenderer.cpp index 4119e5b9f..8b5b248c2 100644 --- a/Minecraft.Client/EnderDragonRenderer.cpp +++ b/Minecraft.Client/EnderDragonRenderer.cpp @@ -13,7 +13,7 @@ ResourceLocation EnderDragonRenderer::DRAGON_LOCATION = ResourceLocation(TN_MOB_ EnderDragonRenderer::EnderDragonRenderer() : MobRenderer(new DragonModel(0), 0.5f) { - dragonModel = (DragonModel *) model; + dragonModel = static_cast(model); setArmor(model); // TODO: Make second constructor that assigns this. } @@ -90,15 +90,15 @@ void EnderDragonRenderer::render(shared_ptr _mob, double x, double y, do shared_ptr mob = dynamic_pointer_cast(_mob); BossMobGuiInfo::setBossHealth(mob, false); MobRenderer::render(mob, x, y, z, rot, a); - if (mob->nearestCrystal != NULL) + if (mob->nearestCrystal != nullptr) { float tt = mob->nearestCrystal->time + a; float hh = sin(tt * 0.2f) / 2 + 0.5f; hh = (hh * hh + hh) * 0.2f; - float xd = (float) (mob->nearestCrystal->x - mob->x - (mob->xo - mob->x) * (1 - a)); - float yd = (float) (hh + mob->nearestCrystal->y - 1 - mob->y - (mob->yo - mob->y) * (1 - a)); - float zd = (float) (mob->nearestCrystal->z - mob->z - (mob->zo - mob->z) * (1 - a)); + float xd = static_cast(mob->nearestCrystal->x - mob->x - (mob->xo - mob->x) * (1 - a)); + float yd = static_cast(hh + mob->nearestCrystal->y - 1 - mob->y - (mob->yo - mob->y) * (1 - a)); + float zd = static_cast(mob->nearestCrystal->z - mob->z - (mob->zo - mob->z) * (1 - a)); float sdd = sqrt(xd * xd + zd * zd); float dd = sqrt(xd * xd + yd * yd + zd * zd); @@ -107,7 +107,7 @@ void EnderDragonRenderer::render(shared_ptr _mob, double x, double y, do glColor4f(1, 1, 1, 1); glPushMatrix(); - glTranslatef((float) x, (float) y + 2, (float) z); + glTranslatef(static_cast(x), static_cast(y) + 2, static_cast(z)); glRotatef((float) (-atan2(zd, xd)) * 180.0f / PI - 90.0f, 0, 1, 0); glRotatef((float) (-atan2(sdd, yd)) * 180.0f / PI - 90.0f, 1, 0, 0); @@ -202,7 +202,7 @@ void EnderDragonRenderer::additionalRendering(shared_ptr _mob, flo t->begin(GL_TRIANGLE_FAN); float dist = random.nextFloat() * 20 + 5 + overDrive * 10; float w = random.nextFloat() * 2 + 1 + overDrive * 2; - t->color(0xffffff, (int) (255 * (1 - overDrive))); + t->color(0xffffff, static_cast(255 * (1 - overDrive))); t->vertex(0, 0, 0); t->color(0xff00ff, 0); t->vertex(-0.866 * w, dist, -0.5f * w); diff --git a/Minecraft.Client/EnderParticle.cpp b/Minecraft.Client/EnderParticle.cpp index 3889bf920..ee1a9c356 100644 --- a/Minecraft.Client/EnderParticle.cpp +++ b/Minecraft.Client/EnderParticle.cpp @@ -28,14 +28,14 @@ EnderParticle::EnderParticle(Level *level, double x, double y, double z, double oSize = size = random->nextFloat()*0.2f+0.5f; - lifetime = (int) (Math::random()*10) + 40; + lifetime = static_cast(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex(static_cast(Math::random() * 8)); } void EnderParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; + float s = (age + a) / static_cast(lifetime); s = 1-s; s = s*s; s = 1-s; @@ -48,13 +48,13 @@ int EnderParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); pos = pos*pos; pos = pos*pos; int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += static_cast(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } @@ -62,7 +62,7 @@ int EnderParticle::getLightColor(float a) float EnderParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); pos = pos*pos; pos = pos*pos; return br*(1-pos)+pos; @@ -74,7 +74,7 @@ void EnderParticle::tick() yo = y; zo = z; - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); float a = pos; pos = -pos+pos*pos*2; // pos = pos*pos; diff --git a/Minecraft.Client/EndermanRenderer.cpp b/Minecraft.Client/EndermanRenderer.cpp index f6e5220a4..fc2b8952d 100644 --- a/Minecraft.Client/EndermanRenderer.cpp +++ b/Minecraft.Client/EndermanRenderer.cpp @@ -10,7 +10,7 @@ ResourceLocation EndermanRenderer::ENDERMAN_LOCATION = ResourceLocation(TN_MOB_E EndermanRenderer::EndermanRenderer() : MobRenderer(new EndermanModel(), 0.5f) { - model = (EndermanModel *) MobRenderer::model; + model = static_cast(MobRenderer::model); this->setArmor(model); } diff --git a/Minecraft.Client/EntityRenderDispatcher.cpp b/Minecraft.Client/EntityRenderDispatcher.cpp index 57fdcc477..01972e568 100644 --- a/Minecraft.Client/EntityRenderDispatcher.cpp +++ b/Minecraft.Client/EntityRenderDispatcher.cpp @@ -87,7 +87,7 @@ double EntityRenderDispatcher::xOff = 0.0; double EntityRenderDispatcher::yOff = 0.0; double EntityRenderDispatcher::zOff = 0.0; -EntityRenderDispatcher *EntityRenderDispatcher::instance = NULL; +EntityRenderDispatcher *EntityRenderDispatcher::instance = nullptr; void EntityRenderDispatcher::staticCtor() { @@ -222,7 +222,7 @@ void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *fon int data = level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); int direction = data & 3; - playerRotY = (float)(direction * 90 + 180); + playerRotY = static_cast(direction * 90 + 180); playerRotX = 0; } } else { @@ -245,6 +245,11 @@ void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *fon void EntityRenderDispatcher::render(shared_ptr entity, float a) { + if (entity == nullptr) + { + return; + } + double x = entity->xOld + (entity->x - entity->xOld) * a; double y = entity->yOld + (entity->y - entity->yOld) * a; double z = entity->zOld + (entity->z - entity->zOld) * a; @@ -281,7 +286,7 @@ void EntityRenderDispatcher::render(shared_ptr entity, float a) void EntityRenderDispatcher::render(shared_ptr entity, double x, double y, double z, float rot, float a, bool bItemFrame, bool bRenderPlayerShadow) { EntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) + if (renderer != nullptr) { renderer->SetItemFrame(bItemFrame); diff --git a/Minecraft.Client/EntityRenderer.cpp b/Minecraft.Client/EntityRenderer.cpp index 9aa4ad7d9..fa41dfa60 100644 --- a/Minecraft.Client/EntityRenderer.cpp +++ b/Minecraft.Client/EntityRenderer.cpp @@ -18,7 +18,7 @@ ResourceLocation EntityRenderer::SHADOW_LOCATION = ResourceLocation(TN__CLAMP__M // 4J - added EntityRenderer::EntityRenderer() { - model = NULL; + model = nullptr; tileRenderer = new TileRenderer(); shadowRadius = 0; shadowStrength = 1.0f; @@ -89,7 +89,7 @@ void EntityRenderer::renderFlame(shared_ptr e, double x, double y, doubl Icon *fire2 = Tile::fire->getTextureLayer(1); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); float s = e->bbWidth * 1.4f; glScalef(s, s, s); @@ -102,18 +102,18 @@ void EntityRenderer::renderFlame(shared_ptr e, double x, double y, doubl float xo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = static_cast(e->y - e->bb->y0); glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); - glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); + glTranslatef(0, 0, -0.3f + static_cast(h) * 0.02f); glColor4f(1, 1, 1, 1); float zo = 0; int ss = 0; t->begin(); while (h > 0) { - Icon *tex = NULL; + Icon *tex = nullptr; if (ss % 2 == 0) { tex = fire1; @@ -238,7 +238,7 @@ void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, in if (a < 0) return; if (a > 1) a = 1; - t->color(1.0f, 1.0f, 1.0f, (float) a); + t->color(1.0f, 1.0f, 1.0f, static_cast(a)); // glColor4f(1, 1, 1, (float) a); double x0 = xt + tt->getShapeX0() + xo; @@ -247,20 +247,20 @@ void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, in double z0 = zt + tt->getShapeZ0() + zo; double z1 = zt + tt->getShapeZ1() + zo; - float u0 = (float) ((x - (x0)) / 2 / r + 0.5f); - float u1 = (float) ((x - (x1)) / 2 / r + 0.5f); - float v0 = (float) ((z - (z0)) / 2 / r + 0.5f); - float v1 = (float) ((z - (z1)) / 2 / r + 0.5f); + float u0 = static_cast((x - (x0)) / 2 / r + 0.5f); + float u1 = static_cast((x - (x1)) / 2 / r + 0.5f); + float v0 = static_cast((z - (z0)) / 2 / r + 0.5f); + float v1 = static_cast((z - (z1)) / 2 / r + 0.5f); // u0 = 0; // v0 = 0; // u1 = 1; // v1 = 1; - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV(static_cast(x0), static_cast(y0), static_cast(z0), (float)( u0), (float)( v0)); + t->vertexUV(static_cast(x0), static_cast(y0), static_cast(z1), (float)( u0), (float)( v1)); + t->vertexUV(static_cast(x1), static_cast(y0), static_cast(z1), (float)( u1), (float)( v1)); + t->vertexUV(static_cast(x1), static_cast(y0), static_cast(z0), (float)( u1), (float)( v0)); } void EntityRenderer::render(AABB *bb, double xo, double yo, double zo) @@ -269,42 +269,42 @@ void EntityRenderer::render(AABB *bb, double xo, double yo, double zo) Tesselator *t = Tesselator::getInstance(); glColor4f(1, 1, 1, 1); t->begin(); - t->offset((float)xo, (float)yo, (float)zo); + t->offset(static_cast(xo), static_cast(yo), static_cast(zo)); t->normal(0, 0, -1); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); t->normal(0, 0, 1); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); t->normal(0, -1, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); t->normal(0, 1, 0); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); t->normal(-1, 0, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); t->normal(1, 0, 0); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); t->offset(0, 0, 0); t->end(); glEnable(GL_TEXTURE_2D); @@ -315,30 +315,30 @@ void EntityRenderer::renderFlat(AABB *bb) { Tesselator *t = Tesselator::getInstance(); t->begin(); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x0), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x0), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z0)); + t->vertex(static_cast(bb->x1), static_cast(bb->y1), static_cast(bb->z1)); + t->vertex(static_cast(bb->x1), static_cast(bb->y0), static_cast(bb->z1)); t->end(); } @@ -385,7 +385,7 @@ void EntityRenderer::postRender(shared_ptr entity, double x, double y, d if (bRenderPlayerShadow && entityRenderDispatcher->options->fancyGraphics && shadowRadius > 0 && !entity->isInvisible()) { double dist = entityRenderDispatcher->distanceToSqr(entity->x, entity->y, entity->z); - float pow = (float) ((1 - dist / (16.0f * 16.0f)) * shadowStrength); + float pow = static_cast((1 - dist / (16.0f * 16.0f)) * shadowStrength); if (pow > 0) { renderShadow(entity, x, y, z, pow, a); @@ -406,5 +406,5 @@ void EntityRenderer::registerTerrainTextures(IconRegister *iconRegister) ResourceLocation *EntityRenderer::getTextureLocation(shared_ptr mob) { - return NULL; + return nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/EntityTileRenderer.cpp b/Minecraft.Client/EntityTileRenderer.cpp index deed369e8..6a84e3a3a 100644 --- a/Minecraft.Client/EntityTileRenderer.cpp +++ b/Minecraft.Client/EntityTileRenderer.cpp @@ -8,9 +8,9 @@ EntityTileRenderer *EntityTileRenderer::instance = new EntityTileRenderer; EntityTileRenderer::EntityTileRenderer() { - chest = shared_ptr(new ChestTileEntity()); - trappedChest = shared_ptr(new ChestTileEntity(ChestTile::TYPE_TRAP)); - enderChest = shared_ptr(new EnderChestTileEntity()); + chest = std::make_shared(); + trappedChest = std::make_shared(ChestTile::TYPE_TRAP); + enderChest = std::make_shared(); } void EntityTileRenderer::render(Tile *tile, int data, float brightness, float alpha, bool setColor, bool useCompiled) diff --git a/Minecraft.Client/EntityTracker.cpp b/Minecraft.Client/EntityTracker.cpp index db175542e..087227e77 100644 --- a/Minecraft.Client/EntityTracker.cpp +++ b/Minecraft.Client/EntityTracker.cpp @@ -59,7 +59,7 @@ void EntityTracker::addEntity(shared_ptr e) else if (e->instanceof(eTYPE_SQUID)) addEntity(e, 16 * 4, 1, true); else if (e->instanceof(eTYPE_WITHERBOSS)) addEntity(e, 16 * 5, 1, false); else if (e->instanceof(eTYPE_BAT)) addEntity(e, 16 * 5, 1, false); - else if (dynamic_pointer_cast(e)!=NULL) addEntity(e, 16 * 5, 1, true); + else if (dynamic_pointer_cast(e)!=nullptr) addEntity(e, 16 * 5, 1, true); else if (e->instanceof(eTYPE_ENDERDRAGON)) addEntity(e, 16 * 10, 1, true); else if (e->instanceof(eTYPE_PRIMEDTNT)) addEntity(e, 16 * 10, 10, true); else if (e->instanceof(eTYPE_FALLINGTILE)) addEntity(e, 16 * 10, 20, true); @@ -85,7 +85,7 @@ void EntityTracker::addEntity(shared_ptr e, int range, int updateInterva { __debugbreak(); } - shared_ptr te = shared_ptr( new TrackedEntity(e, range, updateInterval, trackDeltas) ); + shared_ptr te = std::make_shared(e, range, updateInterval, trackDeltas); entities.insert(te); entityMap[e->entityId] = te; te->updatePlayers(this, &level->players); @@ -145,9 +145,9 @@ void EntityTracker::tick() shared_ptr ep = server->getPlayers()->players[i]; if( ep->dimension != level->dimension->id ) continue; - if( ep->connection == NULL ) continue; + if( ep->connection == nullptr ) continue; INetworkPlayer *thisPlayer = ep->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) continue; + if( thisPlayer == nullptr ) continue; bool addPlayer = false; for (unsigned int j = 0; j < movedPlayers.size(); j++) @@ -156,9 +156,9 @@ void EntityTracker::tick() if( sp == ep ) break; - if(sp->connection == NULL) continue; + if(sp->connection == nullptr) continue; INetworkPlayer *otherPlayer = sp->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { addPlayer = true; break; @@ -170,7 +170,7 @@ void EntityTracker::tick() for (unsigned int i = 0; i < movedPlayers.size(); i++) { shared_ptr player = movedPlayers[i]; - if(player->connection == NULL) continue; + if(player->connection == nullptr) continue; for( auto& te : entities ) { if ( te && te->e != player) diff --git a/Minecraft.Client/ExperienceOrbRenderer.cpp b/Minecraft.Client/ExperienceOrbRenderer.cpp index c0eae7560..691efadec 100644 --- a/Minecraft.Client/ExperienceOrbRenderer.cpp +++ b/Minecraft.Client/ExperienceOrbRenderer.cpp @@ -20,7 +20,7 @@ void ExperienceOrbRenderer::render(shared_ptr _orb, double x, double y, { shared_ptr orb = dynamic_pointer_cast(_orb); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); int icon = orb->getIcon(); bindTexture(orb); // 4J was L"/item/xporb.png" @@ -50,9 +50,9 @@ void ExperienceOrbRenderer::render(shared_ptr _orb, double x, double y, } float br = 255.0f; float rr = (orb->tickCount + a) / 2; - int rc = (int) ((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); - int gc = (int) (br); - int bc = (int) ((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); + int rc = static_cast((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); + int gc = static_cast(br); + int bc = static_cast((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); int col = rc << 16 | gc << 8 | bc; glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); diff --git a/Minecraft.Client/ExplodeParticle.cpp b/Minecraft.Client/ExplodeParticle.cpp index fa950a03a..e9d4687bc 100644 --- a/Minecraft.Client/ExplodeParticle.cpp +++ b/Minecraft.Client/ExplodeParticle.cpp @@ -5,9 +5,9 @@ ExplodeParticle::ExplodeParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) { - xd = xa+(float)(Math::random()*2-1)*0.05f; - yd = ya+(float)(Math::random()*2-1)*0.05f; - zd = za+(float)(Math::random()*2-1)*0.05f; + xd = xa+static_cast(Math::random() * 2 - 1)*0.05f; + yd = ya+static_cast(Math::random() * 2 - 1)*0.05f; + zd = za+static_cast(Math::random() * 2 - 1)*0.05f; //rCol = gCol = bCol = random->nextFloat()*.3f+.7; @@ -21,16 +21,16 @@ ExplodeParticle::ExplodeParticle(Level *level, double x, double y, double z, dou size = random->nextFloat()*random->nextFloat()*6+1; - lifetime = (int)(16/(random->nextFloat()*0.8+0.2))+2; + lifetime = static_cast(16 / (random->nextFloat() * 0.8 + 0.2))+2; // noPhysics = true; } void ExplodeParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); float distSq = (x*x + y*y + z*z); if( distSq < (3.0f * 3.0f) ) return; diff --git a/Minecraft.Client/Extrax64Stubs.cpp b/Minecraft.Client/Extrax64Stubs.cpp index da9fe12eb..0147896ca 100644 --- a/Minecraft.Client/Extrax64Stubs.cpp +++ b/Minecraft.Client/Extrax64Stubs.cpp @@ -58,7 +58,7 @@ bool CSocialManager::IsTitleAllowedToPostImages() { return false; } bool CSocialManager::PostLinkToSocialNetwork(ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect) { return false; } bool CSocialManager::PostImageToSocialNetwork(ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect) { return false; } -CSocialManager* CSocialManager::Instance() { return NULL; } +CSocialManager* CSocialManager::Instance() { return nullptr; } void CSocialManager::SetSocialPostText(LPCWSTR Title, LPCWSTR Caption, LPCWSTR Desc) {}; DWORD XShowPartyUI(DWORD dwUserIndex) { return 0; } @@ -68,7 +68,7 @@ DWORD XContentGetThumbnail(DWORD dwUserIndex, const XCONTENT_DATA* pContentData, void XShowAchievementsUI(int i) {} DWORD XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE Mode) { return 0; } -#ifndef _DURANGO +#if !defined(_DURANGO) && !defined(_WIN64) void PIXAddNamedCounter(int a, const char* b, ...) {} //#define PS3_USE_PIX_EVENTS //#define PS4_USE_PIX_EVENTS @@ -126,7 +126,9 @@ void PIXEndNamedEvent() #endif } void PIXSetMarkerDeprecated(int a, const char* b, ...) {} -#else +#endif + +#if 0//__PSVITA__ // 4J Stu - Removed this implementation in favour of a macro that will convert our string format // conversion at compile time rather than at runtime //void PIXBeginNamedEvent(int a, char *b, ...) @@ -159,7 +161,7 @@ void PIXSetMarkerDeprecated(int a, const char* b, ...) {} //} #endif -// void *D3DXBUFFER::GetBufferPointer() { return NULL; } +// void *D3DXBUFFER::GetBufferPointer() { return nullptr; } // int D3DXBUFFER::GetBufferSize() { return 0; } // void D3DXBUFFER::Release() {} @@ -192,7 +194,16 @@ void IQNetPlayer::SendData(IQNetPlayer * player, const void* pvData, DWORD dwDat { if (WinsockNetLayer::IsActive()) { - WinsockNetLayer::SendToSmallId(player->m_smallId, pvData, dwDataSize); + if (!WinsockNetLayer::IsHosting() && !m_isRemote) + { + SOCKET sock = WinsockNetLayer::GetLocalSocket(m_smallId); + if (sock != INVALID_SOCKET) + WinsockNetLayer::SendOnSocket(sock, pvData, dwDataSize); + } + else + { + WinsockNetLayer::SendToSmallId(player->m_smallId, pvData, dwDataSize); + } } } bool IQNetPlayer::IsSameSystem(IQNetPlayer * player) { return (this == player) || (!m_isRemote && !player->m_isRemote); } @@ -243,7 +254,20 @@ void Win64_SetupRemoteQNetPlayer(IQNetPlayer * player, BYTE smallId, bool isHost static bool Win64_IsActivePlayer(IQNetPlayer* p, DWORD index); -HRESULT IQNet::AddLocalPlayerByUserIndex(DWORD dwUserIndex) { return S_OK; } +HRESULT IQNet::AddLocalPlayerByUserIndex(DWORD dwUserIndex) { + if (dwUserIndex >= MINECRAFT_NET_MAX_PLAYERS) return E_FAIL; + m_player[dwUserIndex].m_isRemote = false; + m_player[dwUserIndex].m_isHostPlayer = false; + // Give the joining player a distinct gamertag + extern wchar_t g_Win64UsernameW[17]; + if (dwUserIndex == 0) + wcscpy_s(m_player[0].m_gamertag, 32, g_Win64UsernameW); + else + swprintf_s(m_player[dwUserIndex].m_gamertag, 32, L"%s(%d)", g_Win64UsernameW, dwUserIndex + 1); + if (dwUserIndex >= s_playerCount) + s_playerCount = dwUserIndex + 1; + return S_OK; +} IQNetPlayer* IQNet::GetHostPlayer() { return &m_player[0]; } IQNetPlayer* IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) { @@ -253,16 +277,34 @@ IQNetPlayer* IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) !m_player[dwUserIndex].m_isRemote && Win64_IsActivePlayer(&m_player[dwUserIndex], dwUserIndex)) return &m_player[dwUserIndex]; - return NULL; + return nullptr; } - if (dwUserIndex != 0) - return NULL; - for (DWORD i = 0; i < s_playerCount; i++) + if (dwUserIndex == 0) { - if (!m_player[i].m_isRemote && Win64_IsActivePlayer(&m_player[i], i)) - return &m_player[i]; + // Primary pad: use direct index when networking is active (smallId may not be 0) + if (WinsockNetLayer::IsActive()) + { + DWORD idx = WinsockNetLayer::GetLocalSmallId(); + if (idx < MINECRAFT_NET_MAX_PLAYERS && + !m_player[idx].m_isRemote && + Win64_IsActivePlayer(&m_player[idx], idx)) + return &m_player[idx]; + return nullptr; + } + // Offline: scan for first local player + for (DWORD i = 0; i < s_playerCount; i++) + { + if (!m_player[i].m_isRemote && Win64_IsActivePlayer(&m_player[i], i)) + return &m_player[i]; + } + return nullptr; } - return NULL; + // Split-screen pads 1-3: the player is at m_player[dwUserIndex] with isRemote=false + if (dwUserIndex < MINECRAFT_NET_MAX_PLAYERS && + !m_player[dwUserIndex].m_isRemote && + Win64_IsActivePlayer(&m_player[dwUserIndex], dwUserIndex)) + return &m_player[dwUserIndex]; + return nullptr; } static bool Win64_IsActivePlayer(IQNetPlayer * p, DWORD index) { @@ -289,7 +331,7 @@ IQNetPlayer* IQNet::GetPlayerBySmallId(BYTE SmallId) { if (m_player[i].m_smallId == SmallId && Win64_IsActivePlayer(&m_player[i], i)) return &m_player[i]; } - return NULL; + return nullptr; } IQNetPlayer* IQNet::GetPlayerByXuid(PlayerUID xuid) { @@ -301,7 +343,7 @@ IQNetPlayer* IQNet::GetPlayerByXuid(PlayerUID xuid) if (m_player[i].GetXuid() == xuid) return &m_player[i]; } - // Keep existing stub behavior: return host slot instead of NULL on miss. + // Keep existing stub behavior: return host slot instead of nullptr on miss. return &m_player[0]; } DWORD IQNet::GetPlayerCount() @@ -330,7 +372,7 @@ void IQNet::ClientJoinGame() for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) { - m_player[i].m_smallId = (BYTE)i; + m_player[i].m_smallId = static_cast(i); m_player[i].m_isRemote = true; m_player[i].m_isHostPlayer = false; m_player[i].m_resolvedXuid = INVALID_XUID; @@ -345,7 +387,7 @@ void IQNet::EndGame() s_playerCount = 1; for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) { - m_player[i].m_smallId = (BYTE)i; + m_player[i].m_smallId = static_cast(i); m_player[i].m_isRemote = false; m_player[i].m_isHostPlayer = false; m_player[i].m_resolvedXuid = INVALID_XUID; @@ -453,11 +495,11 @@ HRESULT XMemCreateCompressionContext( ) { /* - COMPRESSOR_HANDLE Compressor = NULL; + COMPRESSOR_HANDLE Compressor = nullptr; HRESULT hr = CreateCompressor( COMPRESS_ALGORITHM_XPRESS_HUFF, // Compression Algorithm - NULL, // Optional allocation routine + nullptr, // Optional allocation routine &Compressor); // Handle pContext = (XMEMDECOMPRESSION_CONTEXT *)Compressor; @@ -474,11 +516,11 @@ HRESULT XMemCreateDecompressionContext( ) { /* - DECOMPRESSOR_HANDLE Decompressor = NULL; + DECOMPRESSOR_HANDLE Decompressor = nullptr; HRESULT hr = CreateDecompressor( COMPRESS_ALGORITHM_XPRESS_HUFF, // Compression Algorithm - NULL, // Optional allocation routine + nullptr, // Optional allocation routine &Decompressor); // Handle pContext = (XMEMDECOMPRESSION_CONTEXT *)Decompressor; @@ -528,7 +570,7 @@ void C_4JProfile::Initialise(DWORD dwTitleID, ZeroMemory(profileData[i], sizeof(byte) * iGameDefinedDataSizeX4 / 4); // Set some sane initial values! - GAME_SETTINGS* pGameSettings = (GAME_SETTINGS*)profileData[i]; + GAME_SETTINGS* pGameSettings = static_cast(profileData[i]); pGameSettings->ucMenuSensitivity = 100; //eGameSetting_Sensitivity_InMenu pGameSettings->ucInterfaceOpacity = 80; //eGameSetting_Sensitivity_InMenu pGameSettings->usBitmaskValues |= 0x0200; //eGameSetting_DisplaySplitscreenGamertags - on @@ -582,7 +624,7 @@ void C_4JProfile::SetTrialTextStringTable(CXuiStringTable * pStringTable, int void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle, int iText) {} int C_4JProfile::GetLockedProfile() { return 0; } void C_4JProfile::SetLockedProfile(int iProf) {} -bool C_4JProfile::IsSignedIn(int iQuadrant) { return (iQuadrant == 0); } +bool C_4JProfile::IsSignedIn(int iQuadrant) { return (iQuadrant == 0) || InputManager.IsPadConnected(iQuadrant); } bool C_4JProfile::IsSignedInLive(int iProf) { return true; } bool C_4JProfile::IsGuest(int iQuadrant) { return false; } UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame, bool bNoGuestsAllowed, bool bMultiplayerSignIn, bool bAddUser, int(*Func)(LPVOID, const bool, const int iPad), LPVOID lpParam, int iQuadrant) { return 0; } @@ -593,18 +635,10 @@ bool C_4JProfile::QuerySigninStatus(void) { return true; } void C_4JProfile::GetXUID(int iPad, PlayerUID * pXuid, bool bOnlineXuid) { #ifdef _WINDOWS64 - if (iPad != 0) - { - *pXuid = INVALID_XUID; - return; - } - // LoginPacket reads this value as client identity: - // - host keeps legacy host XUID for world compatibility - // - non-host uses persistent uid.dat-backed XUID - if (IQNet::s_isHosting) - *pXuid = Win64Xuid::GetLegacyEmbeddedHostXuid(); - else - *pXuid = Win64Xuid::ResolvePersistentXuid(); + // Each pad gets a unique XUID derived from the persistent uid.dat value. + // Pad 0 uses the base XUID directly. Pads 1-3 get a deterministic hash + // of (base + pad) to produce fully independent IDs with no overlap risk. + *pXuid = Win64Xuid::DeriveXuidForPad(Win64Xuid::ResolvePersistentXuid(), iPad); #else * pXuid = 0xe000d45248242f2e + iPad; #endif @@ -634,8 +668,24 @@ void C_4JProfile::SetPrimaryPad(int iPad) {} char fakeGamerTag[32] = "PlayerName"; void SetFakeGamertag(char* name) { strcpy_s(fakeGamerTag, name); } #else -char* C_4JProfile::GetGamertag(int iPad) { extern char g_Win64Username[17]; return g_Win64Username; } -wstring C_4JProfile::GetDisplayName(int iPad) { extern wchar_t g_Win64UsernameW[17]; return g_Win64UsernameW; } +char* C_4JProfile::GetGamertag(int iPad) { + extern char g_Win64Username[17]; + if (iPad > 0 && iPad < XUSER_MAX_COUNT && IQNet::m_player[iPad].m_gamertag[0] != 0 && + !IQNet::m_player[iPad].m_isRemote) + { + static char s_padGamertag[XUSER_MAX_COUNT][17]; + WideCharToMultiByte(CP_ACP, 0, IQNet::m_player[iPad].m_gamertag, -1, s_padGamertag[iPad], 17, nullptr, nullptr); + return s_padGamertag[iPad]; + } + return g_Win64Username; +} +wstring C_4JProfile::GetDisplayName(int iPad) { + extern wchar_t g_Win64UsernameW[17]; + if (iPad > 0 && iPad < XUSER_MAX_COUNT && IQNet::m_player[iPad].m_gamertag[0] != 0 && + !IQNet::m_player[iPad].m_isRemote) + return IQNet::m_player[iPad].m_gamertag; + return g_Win64UsernameW; +} #endif bool C_4JProfile::IsFullVersion() { return s_bProfileIsFullVersion; } void C_4JProfile::SetSignInChangeCallback(void (*Func)(LPVOID, bool, unsigned int), LPVOID lpParam) {} @@ -645,8 +695,8 @@ bool C_4JProfile::LocaleIsUSorCanada(void) { return false; } HRESULT C_4JProfile::GetLiveConnectionStatus() { return S_OK; } bool C_4JProfile::IsSystemUIDisplayed() { return false; } void C_4JProfile::SetProfileReadErrorCallback(void (*Func)(LPVOID), LPVOID lpParam) {} -int(*defaultOptionsCallback)(LPVOID, C_4JProfile::PROFILESETTINGS*, const int iPad) = NULL; -LPVOID lpProfileParam = NULL; +int(*defaultOptionsCallback)(LPVOID, C_4JProfile::PROFILESETTINGS*, const int iPad) = nullptr; +LPVOID lpProfileParam = nullptr; int C_4JProfile::SetDefaultOptionsCallback(int(*Func)(LPVOID, PROFILESETTINGS*, const int iPad), LPVOID lpParam) { defaultOptionsCallback = Func; @@ -724,7 +774,7 @@ void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA & xCont void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE * ppbImageData, DWORD * pdwImageBytes) {} C4JStorage::ESaveGameState C4JStorage::LoadSaveData(PSAVE_INFO pSaveInfo, int(*Func)(LPVOID lpParam, const bool, const bool), LPVOID lpParam) { return C4JStorage::ESaveGame_Idle; } C4JStorage::EDeleteGameStatus C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo, int(*Func)(LPVOID lpParam, const bool), LPVOID lpParam) { return C4JStorage::EDeleteGame_Idle; } -PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return NULL; } +PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return nullptr; } void C4JStorage::RegisterMarketplaceCountsCallback(int (*Func)(LPVOID lpParam, C4JStorage::DLC_TMS_DETAILS*, int), LPVOID lpParam) {} void C4JStorage::SetDLCPackageRoot(char* pszDLCRoot) {} @@ -746,7 +796,7 @@ void C4JStorage::StoreTMSPathName(WCHAR * pwchName) {} unsigned int C4JStorage::CRC(unsigned char* buf, int len) { return 0; } struct PTMSPP_FILEDATA; -C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad, C4JStorage::eGlobalStorage eStorageFacility, C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, int(*Func)(LPVOID, int, int, PTMSPP_FILEDATA, LPCSTR)/*=NULL*/, LPVOID lpParam/*=NULL*/, int iUserData/*=0*/) { return C4JStorage::ETMSStatus_Idle; } +C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad, C4JStorage::eGlobalStorage eStorageFacility, C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, int(*Func)(LPVOID, int, int, PTMSPP_FILEDATA, LPCSTR)/*=nullptr*/, LPVOID lpParam/*=nullptr*/, int iUserData/*=0*/) { return C4JStorage::ETMSStatus_Idle; } #endif // _WINDOWS64 #endif // __PS3__ diff --git a/Minecraft.Client/FallingTileRenderer.cpp b/Minecraft.Client/FallingTileRenderer.cpp index 2d9f5daea..132f033a5 100644 --- a/Minecraft.Client/FallingTileRenderer.cpp +++ b/Minecraft.Client/FallingTileRenderer.cpp @@ -22,7 +22,7 @@ void FallingTileRenderer::render(shared_ptr _tile, double x, double y, d if (level->getTile(floor(tile->x), floor(tile->y), floor(tile->z)) != tile->tile) { glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); bindTexture(tile); // 4J was L"/terrain.png" Tile *tt = Tile::tiles[tile->tile]; @@ -37,7 +37,7 @@ void FallingTileRenderer::render(shared_ptr _tile, double x, double y, d Tesselator *t = Tesselator::getInstance(); t->begin(); t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, -Mth::floor(tile->z) - 0.5f); - tileRenderer->tesselateAnvilInWorld((AnvilTile *) tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); + tileRenderer->tesselateAnvilInWorld(static_cast(tt), Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); t->offset(0, 0, 0); t->end(); } @@ -51,7 +51,7 @@ void FallingTileRenderer::render(shared_ptr _tile, double x, double y, d t->offset(0, 0, 0); t->end(); } - else if( tt != NULL ) + else if( tt != nullptr ) { tileRenderer->setShape(tt); tileRenderer->renderBlock(tt, level, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); diff --git a/Minecraft.Client/FileTexturePack.cpp b/Minecraft.Client/FileTexturePack.cpp index af58dc1e1..711f67362 100644 --- a/Minecraft.Client/FileTexturePack.cpp +++ b/Minecraft.Client/FileTexturePack.cpp @@ -36,7 +36,7 @@ InputStream *FileTexturePack::getResourceImplementation(const wstring &name) //t return zipFile.getInputStream(entry); #endif - return NULL; + return nullptr; } bool FileTexturePack::hasFile(const wstring &name) diff --git a/Minecraft.Client/FireballRenderer.cpp b/Minecraft.Client/FireballRenderer.cpp index 3b1ab924f..24e59ff48 100644 --- a/Minecraft.Client/FireballRenderer.cpp +++ b/Minecraft.Client/FireballRenderer.cpp @@ -20,7 +20,7 @@ void FireballRenderer::render(shared_ptr _fireball, double x, double y, glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glEnable(GL_RESCALE_NORMAL); float s = scale; glScalef(s / 1.0f, s / 1.0f, s / 1.0f); @@ -43,10 +43,10 @@ void FireballRenderer::render(shared_ptr _fireball, double x, double y, glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 0 - yo), static_cast(0), (float)( u0), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 0 - yo), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 1 - yo), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 1 - yo), static_cast(0), (float)( u0), (float)( v0)); t->end(); glDisable(GL_RESCALE_NORMAL); @@ -61,7 +61,7 @@ void FireballRenderer::renderFlame(shared_ptr e, double x, double y, dou Icon *tex = Tile::fire->getTextureLayer(0); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); float s = e->bbWidth * 1.4f; glScalef(s, s, s); @@ -75,7 +75,7 @@ void FireballRenderer::renderFlame(shared_ptr e, double x, double y, dou // float yo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = static_cast(e->y - e->bb->y0); //glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -99,10 +99,10 @@ void FireballRenderer::renderFlame(shared_ptr e, double x, double y, dou u1 = u0; u0 = tmp; - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1.4f - yo), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1.4f - yo), (float)( 0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 0 - yo), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 0 - yo), static_cast(0), (float)( u0), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 1.4f - yo), static_cast(0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 1.4f - yo), static_cast(0), (float)( u1), (float)( v0)); t->end(); glPopMatrix(); diff --git a/Minecraft.Client/FireworksParticles.cpp b/Minecraft.Client/FireworksParticles.cpp index fd19b0114..c17283ac4 100644 --- a/Minecraft.Client/FireworksParticles.cpp +++ b/Minecraft.Client/FireworksParticles.cpp @@ -15,12 +15,12 @@ FireworksParticles::FireworksStarter::FireworksStarter(Level *level, double x, d this->engine = engine; lifetime = 8; - if (infoTag != NULL) + if (infoTag != nullptr) { - explosions = (ListTag *)infoTag->getList(FireworksItem::TAG_EXPLOSIONS)->copy(); + explosions = static_cast *>(infoTag->getList(FireworksItem::TAG_EXPLOSIONS)->copy()); if (explosions->size() == 0) { - explosions = NULL; + explosions = nullptr; } else { @@ -42,7 +42,7 @@ FireworksParticles::FireworksStarter::FireworksStarter(Level *level, double x, d else { // 4J: - explosions = NULL; + explosions = nullptr; } } @@ -53,7 +53,7 @@ void FireworksParticles::FireworksStarter::render(Tesselator *t, float a, float void FireworksParticles::FireworksStarter::tick() { - if (life == 0 && explosions != NULL) + if (life == 0 && explosions != nullptr) { bool farEffect = isFarAwayFromCamera(); @@ -97,7 +97,7 @@ void FireworksParticles::FireworksStarter::tick() level->playLocalSound(x, y, z, soundId, 20, .95f + random->nextFloat() * .1f, true, 100.0f); } - if ((life % 2) == 0 && explosions != NULL && (life / 2) < explosions->size()) + if ((life % 2) == 0 && explosions != nullptr && (life / 2) < explosions->size()) { int eIndex = life / 2; CompoundTag *compoundTag = explosions->get(eIndex); @@ -186,10 +186,10 @@ void FireworksParticles::FireworksStarter::tick() } { int rgb = colors[0]; - float r = (float) ((rgb & 0xff0000) >> 16) / 255.0f; - float g = (float) ((rgb & 0x00ff00) >> 8) / 255.0f; - float b = (float) ((rgb & 0x0000ff) >> 0) / 255.0f; - shared_ptr fireworksOverlayParticle = shared_ptr(new FireworksParticles::FireworksOverlayParticle(level, x, y, z)); + float r = static_cast((rgb & 0xff0000) >> 16) / 255.0f; + float g = static_cast((rgb & 0x00ff00) >> 8) / 255.0f; + float b = static_cast((rgb & 0x0000ff) >> 0) / 255.0f; + shared_ptr fireworksOverlayParticle = std::make_shared(level, x, y, z); fireworksOverlayParticle->setColor(r, g, b); fireworksOverlayParticle->setAlpha(0.99f); // 4J added engine->add(fireworksOverlayParticle); @@ -212,7 +212,7 @@ void FireworksParticles::FireworksStarter::tick() bool FireworksParticles::FireworksStarter::isFarAwayFromCamera() { Minecraft *instance = Minecraft::GetInstance(); - if (instance != NULL && instance->cameraTargetPlayer != NULL) + if (instance != nullptr && instance->cameraTargetPlayer != nullptr) { if (instance->cameraTargetPlayer->distanceToSqr(x, y, z) < 16 * 16) { @@ -224,14 +224,14 @@ bool FireworksParticles::FireworksStarter::isFarAwayFromCamera() void FireworksParticles::FireworksStarter::createParticle(double x, double y, double z, double xa, double ya, double za, intArray rgbColors, intArray fadeColors, bool trail, bool flicker) { - shared_ptr fireworksSparkParticle = shared_ptr(new FireworksSparkParticle(level, x, y, z, xa, ya, za, engine)); + shared_ptr fireworksSparkParticle = std::make_shared(level, x, y, z, xa, ya, za, engine); fireworksSparkParticle->setAlpha(0.99f); fireworksSparkParticle->setTrail(trail); fireworksSparkParticle->setFlicker(flicker); int color = random->nextInt(rgbColors.length); fireworksSparkParticle->setColor(rgbColors[color]); - if (/*fadeColors != NULL &&*/ fadeColors.length > 0) + if (/*fadeColors != nullptr &&*/ fadeColors.length > 0) { fireworksSparkParticle->setFadeColor(fadeColors[random->nextInt(fadeColors.length)]); } @@ -365,24 +365,24 @@ void FireworksParticles::FireworksSparkParticle::setFlicker(bool flicker) void FireworksParticles::FireworksSparkParticle::setColor(int rgb) { - float r = (float) ((rgb & 0xff0000) >> 16) / 255.0f; - float g = (float) ((rgb & 0x00ff00) >> 8) / 255.0f; - float b = (float) ((rgb & 0x0000ff) >> 0) / 255.0f; + float r = static_cast((rgb & 0xff0000) >> 16) / 255.0f; + float g = static_cast((rgb & 0x00ff00) >> 8) / 255.0f; + float b = static_cast((rgb & 0x0000ff) >> 0) / 255.0f; float scale = 1.0f; Particle::setColor(r * scale, g * scale, b * scale); } void FireworksParticles::FireworksSparkParticle::setFadeColor(int rgb) { - fadeR = (float) ((rgb & 0xff0000) >> 16) / 255.0f; - fadeG = (float) ((rgb & 0x00ff00) >> 8) / 255.0f; - fadeB = (float) ((rgb & 0x0000ff) >> 0) / 255.0f; + fadeR = static_cast((rgb & 0xff0000) >> 16) / 255.0f; + fadeG = static_cast((rgb & 0x00ff00) >> 8) / 255.0f; + fadeB = static_cast((rgb & 0x0000ff) >> 0) / 255.0f; hasFade = true; } AABB *FireworksParticles::FireworksSparkParticle::getCollideBox() { - return NULL; + return nullptr; } bool FireworksParticles::FireworksSparkParticle::isPushable() @@ -407,7 +407,7 @@ void FireworksParticles::FireworksSparkParticle::tick() if (age++ >= lifetime) remove(); if (age > lifetime / 2) { - setAlpha(1.0f - (((float) age - lifetime / 2) / (float) lifetime)); + setAlpha(1.0f - ((static_cast(age) - lifetime / 2) / static_cast(lifetime))); if (hasFade) { @@ -433,7 +433,7 @@ void FireworksParticles::FireworksSparkParticle::tick() if (trail && (age < lifetime / 2) && ((age + lifetime) % 2) == 0) { - shared_ptr fireworksSparkParticle = shared_ptr(new FireworksParticles::FireworksSparkParticle(level, x, y, z, 0, 0, 0, engine)); + shared_ptr fireworksSparkParticle = std::make_shared(level, x, y, z, 0, 0, 0, engine); fireworksSparkParticle->setAlpha(0.99f); fireworksSparkParticle->setColor(rCol, gCol, bCol); fireworksSparkParticle->age = fireworksSparkParticle->lifetime / 2; @@ -475,12 +475,12 @@ void FireworksParticles::FireworksOverlayParticle::render(Tesselator *t, float a float u1 = u0 + 32.0f / 128.0f; float v0 = 16.0f / 128.0f; float v1 = v0 + 32.0f / 128.0f; - float r = 7.1f * sin(((float) age + a - 1.0f) * .25f * PI); - alpha = 0.6f - ((float) age + a - 1.0f) * .25f * .5f; + float r = 7.1f * sin((static_cast(age) + a - 1.0f) * .25f * PI); + alpha = 0.6f - (static_cast(age) + a - 1.0f) * .25f * .5f; - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); t->color(rCol, gCol, bCol, alpha); diff --git a/Minecraft.Client/FishingHookRenderer.cpp b/Minecraft.Client/FishingHookRenderer.cpp index 9d60a9ace..d587ddb87 100644 --- a/Minecraft.Client/FishingHookRenderer.cpp +++ b/Minecraft.Client/FishingHookRenderer.cpp @@ -17,7 +17,7 @@ void FishingHookRenderer::render(shared_ptr _hook, double x, double y, d glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); int xi = 1; @@ -39,17 +39,17 @@ void FishingHookRenderer::render(shared_ptr _hook, double x, double y, d glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 0 - yo), static_cast(0), (float)( u0), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 0 - yo), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 1 - yo), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 1 - yo), static_cast(0), (float)( u0), (float)( v0)); t->end(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); - if (hook->owner != NULL) + if (hook->owner != nullptr) { float swing = hook->owner->getAttackAnim(a); float swing2 = (float) Mth::sin(sqrt(swing) * PI); @@ -82,9 +82,9 @@ void FishingHookRenderer::render(shared_ptr _hook, double x, double y, d double yh = hook->yo + (hook->y - hook->yo) * a + 4 / 16.0f; double zh = hook->zo + (hook->z - hook->zo) * a; - double xa = (float) (xp - xh); - double ya = (float) (yp - yh); - double za = (float) (zp - zh); + double xa = static_cast(xp - xh); + double ya = static_cast(yp - yh); + double za = static_cast(zp - zh); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); @@ -93,8 +93,8 @@ void FishingHookRenderer::render(shared_ptr _hook, double x, double y, d int steps = 16; for (int i = 0; i <= steps; i++) { - float aa = i / (float) steps; - t->vertex((float)(x + xa * aa), (float)( y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), (float)( z + za * aa)); + float aa = i / static_cast(steps); + t->vertex(static_cast(x + xa * aa), static_cast(y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), static_cast(z + za * aa)); } t->end(); glEnable(GL_LIGHTING); diff --git a/Minecraft.Client/FlameParticle.cpp b/Minecraft.Client/FlameParticle.cpp index eb12dbfda..a242f7147 100644 --- a/Minecraft.Client/FlameParticle.cpp +++ b/Minecraft.Client/FlameParticle.cpp @@ -15,14 +15,14 @@ FlameParticle::FlameParticle(Level *level, double x, double y, double z, double oSize = size; rCol = gCol = bCol = 1.0f; - lifetime = (int)(8/(Math::random()*0.8+0.2))+4; + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2))+4; noPhysics = true; setMiscTex(48); } void FlameParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; + float s = (age + a) / static_cast(lifetime); size = oSize * (1 - s*s*0.5f); Particle::render(t, a, xa, ya, za, xa2, za2); } @@ -37,7 +37,7 @@ int FlameParticle::getLightColor(float a) int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br1 += (int) (l * 15 * 16); + br1 += static_cast(l * 15 * 16); if (br1 > 15 * 16) br1 = 15 * 16; return br1 | br2 << 16; } diff --git a/Minecraft.Client/FolderTexturePack.cpp b/Minecraft.Client/FolderTexturePack.cpp index 4b65dc7f0..05feca664 100644 --- a/Minecraft.Client/FolderTexturePack.cpp +++ b/Minecraft.Client/FolderTexturePack.cpp @@ -31,7 +31,7 @@ InputStream *FolderTexturePack::getResourceImplementation(const wstring &name) / #endif InputStream *resource = InputStream::getResourceAsStream(wDrive + name); //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) + //if (stream == nullptr) //{ // throw new FileNotFoundException(name); //} @@ -85,7 +85,7 @@ void FolderTexturePack::loadUI() swprintf(szResourceLocator, LOCATOR_SIZE,L"file://%lsTexturePack.xzp#skin_Minecraft.xur",getPath().c_str()); XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); + app.LoadSkin(szResourceLocator,nullptr);//L"TexturePack"); bUILoaded = true; //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); } diff --git a/Minecraft.Client/FolderTexturePack.h b/Minecraft.Client/FolderTexturePack.h index 409210780..4327698d5 100644 --- a/Minecraft.Client/FolderTexturePack.h +++ b/Minecraft.Client/FolderTexturePack.h @@ -20,7 +20,7 @@ public: bool isTerrainUpdateCompatible(); // 4J Added - virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=NULL); + virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=nullptr); virtual void loadUI(); virtual void unloadUI(); }; \ No newline at end of file diff --git a/Minecraft.Client/Font.cpp b/Minecraft.Client/Font.cpp index ce2275f69..db2a18c04 100644 --- a/Minecraft.Client/Font.cpp +++ b/Minecraft.Client/Font.cpp @@ -34,7 +34,7 @@ Font::Font(Options *options, const wstring& name, Textures* textures, bool enfor m_textureLocation = textureLocation; // Build character map - if (charMap != NULL) + if (charMap != nullptr) { for(int i = 0; i < charC; i++) { @@ -149,7 +149,7 @@ void Font::renderStyleLine(float x0, float y0, float x1, float y1) void Font::addCharacterQuad(wchar_t c) { float xOff = c % m_cols * m_charWidth; - float yOff = c / m_cols * m_charWidth; + float yOff = c / m_cols * m_charHeight; // was m_charWidth — wrong when glyphs aren't square float width = charWidths[c] - .01f; float height = m_charHeight - .01f; float fontWidth = m_cols * m_charWidth; @@ -187,7 +187,7 @@ void Font::addCharacterQuad(wchar_t c) void Font::renderCharacter(wchar_t c) { float xOff = c % m_cols * m_charWidth; - float yOff = c / m_cols * m_charWidth; + float yOff = c / m_cols * m_charHeight; // was m_charWidth — wrong when glyphs aren't square float width = charWidths[c] - .01f; float height = m_charHeight - .01f; @@ -383,7 +383,7 @@ int Font::width(const wstring& str) { wstring cleanStr = sanitize(str); - if (cleanStr == L"") return 0; // 4J - was NULL comparison + if (cleanStr == L"") return 0; // 4J - was nullptr comparison int len = 0; for (int i = 0; i < cleanStr.length(); ++i) @@ -602,7 +602,7 @@ bool Font::AllCharactersValid(const wstring &str) continue; } - int index = SharedConstants::acceptableLetters.find(c); + size_t index = SharedConstants::acceptableLetters.find(c); if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) { diff --git a/Minecraft.Client/Font.h b/Minecraft.Client/Font.h index a5d117ca0..c78ea6785 100644 --- a/Minecraft.Client/Font.h +++ b/Minecraft.Client/Font.h @@ -38,7 +38,7 @@ private: std::map m_charMap; public: - Font(Options *options, const wstring& name, Textures* textures, bool enforceUnicode, ResourceLocation *textureLocation, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[] = NULL); + Font(Options *options, const wstring& name, Textures* textures, bool enforceUnicode, ResourceLocation *textureLocation, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[] = nullptr); #ifndef _XBOX // 4J Stu - This dtor clashes with one in xui! We never delete these anyway so take it out for now. Can go back when we have got rid of XUI ~Font(); diff --git a/Minecraft.Client/FootstepParticle.cpp b/Minecraft.Client/FootstepParticle.cpp index 300575eb1..b2bfc9893 100644 --- a/Minecraft.Client/FootstepParticle.cpp +++ b/Minecraft.Client/FootstepParticle.cpp @@ -31,9 +31,9 @@ void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float glDisable(GL_LIGHTING); float r = 2 / 16.0f; - float xx = (float) (x - xOff); - float yy = (float) (y - yOff); - float zz = (float) (z - zOff); + float xx = static_cast(x - xOff); + float yy = static_cast(y - yOff); + float zz = static_cast(z - zOff); float br = level->getBrightness(Mth::floor(x), Mth::floor(y), Mth::floor(z)); @@ -43,10 +43,10 @@ void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float t->begin(); t->color(br, br, br, alpha); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz + r), (float)( 0), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz + r), (float)( 1), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz - r), (float)( 1), (float)( 0)); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz - r), (float)( 0), (float)( 0)); + t->vertexUV((float)(xx - r), (float)( yy), (float)( zz + r), static_cast(0), static_cast(1)); + t->vertexUV((float)(xx + r), (float)( yy), (float)( zz + r), static_cast(1), static_cast(1)); + t->vertexUV((float)(xx + r), (float)( yy), (float)( zz - r), static_cast(1), static_cast(0)); + t->vertexUV((float)(xx - r), (float)( yy), (float)( zz - r), static_cast(0), static_cast(0)); t->end(); glDisable(GL_BLEND); diff --git a/Minecraft.Client/GameRenderer.cpp b/Minecraft.Client/GameRenderer.cpp index be3892116..8c9dd5916 100644 --- a/Minecraft.Client/GameRenderer.cpp +++ b/Minecraft.Client/GameRenderer.cpp @@ -74,7 +74,7 @@ ResourceLocation GameRenderer::SNOW_LOCATION = ResourceLocation(TN_ENVIRONMENT_S GameRenderer::GameRenderer(Minecraft *mc) { // 4J - added this block of initialisers - renderDistance = (float)(16 * 16 >> mc->options->viewDistance); + renderDistance = static_cast(16 * 16 >> mc->options->viewDistance); _tick = 0; hovered = nullptr; thirdDistance = 4; @@ -106,8 +106,8 @@ GameRenderer::GameRenderer(Minecraft *mc) zoom = 1; zoom_x = 0; zoom_y = 0; - rainXa = NULL; - rainZa = NULL; + rainXa = nullptr; + rainZa = nullptr; lastActiveTime = Minecraft::currentTimeMillis(); lastNsTime = 0; random = new Random(); @@ -139,7 +139,7 @@ GameRenderer::GameRenderer(Minecraft *mc) } this->mc = mc; - itemInHandRenderer = NULL; + itemInHandRenderer = nullptr; // 4J-PB - set up the local players iteminhand renderers here - needs to be done with lighting enabled so that the render geometry gets compiled correctly glEnable(GL_LIGHTING); @@ -170,7 +170,7 @@ GameRenderer::GameRenderer(Minecraft *mc) m_updateEvents->Set(eUpdateEventIsFinished); InitializeCriticalSection(&m_csDeleteStack); - m_updateThread = new C4JThread(runUpdate, NULL, "Chunk update"); + m_updateThread = new C4JThread(runUpdate, nullptr, "Chunk update"); #ifdef __PS3__ m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); #endif// __PS3__ @@ -182,8 +182,8 @@ GameRenderer::GameRenderer(Minecraft *mc) // 4J Stu Added to go with 1.8.2 change GameRenderer::~GameRenderer() { - if(rainXa != NULL) delete [] rainXa; - if(rainZa != NULL) delete [] rainZa; + if(rainXa != nullptr) delete [] rainXa; + if(rainZa != nullptr) delete [] rainZa; } void GameRenderer::tick(bool first) // 4J - add bFirst @@ -211,7 +211,7 @@ void GameRenderer::tick(bool first) // 4J - add bFirst accumulatedSmoothYO = 0; } - if (mc->cameraTargetPlayer == NULL) + if (mc->cameraTargetPlayer == nullptr) { mc->cameraTargetPlayer = dynamic_pointer_cast(mc->player); } @@ -230,7 +230,7 @@ void GameRenderer::tick(bool first) // 4J - add bFirst darkenWorldAmountO = darkenWorldAmount; if (BossMobGuiInfo::darkenWorld) { - darkenWorldAmount += 1.0f / ((float) SharedConstants::TICKS_PER_SECOND * 1); + darkenWorldAmount += 1.0f / (static_cast(SharedConstants::TICKS_PER_SECOND) * 1); if (darkenWorldAmount > 1) { darkenWorldAmount = 1; @@ -239,7 +239,7 @@ void GameRenderer::tick(bool first) // 4J - add bFirst } else if (darkenWorldAmount > 0) { - darkenWorldAmount -= 1.0f / ((float) SharedConstants::TICKS_PER_SECOND * 4); + darkenWorldAmount -= 1.0f / (static_cast(SharedConstants::TICKS_PER_SECOND) * 4); } if( mc->player != mc->localplayers[ProfileManager.GetPrimaryPad()] ) return; // 4J added for split screen - only do rest of processing for once per frame @@ -249,8 +249,8 @@ void GameRenderer::tick(bool first) // 4J - add bFirst void GameRenderer::pick(float a) { - if (mc->cameraTargetPlayer == NULL) return; - if (mc->level == NULL) return; + if (mc->cameraTargetPlayer == nullptr) return; + if (mc->level == nullptr) return; mc->crosshairPickMob = nullptr; @@ -280,7 +280,7 @@ void GameRenderer::pick(float a) ( hitz < minxz ) || ( hitz > maxxz) ) { delete mc->hitResult; - mc->hitResult = NULL; + mc->hitResult = nullptr; } } @@ -297,7 +297,7 @@ void GameRenderer::pick(float a) range = dist; } - if (mc->hitResult != NULL) + if (mc->hitResult != nullptr) { dist = mc->hitResult->pos->distanceTo(from); } @@ -327,13 +327,14 @@ void GameRenderer::pick(float a) else if (p != nullptr) { double dd = from->distanceTo(p->pos); - if (e == mc->cameraTargetPlayer->riding != NULL) - { - if (nearest == 0) - { - hovered = e; - } - } + auto const riding = mc->cameraTargetPlayer->riding; + if (riding != nullptr && e == riding) + { + if (nearest == 0) + { + hovered = e; + } + } else { hovered = e; @@ -343,11 +344,11 @@ void GameRenderer::pick(float a) delete p; } - if (hovered != NULL) + if (hovered != nullptr) { - if (nearest < dist || (mc->hitResult == NULL)) + if (nearest < dist || (mc->hitResult == nullptr)) { - if( mc->hitResult != NULL ) + if( mc->hitResult != nullptr ) delete mc->hitResult; mc->hitResult = new HitResult(hovered); if (hovered->instanceof(eTYPE_LIVINGENTITY)) @@ -391,7 +392,7 @@ float GameRenderer::getFov(float a, bool applyEffects) float fov = m_fov;//70; if (applyEffects) { - fov += mc->options->fov * 40; + //fov += mc->options->fov * 40; fov *= oFov[playerIdx] + (this->fov[playerIdx] - oFov[playerIdx]) * a; } if (player->getHealth() <= 0) @@ -475,7 +476,7 @@ void GameRenderer::moveCameraToPlayer(float a) int data = mc->level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); int direction = data & 3; - glRotatef((float)direction * 90,0.0f, 1.0f, 0.0f); + glRotatef(static_cast(direction) * 90,0.0f, 1.0f, 0.0f); } glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, -1, 0); glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, -1, 0, 0); @@ -493,7 +494,7 @@ void GameRenderer::moveCameraToPlayer(float a) float rotationY = thirdRotationO + (thirdRotation - thirdRotationO) * a; float xRot = thirdTiltO + (thirdTilt - thirdTiltO) * a; - glTranslatef(0, 0, (float) -cameraDist); + glTranslatef(0, 0, static_cast(-cameraDist)); glRotatef(xRot, 1, 0, 0); glRotatef(rotationY, 0, 1, 0); } @@ -522,9 +523,9 @@ void GameRenderer::moveCameraToPlayer(float a) for (int i = 0; i < 8; i++) { - float xo = (float)((i & 1) * 2 - 1); - float yo = (float)(((i >> 1) & 1) * 2 - 1); - float zo = (float)(((i >> 2) & 1) * 2 - 1); + float xo = static_cast((i & 1) * 2 - 1); + float yo = static_cast(((i >> 1) & 1) * 2 - 1); + float zo = static_cast(((i >> 2) & 1) * 2 - 1); xo *= 0.1f; yo *= 0.1f; @@ -532,7 +533,7 @@ void GameRenderer::moveCameraToPlayer(float a) // 4J - corrected bug here where zo was also added to x component HitResult *hr = mc->level->clip(Vec3::newTemp(x + xo, y + yo, z + zo), Vec3::newTemp(x - xd + xo, y - yd + yo, z - zd + zo)); - if (hr != NULL) + if (hr != nullptr) { double dist = hr->pos->distanceTo(Vec3::newTemp(x, y, z)); if (dist < cameraDist) cameraDist = dist; @@ -540,7 +541,7 @@ void GameRenderer::moveCameraToPlayer(float a) } } - glTranslatef(0, 0, (float) -cameraDist); + glTranslatef(0, 0, static_cast(-cameraDist)); } } else @@ -593,9 +594,10 @@ void GameRenderer::unZoomRegion() // 4J added as we have more complex adjustments to make for fov & aspect on account of viewports 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. - aspect = mc->width / (float) mc->height; + // Use the real window dimensions so the perspective updates on resize. + extern int g_rScreenWidth; + extern int g_rScreenHeight; + aspect = g_rScreenWidth / static_cast(g_rScreenHeight); fov = getFov(a, applyEffects); if( ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP ) || @@ -616,11 +618,11 @@ void GameRenderer::setupCamera(float a, int eye) { if (mc->options->viewDistance >= 0) { - renderDistance = (float)(16 * 16 >> mc->options->viewDistance); + renderDistance = static_cast(16 * 16 >> mc->options->viewDistance); } else { - renderDistance = (float)((16 * 16) << (-mc->options->viewDistance)); + renderDistance = static_cast((16 * 16) << (-mc->options->viewDistance)); } glMatrixMode(GL_PROJECTION); @@ -635,7 +637,7 @@ void GameRenderer::setupCamera(float a, int eye) if (zoom != 1) { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); + glTranslatef(static_cast(zoom_x), static_cast(-zoom_y), 0); glScaled(zoom, zoom, 1); } gluPerspective(fov, aspect, 0.05f, renderDistance * 2); @@ -700,7 +702,7 @@ void GameRenderer::renderItemInHand(float a, int eye) bool renderHand = true; // 4J-PB - to turn off the hand for screenshots, but not when the item held is a map - if ( localplayer!=NULL) + if ( localplayer!=nullptr) { shared_ptr item = localplayer->inventory->getSelected(); if(!(item && item->getItem()->id==Item::map_Id) && app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_DisplayHand)==0 ) renderHand = false; @@ -718,7 +720,7 @@ void GameRenderer::renderItemInHand(float a, int eye) if (zoom != 1) { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); + glTranslatef(static_cast(zoom_x), static_cast(-zoom_y), 0); glScaled(zoom, zoom, 1); } gluPerspective(fov, aspect, 0.05f, renderDistance * 2); @@ -830,8 +832,8 @@ void GameRenderer::turnOnLightLayer(double alpha) // 4J - change brought forward from 1.8.2 void GameRenderer::tickLightTexture() { - blrt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); - blgt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); + blrt += static_cast((Math::random() - Math::random()) * Math::random() * Math::random()); + blgt += static_cast((Math::random() - Math::random()) * Math::random() * Math::random()); blrt *= 0.9; blgt *= 0.9; blr += (blrt - blr) * 1; @@ -952,87 +954,70 @@ float GameRenderer::ComputeGammaFromSlider(float slider0to100) void GameRenderer::CachePlayerGammas() { - for (int j = 0; j < XUSER_MAX_COUNT && j < NUM_LIGHT_TEXTURES; ++j) - { - std::shared_ptr player = Minecraft::GetInstance()->localplayers[j]; - if (!player) - { - m_cachedGammaPerPlayer[j] = 1.0f; - continue; - } + const float slider = app.GetGameSettings(ProfileManager.GetPrimaryPad(), eGameSetting_Gamma); + const float gamma = ComputeGammaFromSlider(slider); - const float slider = app.GetGameSettings(j, eGameSetting_Gamma); // 0..100 - m_cachedGammaPerPlayer[j] = ComputeGammaFromSlider(slider); - } + for (int j = 0; j < XUSER_MAX_COUNT && j < NUM_LIGHT_TEXTURES; ++j) + m_cachedGammaPerPlayer[j] = gamma; } bool GameRenderer::ComputeViewportForPlayer(int j, D3D11_VIEWPORT &outViewport) const { - int active = 0; - int indexMap[NUM_LIGHT_TEXTURES] = {-1, -1, -1, -1}; - for (int i = 0; i < XUSER_MAX_COUNT && i < NUM_LIGHT_TEXTURES; ++i) - { - if (Minecraft::GetInstance()->localplayers[i]) - indexMap[active++] = i; - } + extern int g_rScreenWidth; + extern int g_rScreenHeight; - if (active <= 1) - { - outViewport.TopLeftX = 0.0f; - outViewport.TopLeftY = 0.0f; - outViewport.Width = static_cast(mc->width); - outViewport.Height = static_cast(mc->height); - outViewport.MinDepth = 0.0f; - outViewport.MaxDepth = 1.0f; - return true; - } - - int k = -1; - for (int ord = 0; ord < active; ++ord) - if (indexMap[ord] == j) - { - k = ord; - break; - } - if (k < 0) + std::shared_ptr player = Minecraft::GetInstance()->localplayers[j]; + if (!player) return false; - const float width = static_cast(mc->width); - const float height = static_cast(mc->height); + const float w = static_cast(g_rScreenWidth); + const float h = static_cast(g_rScreenHeight); + const float halfW = w * 0.5f; + const float halfH = h * 0.5f; - if (active == 2) + outViewport.MinDepth = 0.0f; + outViewport.MaxDepth = 1.0f; + + switch (static_cast(player->m_iScreenSection)) { - const float halfH = height * 0.5f; - outViewport.TopLeftX = 0.0f; - outViewport.Width = width; - outViewport.MinDepth = 0.0f; - outViewport.MaxDepth = 1.0f; - if (k == 0) - { - outViewport.TopLeftY = 0.0f; - outViewport.Height = halfH; - } - else - { - outViewport.TopLeftY = halfH; - outViewport.Height = halfH; - } - return true; - } - else - { - const float halfW = width * 0.5f; - const float halfH = height * 0.5f; - const int row = (k >= 2) ? 1 : 0; - const int col = (k % 2); - outViewport.TopLeftX = col ? halfW : 0.0f; - outViewport.TopLeftY = row ? halfH : 0.0f; - outViewport.Width = halfW; - outViewport.Height = halfH; - outViewport.MinDepth = 0.0f; - outViewport.MaxDepth = 1.0f; - return true; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + outViewport.TopLeftX = 0; outViewport.TopLeftY = 0; + outViewport.Width = w; outViewport.Height = halfH; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + outViewport.TopLeftX = 0; outViewport.TopLeftY = halfH; + outViewport.Width = w; outViewport.Height = halfH; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + outViewport.TopLeftX = 0; outViewport.TopLeftY = 0; + outViewport.Width = halfW; outViewport.Height = h; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + outViewport.TopLeftX = halfW; outViewport.TopLeftY = 0; + outViewport.Width = halfW; outViewport.Height = h; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + outViewport.TopLeftX = 0; outViewport.TopLeftY = 0; + outViewport.Width = halfW; outViewport.Height = halfH; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + outViewport.TopLeftX = halfW; outViewport.TopLeftY = 0; + outViewport.Width = halfW; outViewport.Height = halfH; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + outViewport.TopLeftX = 0; outViewport.TopLeftY = halfH; + outViewport.Width = halfW; outViewport.Height = halfH; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + outViewport.TopLeftX = halfW; outViewport.TopLeftY = halfH; + outViewport.Width = halfW; outViewport.Height = halfH; + break; + default: + outViewport.TopLeftX = 0; outViewport.TopLeftY = 0; + outViewport.Width = w; outViewport.Height = h; + break; } + return true; } uint32_t GameRenderer::BuildPlayerViewports(D3D11_VIEWPORT *outViewports, float *outGammas, UINT maxCount) const @@ -1132,6 +1117,11 @@ int GameRenderer::getLightTexture(int iPad, Level *level) void GameRenderer::render(float a, bool bFirst) { + if (mc->player == nullptr) + { + return; + } + if( _updateLightTexture && bFirst) updateLightTexture(a); if (Display::isActive()) { @@ -1168,56 +1158,57 @@ void GameRenderer::render(float a, bool bFirst) } #endif - if (mc->noRender) return; - GameRenderer::anaglyph3d = mc->options->anaglyph3d; + if (mc->noRender) + return; + anaglyph3d = mc->options->anaglyph3d; - glViewport(0, 0, mc->width, mc->height); // 4J - added + glViewport(0, 0, mc->width, mc->height); // 4J - added (no-op on Win64, viewport set by StateSetViewport) ScreenSizeCalculator ssc(mc->options, mc->width, mc->height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - int xMouse = Mouse::getX() * screenWidth / mc->width; - int yMouse = screenHeight - Mouse::getY() * screenHeight / mc->height - 1; + const int screenWidth = ssc.getWidth(); + const int screenHeight = ssc.getHeight(); + const int xMouse = Mouse::getX() * screenWidth / mc->width; + const int yMouse = screenHeight - Mouse::getY() * screenHeight / mc->height - 1; - int maxFps = getFpsCap(mc->options->framerateLimit); + const int maxFps = getFpsCap(mc->options->framerateLimit); - if (mc->level != NULL) - { - if (mc->options->framerateLimit == 0) - { - renderLevel(a, 0); - } - else - { - renderLevel(a, lastNsTime + 1000000000 / maxFps); - } + if (mc->level != nullptr) + { + if (mc->options->framerateLimit == 0) + { + renderLevel(a, 0); + } + else + { + renderLevel(a, lastNsTime + 1000000000 / maxFps); + } - lastNsTime = System::nanoTime(); + lastNsTime = System::nanoTime(); - if (!mc->options->hideGui || mc->screen != NULL) - { - mc->gui->render(a, mc->screen != NULL, xMouse, yMouse); - } - } - else - { - glViewport(0, 0, mc->width, mc->height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - setupGuiScreen(); + if (!mc->options->hideGui || mc->screen != nullptr) + { + mc->gui->render(a, mc->screen != nullptr, xMouse, yMouse); + } + } + else + { + glViewport(0, 0, mc->width, mc->height); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + setupGuiScreen(); - lastNsTime = System::nanoTime(); - } + lastNsTime = System::nanoTime(); + } - - if (mc->screen != NULL) - { - glClear(GL_DEPTH_BUFFER_BIT); - mc->screen->render(xMouse, yMouse, a); - if (mc->screen != NULL && mc->screen->particles != NULL) mc->screen->particles->render(a); - } - } + if (mc->screen != nullptr) + { + glClear(GL_DEPTH_BUFFER_BIT); + mc->screen->render(xMouse, yMouse, a); + if (mc->screen != nullptr && mc->screen->particles != nullptr) + mc->screen->particles->render(a); + } +} void GameRenderer::renderLevel(float a) { @@ -1383,7 +1374,7 @@ void GameRenderer::renderLevel(float a, int64_t until) // going to do for the primary player, and the other players can just view whatever they have loaded in - we're sharing render data between players. bool updateChunks = ( mc->player == mc->localplayers[ProfileManager.GetPrimaryPad()] ); - // if (mc->cameraTargetPlayer == NULL) // 4J - removed condition as we want to update this is mc->player changes for different local players + // if (mc->cameraTargetPlayer == nullptr) // 4J - removed condition as we want to update this is mc->player changes for different local players { mc->cameraTargetPlayer = mc->player; } @@ -1511,7 +1502,7 @@ void GameRenderer::renderLevel(float a, int64_t until) PIXEndNamedEvent(); turnOffLightLayer(a); // 4J - brought forward from 1.8.2 - if ( (mc->hitResult != NULL) && cameraEntity->isUnderLiquid(Material::water) && cameraEntity->instanceof(eTYPE_PLAYER) ) //&& !mc->options.hideGui) + if ( (mc->hitResult != nullptr) && cameraEntity->isUnderLiquid(Material::water) && cameraEntity->instanceof(eTYPE_PLAYER) ) //&& !mc->options.hideGui) { shared_ptr player = dynamic_pointer_cast(cameraEntity); glDisable(GL_ALPHA_TEST); @@ -1580,7 +1571,7 @@ void GameRenderer::renderLevel(float a, int64_t until) if ( (zoom == 1) && cameraEntity->instanceof(eTYPE_PLAYER) ) //&& !mc->options.hideGui) { - if (mc->hitResult != NULL && !cameraEntity->isUnderLiquid(Material::water)) + if (mc->hitResult != nullptr && !cameraEntity->isUnderLiquid(Material::water)) { shared_ptr player = dynamic_pointer_cast(cameraEntity); glDisable(GL_ALPHA_TEST); @@ -1670,7 +1661,7 @@ void GameRenderer::tickRain() double rainPosZ = 0; int rainPosSamples = 0; - int rainCount = (int) (100 * rainLevel * rainLevel); + int rainCount = static_cast(100 * rainLevel * rainLevel); if (mc->options->particles == 1) { rainCount >>= 1; @@ -1693,7 +1684,7 @@ void GameRenderer::tickRain() { if (Tile::tiles[t]->material == Material::lava) { - mc->particleEngine->add( shared_ptr( new SmokeParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, 0, 0) ) ); + mc->particleEngine->add(std::make_shared(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, 0, 0)); } else { @@ -1703,7 +1694,7 @@ void GameRenderer::tickRain() rainPosY = y + 0.1f - Tile::tiles[t]->getShapeY0(); rainPosZ = z + za; } - mc->particleEngine->add( shared_ptr( new WaterDropParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za) ) ); + mc->particleEngine->add(std::make_shared(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za)); } } } @@ -1738,7 +1729,7 @@ void GameRenderer::renderSnowAndRain(float a) turnOnLightLayer(a); - if (rainXa == NULL) + if (rainXa == nullptr) { rainXa = new float[32 * 32]; rainZa = new float[32 * 32]; @@ -1885,11 +1876,11 @@ void GameRenderer::renderSnowAndRain(float a) t->begin(); } float ra = (((_tick) & 511) + a) / 512.0f; - float uo = random->nextFloat() + time * 0.01f * (float) random->nextGaussian(); - float vo = random->nextFloat() + time * (float) random->nextGaussian() * 0.001f; + float uo = random->nextFloat() + time * 0.01f * static_cast(random->nextGaussian()); + float vo = random->nextFloat() + time * static_cast(random->nextGaussian()) * 0.001f; double xd = (x + 0.5f) - player->x; double zd = (z + 0.5f) - player->z; - float dd = (float) sqrt(xd * xd + zd * zd) / r; + float dd = static_cast(sqrt(xd * xd + zd * zd)) / r; float br = 1; t->offset(-xo * 1, -yo * 1, -zo * 1); #ifdef __PSVITA__ @@ -1931,7 +1922,7 @@ void GameRenderer::setupGuiScreen(int forceScale /*=-1*/) glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); + glOrtho(0, static_cast(ssc.rawWidth), static_cast(ssc.rawHeight), 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -2000); @@ -1943,27 +1934,27 @@ void GameRenderer::setupClearColor(float a) shared_ptr player = mc->cameraTargetPlayer; float whiteness = 1.0f / (4 - mc->options->viewDistance); - whiteness = 1 - (float) pow((double)whiteness, 0.25); + whiteness = 1 - static_cast(pow(static_cast(whiteness), 0.25)); Vec3 *skyColor = level->getSkyColor(mc->cameraTargetPlayer, a); - float sr = (float) skyColor->x; - float sg = (float) skyColor->y; - float sb = (float) skyColor->z; + float sr = static_cast(skyColor->x); + float sg = static_cast(skyColor->y); + float sb = static_cast(skyColor->z); Vec3 *fogColor = level->getFogColor(a); - fr = (float) fogColor->x; - fg = (float) fogColor->y; - fb = (float) fogColor->z; + fr = static_cast(fogColor->x); + fg = static_cast(fogColor->y); + fb = static_cast(fogColor->z); if (mc->options->viewDistance < 2) { Vec3 *sunAngle = Mth::sin(level->getSunAngle(a)) > 0 ? Vec3::newTemp(-1, 0, 0) : Vec3::newTemp(1, 0, 0); - float d = (float) player->getViewVector(a)->dot(sunAngle); + float d = static_cast(player->getViewVector(a)->dot(sunAngle)); if (d < 0) d = 0; if (d > 0) { float *c = level->dimension->getSunriseColor(level->getTimeOfDay(a), a); - if (c != NULL) + if (c != nullptr) { d *= c[3]; fr = fr * (1 - d) + c[0] * d; @@ -1999,9 +1990,9 @@ void GameRenderer::setupClearColor(float a) if (isInClouds) { Vec3 *cc = level->getCloudColor(a); - fr = (float) cc->x; - fg = (float) cc->y; - fb = (float) cc->z; + fr = static_cast(cc->x); + fg = static_cast(cc->y); + fb = static_cast(cc->z); } else if (t != 0 && Tile::tiles[t]->material == Material::water) { @@ -2012,9 +2003,9 @@ void GameRenderer::setupClearColor(float a) byte greenComponent = ((colour>>8)&0xFF); byte blueComponent = ((colour)&0xFF); - fr = (float)redComponent/256 + clearness;//0.02f; - fg = (float)greenComponent/256 + clearness;//0.02f; - fb = (float)blueComponent/256 + clearness;//0.2f; + fr = static_cast(redComponent)/256 + clearness;//0.02f; + fg = static_cast(greenComponent)/256 + clearness;//0.02f; + fb = static_cast(blueComponent)/256 + clearness;//0.2f; } else if (t != 0 && Tile::tiles[t]->material == Material::lava) { @@ -2023,9 +2014,9 @@ void GameRenderer::setupClearColor(float a) byte greenComponent = ((colour>>8)&0xFF); byte blueComponent = ((colour)&0xFF); - fr = (float)redComponent/256;//0.6f; - fg = (float)greenComponent/256;//0.1f; - fb = (float)blueComponent/256;//0.00f; + fr = static_cast(redComponent)/256;//0.6f; + fg = static_cast(greenComponent)/256;//0.1f; + fb = static_cast(blueComponent)/256;//0.00f; } float brr = fogBrO + (fogBr - fogBrO) * a; @@ -2040,7 +2031,7 @@ void GameRenderer::setupClearColor(float a) int duration = player->getEffect(MobEffect::blindness)->getDuration(); if (duration < 20) { - yy = yy * (1.0f - (float) duration / 20.0f); + yy = yy * (1.0f - static_cast(duration) / 20.0f); } else { @@ -2145,7 +2136,7 @@ void GameRenderer::setupFog(int i, float alpha) int duration = player->getEffect(MobEffect::blindness)->getDuration(); if (duration < 20) { - distance = 5.0f + (renderDistance - 5.0f) * (1.0f - (float) duration / 20.0f); + distance = 5.0f + (renderDistance - 5.0f) * (1.0f - static_cast(duration) / 20.0f); } glFogi(GL_FOG_MODE, GL_LINEAR); @@ -2200,7 +2191,7 @@ void GameRenderer::setupFog(int i, float alpha) { if (yy < 0) yy = 0; yy = yy * yy; - float dist = 100 * (float) yy; + float dist = 100 * static_cast(yy); if (dist < 5) dist = 5; if (distance > dist) distance = dist; } @@ -2227,7 +2218,7 @@ void GameRenderer::setupFog(int i, float alpha) } */ - if (mc->level->dimension->isFoggyAt((int) player->x, (int) player->z)) + if (mc->level->dimension->isFoggyAt(static_cast(player->x), static_cast(player->z))) { glFogf(GL_FOG_START, distance * 0.05f); glFogf(GL_FOG_END, min(distance, 16 * 16 * .75f) * .5f); diff --git a/Minecraft.Client/GhastModel.cpp b/Minecraft.Client/GhastModel.cpp index 14277c438..0a482e628 100644 --- a/Minecraft.Client/GhastModel.cpp +++ b/Minecraft.Client/GhastModel.cpp @@ -23,7 +23,7 @@ GhastModel::GhastModel() : Model() tentacles[i]->x = xo; tentacles[i]->z = yo; - tentacles[i]->y = (float)(31 + yoffs); + tentacles[i]->y = static_cast(31 + yoffs); } // 4J added - compile now to avoid random performance hit first time cubes are rendered diff --git a/Minecraft.Client/Gui.cpp b/Minecraft.Client/Gui.cpp index 8a3e84db0..f0d44319a 100644 --- a/Minecraft.Client/Gui.cpp +++ b/Minecraft.Client/Gui.cpp @@ -28,6 +28,7 @@ #include "..\Minecraft.World\net.minecraft.world.h" #include "..\Minecraft.World\LevelChunk.h" #include "..\Minecraft.World\Biome.h" +#include ResourceLocation Gui::PUMPKIN_BLUR_LOCATION = ResourceLocation(TN__BLUR__MISC_PUMPKINBLUR); @@ -62,6 +63,12 @@ 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. + + if (minecraft->player == nullptr) + { + return; + } + 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(); @@ -87,7 +94,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) int quickSelectHeight=22; float fScaleFactorWidth=1.0f,fScaleFactorHeight=1.0f; bool bTwoPlayerSplitscreen=false; - currentGuiScaleFactor = (float) guiScale; // Keep static copy of scale so we know how gui coordinates map to physical pixels - this is also affected by the viewport + currentGuiScaleFactor = static_cast(guiScale); // Keep static copy of scale so we know how gui coordinates map to physical pixels - this is also affected by the viewport switch(guiScale) { @@ -117,7 +124,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) iSafezoneYHalf = splitYOffset; iSafezoneTopYHalf = screenHeight/10; fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); + iWidthOffset=static_cast((float)screenWidth * (1.0f - fScaleFactorWidth)); iTooltipsYOffset=44; bTwoPlayerSplitscreen=true; currentGuiScaleFactor *= 0.5f; @@ -127,7 +134,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) iSafezoneTopYHalf = 0; fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); + iWidthOffset=static_cast((float)screenWidth * (1.0f - fScaleFactorWidth)); iTooltipsYOffset=44; bTwoPlayerSplitscreen=true; currentGuiScaleFactor *= 0.5f; @@ -436,7 +443,8 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) double maxHealth = minecraft->localplayers[iPad]->getAttribute(SharedMonsterAttributes.MAX_HEALTH); double totalAbsorption = minecraft->localplayers[iPad]->getAbsorptionAmount(); - int numHealthRows = Mth.ceil((maxHealth + totalAbsorption) / 2 / (float) NUM_HEARTS_PER_ROW); + const double healthHalves = (maxHealth + totalAbsorption) / 2.0; + int numHealthRows = Mth.ceil(healthHalves / (float) NUM_HEARTS_PER_ROW); int healthRowHeight = Math.max(10 - (numHealthRows - 2), 3); int yLine2 = yLine1 - (numHealthRows - 1) * healthRowHeight - 10; absorption = totalAbsorption; @@ -462,7 +470,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } //minecraft.profiler.popPush("health"); - for (int i = Mth.ceil((maxHealth + totalAbsorption) / 2) - 1; i >= 0; i--) + for (int i = (int)Mth.ceil(healthHalves) - 1; i >= 0; i--) { int healthTexBaseX = 16; if (minecraft.player.hasEffect(MobEffect.poison)) @@ -600,8 +608,11 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) // render air bubbles if (minecraft->player->isUnderLiquid(Material::water)) { - int count = (int) ceil((minecraft->player->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY); - int extra = (int) ceil((minecraft->player->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY) - count; + const int airSupply = minecraft->player->getAirSupply(); + const float airScale = 10.0f / Player::TOTAL_AIR_SUPPLY; + const float airSupplyScaled = airSupply * airScale; + int count = (int) ceil((airSupply - 2) * airScale); + int extra = (int) ceil(airSupplyScaled) - count; for (int i = 0; i < count + extra; i++) { // Air bubbles @@ -697,7 +708,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) #endif glPushMatrix(); - glTranslatef((float)xo, (float)yo, 50); + glTranslatef(static_cast(xo), static_cast(yo), 50); float ss = 12; glScalef(-ss, ss, ss); glRotatef(180, 0, 0, 1); @@ -718,7 +729,8 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) Lighting::turnOn(); glRotatef(-45 - 90, 0, 1, 0); - glRotatef(-(float) atan(yd / 40.0f ) * 20, 1, 0, 0); + const float xRotAngle = -(float) atan(yd / 40.0f) * 20; + glRotatef(xRotAngle, 1, 0, 0); float bodyRot = (minecraft->player->yBodyRotO + (minecraft->player->yBodyRot - minecraft->player->yBodyRotO)); // Fixed rotation angle of degrees, adjusted by bodyRot to negate the rotation that occurs in the renderer // bodyRot in the rotation below is a simplification of "180 - (180 - bodyRot)" where the first 180 is EntityRenderDispatcher::instance->playerRotY that we set below @@ -729,7 +741,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) // Set head rotation to body rotation to make head static minecraft->player->yRot = bodyRot; minecraft->player->yRotO = minecraft->player->yRot; - minecraft->player->xRot = -(float) atan(yd / 40.0f) * 20; + minecraft->player->xRot = xRotAngle; minecraft->player->onFire = 0; minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); @@ -806,14 +818,14 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glDisable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); int timer = minecraft->player->getSleepTimer(); - float amount = (float) timer / (float) Player::SLEEP_DURATION; + float amount = static_cast(timer) / static_cast(Player::SLEEP_DURATION); if (amount > 1) { // waking up - amount = 1.0f - ((float) (timer - Player::SLEEP_DURATION) / (float) Player::WAKE_UP_DURATION); + amount = 1.0f - (static_cast(timer - Player::SLEEP_DURATION) / static_cast(Player::WAKE_UP_DURATION)); } - int color = (int) (220.0f * amount) << 24 | (0x101020); + int color = static_cast(220.0f * amount) << 24 | (0x101020); fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); glEnable(GL_ALPHA_TEST); glEnable(GL_DEPTH_TEST); @@ -825,9 +837,9 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glDisable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); int timer = minecraft->player->getDeathFadeTimer(); - float amount = (float) timer / (float) Player::DEATHFADE_DURATION; + float amount = static_cast(timer) / static_cast(Player::DEATHFADE_DURATION); - int color = (int) (220.0f * amount) << 24 | (0x200000); + int color = static_cast(220.0f * amount) << 24 | (0x200000); fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); glEnable(GL_ALPHA_TEST); glEnable(GL_DEPTH_TEST); @@ -842,201 +854,6 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) // font.draw(str, x + 1, y, 0xffffff); // } -#ifndef _FINAL_BUILD - MemSect(31); - if (minecraft->options->renderDebug) - { - const int debugLeft = 1; - const int debugTop = 1; - const float maxContentWidth = 1200.f; - const float maxContentHeight = 420.f; - float scale = (float)(screenWidth - debugLeft - 8) / maxContentWidth; - float scaleV = (float)(screenHeight - debugTop - 80) / maxContentHeight; - if (scaleV < scale) scale = scaleV; - if (scale > 1.f) scale = 1.f; - if (scale < 0.5f) scale = 0.5f; - glPushMatrix(); - glTranslatef((float)debugLeft, (float)debugTop, 0.f); - glScalef(scale, scale, 1.f); - glTranslatef((float)-debugLeft, (float)-debugTop, 0.f); - - vector lines; - - lines.push_back(ClientConstants::VERSION_STRING); - lines.push_back(minecraft->fpsString); - lines.push_back(L"E: " + std::to_wstring(minecraft->level->getAllEntities().size())); // Could maybe use entity::shouldRender to work out how many are rendered but thats like expensive - // TODO Add server information with packet counts - once multiplayer is more stable - int renderDistance = app.GetGameSettings(iPad, eGameSetting_RenderDistance); - // Calculate the chunk sections using 16 * (2n + 1)^2 - lines.push_back(L"C: " + std::to_wstring(16 * (2 * renderDistance + 1) * (2 * renderDistance + 1)) + L" D: " + std::to_wstring(renderDistance)); - lines.push_back(minecraft->gatherStats4()); // Chunk Cache - - // Dimension - wstring dimension = L"unknown"; - switch (minecraft->player->dimension) - { - case -1: - dimension = L"minecraft:the_nether"; - break; - case 0: - dimension = L"minecraft:overworld"; - break; - case 1: - dimension = L"minecraft:the_end"; - break; - } - lines.push_back(dimension); - - lines.push_back(L""); // Spacer - - // Players block pos - int xBlockPos = Mth::floor(minecraft->player->x); - int yBlockPos = Mth::floor(minecraft->player->y); - int zBlockPos = Mth::floor(minecraft->player->z); - - // Chunk player is in - int xChunkPos = xBlockPos >> 4; - int yChunkPos = yBlockPos >> 4; - int zChunkPos = zBlockPos >> 4; - - // Players offset within the chunk - int xChunkOffset = xBlockPos & 15; - int yChunkOffset = yBlockPos & 15; - int zChunkOffset = zBlockPos & 15; - - // Format the position like java with limited decumal places - WCHAR posString[44]; // Allows upto 7 digit positions (+-9_999_999) - swprintf(posString, 44, L"%.3f / %.5f / %.3f", minecraft->player->x, minecraft->player->y, minecraft->player->z); - - lines.push_back(L"XYZ: " + std::wstring(posString)); - lines.push_back(L"Block: " + std::to_wstring(static_cast(xBlockPos)) + L" " + std::to_wstring(static_cast(yBlockPos)) + L" " + std::to_wstring(static_cast(zBlockPos))); - lines.push_back(L"Chunk: " + std::to_wstring(xChunkOffset) + L" " + std::to_wstring(yChunkOffset) + L" " + std::to_wstring(zChunkOffset) + L" in " + std::to_wstring(xChunkPos) + L" " + std::to_wstring(yChunkPos) + L" " + std::to_wstring(zChunkPos)); - - // Wrap the yRot to 360 then adjust to (-180 to 180) range to match java - float yRotDisplay = fmod(minecraft->player->yRot, 360.0f); - if (yRotDisplay > 180.0f) - { - yRotDisplay -= 360.0f; - } - if (yRotDisplay < -180.0f) - { - yRotDisplay += 360.0f; - } - // Generate the angle string in the format "yRot / xRot" with one decimal place, similar to java edition - WCHAR angleString[16]; - swprintf(angleString, 16, L"%.1f / %.1f", yRotDisplay, minecraft->player->xRot); - - // Work out the named direction - int direction = Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3; - wstring cardinalDirection; - switch (direction) - { - case 0: - cardinalDirection = L"south"; - break; - case 1: - cardinalDirection = L"west"; - break; - case 2: - cardinalDirection = L"north"; - break; - case 3: - cardinalDirection = L"east"; - break; - } - - lines.push_back(L"Facing: " + cardinalDirection + L" (" + angleString + L")"); - - // We have to limit y to 256 as we don't get any information past that - if (minecraft->level != NULL && minecraft->level->hasChunkAt(xBlockPos, fmod(yBlockPos, 256), zBlockPos)) - { - LevelChunk *chunkAt = minecraft->level->getChunkAt(xBlockPos, zBlockPos); - if (chunkAt != NULL) - { - int skyLight = chunkAt->getBrightness(LightLayer::Sky, xChunkOffset, yChunkOffset, zChunkOffset); - int blockLight = chunkAt->getBrightness(LightLayer::Block, xChunkOffset, yChunkOffset, zChunkOffset); - int maxLight = fmax(skyLight, blockLight); - lines.push_back(L"Light: " + std::to_wstring(maxLight) + L" (" + std::to_wstring(skyLight) + L" sky, " + std::to_wstring(blockLight) + L" block)"); - - lines.push_back(L"CH S: " + std::to_wstring(chunkAt->getHeightmap(xChunkOffset, zChunkOffset))); - - Biome *biome = chunkAt->getBiome(xChunkOffset, zChunkOffset, minecraft->level->getBiomeSource()); - lines.push_back(L"Biome: " + biome->m_name + L" (" + std::to_wstring(biome->id) + L")"); - - lines.push_back(L"Difficulty: " + std::to_wstring(minecraft->level->difficulty) + L" (Day " + std::to_wstring(minecraft->level->getGameTime() / Level::TICKS_PER_DAY) + L")"); - } - } - - - // This is all LCE only stuff, it was never on java - lines.push_back(L""); // Spacer - lines.push_back(L"Seed: " + std::to_wstring(minecraft->level->getLevelData()->getSeed())); - lines.push_back(minecraft->gatherStats1()); // Time to autosave - lines.push_back(minecraft->gatherStats2()); // Empty currently - CPlatformNetworkManagerStub::GatherStats() - lines.push_back(minecraft->gatherStats3()); // RTT - -#ifdef _DEBUG // Only show terrain features in debug builds not release - // TERRAIN FEATURES - if (minecraft->level->dimension->id == 0) - { - wstring wfeature[eTerrainFeature_Count]; - - wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; - wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; - wfeature[eTerrainFeature_Village] = L"Village: "; - wfeature[eTerrainFeature_Ravine] = L"Ravine: "; - - float maxW = (float)(screenWidth - debugLeft - 8) / scale; - float maxWForContent = maxW - (float)font->width(L"..."); - bool truncated[eTerrainFeature_Count] = {}; - - for (int i = 0; i < (int)app.m_vTerrainFeatures.size(); i++) - { - FEATURE_DATA *pFeatureData = app.m_vTerrainFeatures[i]; - int type = pFeatureData->eTerrainFeature; - if (type < eTerrainFeature_Stronghold || type > eTerrainFeature_Ravine) - { - continue; - } - if (truncated[type]) - { - continue; - } - - wstring itemInfo = L"[" + std::to_wstring(pFeatureData->x * 16) + L", " + std::to_wstring(pFeatureData->z * 16) + L"] "; - if (font->width(wfeature[type] + itemInfo) <= maxWForContent) - { - wfeature[type] += itemInfo; - } - else - { - wfeature[type] += L"..."; - truncated[type] = true; - } - } - - lines.push_back(L""); // Add a spacer line - for (int i = eTerrainFeature_Stronghold; i <= (int)eTerrainFeature_Ravine; i++) - { - lines.push_back(wfeature[i]); - } - lines.push_back(L""); - } -#endif - - // Loop through the lines and draw them all on screen - int yPos = debugTop; - for (const auto &line : lines) - { - drawString(font, line, debugLeft, yPos, 0xffffff); - yPos += 10; - } - - glPopMatrix(); - } - MemSect(0); -#endif - lastTickA = a; // 4J Stu - This is now displayed in a xui scene #if 0 @@ -1190,6 +1007,190 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glPopMatrix(); } +#ifndef _FINAL_BUILD + MemSect(31); + if (true) + { + // Real window dimensions updated on every WM_SIZE — always current + extern int g_rScreenWidth; + extern int g_rScreenHeight; + + // Set up a fresh projection using physical pixel coordinates so the debug + // text is never distorted regardless of aspect ratio, splitscreen layout, + // or menu state. 1 coordinate unit = 1 physical pixel. + // Compute the actual viewport dimensions for this player's screen section. + // glOrtho must match the viewport exactly for 1 unit = 1 physical pixel. + int vpW = g_rScreenWidth; + int vpH = g_rScreenHeight; + switch (minecraft->player->m_iScreenSection) + { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + vpH /= 2; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + vpW /= 2; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + vpW /= 2; + vpH /= 2; + break; + default: // VIEWPORT_TYPE_FULLSCREEN + break; + } + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + glOrtho(0, vpW, vpH, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + glTranslatef(0, 0, -2000); + + // Font was designed for guiScale px/unit; scale up so characters appear + // at the same physical size as the rest of the HUD at 0.5x. + const float fontScale = static_cast(guiScale) * 1.0f; + const int debugLeft = 1; + const int debugTop = 1; + + glTranslatef(static_cast(debugLeft), static_cast(debugTop), 0.f); + glScalef(fontScale, fontScale, 1.f); + glTranslatef(static_cast(-debugLeft), static_cast(-debugTop), 0.f); + + vector lines; + + // Only show version/branch for player 0 to avoid cluttering each splitscreen viewport + if (iPad == 0) + { + lines.push_back(ClientConstants::VERSION_STRING); + lines.push_back(ClientConstants::BRANCH_STRING); + } + if (minecraft->options->renderDebug && minecraft->player != nullptr && minecraft->level != nullptr) + { + lines.push_back(minecraft->fpsString); + lines.push_back(L"E: " + std::to_wstring(minecraft->level->getAllEntities().size())); + int renderDistance = app.GetGameSettings(iPad, eGameSetting_RenderDistance); + lines.push_back(L"C: " + std::to_wstring(16 * (2 * renderDistance + 1) * (2 * renderDistance + 1)) + L" D: " + std::to_wstring(renderDistance)); + lines.push_back(minecraft->gatherStats4()); + + wstring dimension = L"unknown"; + switch (minecraft->player->dimension) + { + case -1: dimension = L"minecraft:the_nether"; break; + case 0: dimension = L"minecraft:overworld"; break; + case 1: dimension = L"minecraft:the_end"; break; + } + lines.push_back(dimension); + lines.push_back(L""); + + int xBlockPos = Mth::floor(minecraft->player->x); + int yBlockPos = Mth::floor(minecraft->player->y); + int zBlockPos = Mth::floor(minecraft->player->z); + int xChunkPos = xBlockPos >> 4; + int yChunkPos = yBlockPos >> 4; + int zChunkPos = zBlockPos >> 4; + int xChunkOffset = xBlockPos & 15; + int yChunkOffset = yBlockPos & 15; + int zChunkOffset = zBlockPos & 15; + + WCHAR posString[44]; + swprintf(posString, 44, L"%.3f / %.5f / %.3f", minecraft->player->x, minecraft->player->y, minecraft->player->z); + + lines.push_back(L"XYZ: " + std::wstring(posString)); + lines.push_back(L"Block: " + std::to_wstring(xBlockPos) + L" " + std::to_wstring(yBlockPos) + L" " + std::to_wstring(zBlockPos)); + lines.push_back(L"Chunk: " + std::to_wstring(xChunkOffset) + L" " + std::to_wstring(yChunkOffset) + L" " + std::to_wstring(zChunkOffset) + L" in " + std::to_wstring(xChunkPos) + L" " + std::to_wstring(yChunkPos) + L" " + std::to_wstring(zChunkPos)); + + float yRotDisplay = fmod(minecraft->player->yRot, 360.0f); + if (yRotDisplay > 180.0f) yRotDisplay -= 360.0f; + if (yRotDisplay < -180.0f) yRotDisplay += 360.0f; + WCHAR angleString[16]; + swprintf(angleString, 16, L"%.1f / %.1f", yRotDisplay, minecraft->player->xRot); + + int direction = Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3; + const wchar_t* cardinals[] = { L"south", L"west", L"north", L"east" }; + lines.push_back(L"Facing: " + std::wstring(cardinals[direction]) + L" (" + angleString + L")"); + + if (minecraft->level != NULL && minecraft->level->hasChunkAt(xBlockPos, fmod(yBlockPos, 256), zBlockPos)) + { + LevelChunk *chunkAt = minecraft->level->getChunkAt(xBlockPos, zBlockPos); + if (chunkAt != NULL) + { + int skyLight = chunkAt->getBrightness(LightLayer::Sky, xChunkOffset, yChunkOffset, zChunkOffset); + int blockLight = chunkAt->getBrightness(LightLayer::Block, xChunkOffset, yChunkOffset, zChunkOffset); + int maxLight = fmax(skyLight, blockLight); + lines.push_back(L"Light: " + std::to_wstring(maxLight) + L" (" + std::to_wstring(skyLight) + L" sky, " + std::to_wstring(blockLight) + L" block)"); + lines.push_back(L"CH S: " + std::to_wstring(chunkAt->getHeightmap(xChunkOffset, zChunkOffset))); + Biome *biome = chunkAt->getBiome(xChunkOffset, zChunkOffset, minecraft->level->getBiomeSource()); + lines.push_back(L"Biome: " + biome->m_name + L" (" + std::to_wstring(biome->id) + L")"); + lines.push_back(L"Difficulty: " + std::to_wstring(minecraft->level->difficulty) + L" (Day " + std::to_wstring(minecraft->level->getGameTime() / Level::TICKS_PER_DAY) + L")"); + } + } + + lines.push_back(L""); + lines.push_back(L"Seed: " + std::to_wstring(minecraft->level->getLevelData()->getSeed())); + lines.push_back(minecraft->gatherStats1()); + lines.push_back(minecraft->gatherStats2()); + lines.push_back(minecraft->gatherStats3()); + } + +#ifdef _DEBUG + if (minecraft->options->renderDebug && minecraft->player != nullptr && minecraft->level != nullptr && minecraft->level->dimension->id == 0) + { + wstring wfeature[eTerrainFeature_Count]; + wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; + wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; + wfeature[eTerrainFeature_Village] = L"Village: "; + wfeature[eTerrainFeature_Ravine] = L"Ravine: "; + + // maxW in font units: physical width divided by font scale + float maxW = (static_cast(g_rScreenWidth) - debugLeft - 8) / fontScale; + float maxWForContent = maxW - static_cast(font->width(L"...")); + bool truncated[eTerrainFeature_Count] = {}; + + for (size_t i = 0; i < app.m_vTerrainFeatures.size(); i++) + { + FEATURE_DATA *pFeatureData = app.m_vTerrainFeatures[i]; + int type = pFeatureData->eTerrainFeature; + if (type < eTerrainFeature_Stronghold || type > eTerrainFeature_Ravine) continue; + if (truncated[type]) continue; + wstring itemInfo = L"[" + std::to_wstring(pFeatureData->x * 16) + L", " + std::to_wstring(pFeatureData->z * 16) + L"] "; + if (font->width(wfeature[type] + itemInfo) <= maxWForContent) + wfeature[type] += itemInfo; + else + { + wfeature[type] += L"..."; + truncated[type] = true; + } + } + + lines.push_back(L""); + for (int i = eTerrainFeature_Stronghold; i <= static_cast(eTerrainFeature_Ravine); i++) + lines.push_back(wfeature[i]); + lines.push_back(L""); + } +#endif + + int yPos = debugTop; + for (const auto &line : lines) + { + drawString(font, line, debugLeft, yPos, 0xffffff); + yPos += 10; + } + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + } + MemSect(0); +#endif + glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); glEnable(GL_ALPHA_TEST); @@ -1243,10 +1244,10 @@ void Gui::renderPumpkin(int w, int h) MemSect(0); Tesselator *t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( 0), (float)( 1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( 1), (float)( 1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( 1), (float)( 0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( 0), (float)( 0)); + t->vertexUV(static_cast(0), static_cast(h), static_cast(-90), static_cast(0), static_cast(1)); + t->vertexUV(static_cast(w), static_cast(h), static_cast(-90), static_cast(1), static_cast(1)); + t->vertexUV(static_cast(w), static_cast(0), static_cast(-90), static_cast(1), static_cast(0)); + t->vertexUV(static_cast(0), static_cast(0), static_cast(-90), static_cast(0), static_cast(0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); @@ -1307,10 +1308,10 @@ void Gui::renderTp(float br, int w, int h) float v1 = slot->getV1(); Tesselator *t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( u0), (float)( v1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( u1), (float)( v1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( u1), (float)( v0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( u0), (float)( v0)); + t->vertexUV(static_cast(0), static_cast(h), static_cast(-90), (float)( u0), (float)( v1)); + t->vertexUV(static_cast(w), static_cast(h), static_cast(-90), (float)( u1), (float)( v1)); + t->vertexUV(static_cast(w), static_cast(0), static_cast(-90), (float)( u1), (float)( v0)); + t->vertexUV(static_cast(0), static_cast(0), static_cast(-90), (float)( u0), (float)( v0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); @@ -1328,10 +1329,10 @@ void Gui::renderSlot(int slot, int x, int y, float a) if (pop > 0) { glPushMatrix(); - float squeeze = 1 + pop / (float) Inventory::POP_TIME_DURATION; - glTranslatef((float)(x + 8), (float)(y + 12), 0); + float squeeze = 1 + pop / static_cast(Inventory::POP_TIME_DURATION); + glTranslatef(static_cast(x + 8), static_cast(y + 12), 0); glScalef(1 / squeeze, (squeeze + 1) / 2, 1); - glTranslatef((float)-(x + 8), (float)-(y + 12), 0); + glTranslatef(static_cast(-(x + 8)), static_cast(-(y + 12)), 0); } itemRenderer->renderAndDecorateItem(minecraft->font, minecraft->textures, item, x, y); @@ -1470,7 +1471,7 @@ void Gui::addMessage(const wstring& _string,int iPad,bool bIsDeathMessage) { i++; } - int iLast=(int)string.find_last_of(L" ",i); + size_t iLast=string.find_last_of(L" ",i); switch(XGetLanguage()) { case XC_LANGUAGE_JAPANESE: @@ -1479,7 +1480,7 @@ void Gui::addMessage(const wstring& _string,int iPad,bool bIsDeathMessage) iLast = maximumChars; break; default: - iLast=(int)string.find_last_of(L" ",i); + iLast=string.find_last_of(L" ",i); break; } @@ -1539,7 +1540,7 @@ float Gui::getOpacity(int iPad, DWORD index) float Gui::getJukeboxOpacity(int iPad) { float t = overlayMessageTime - lastTickA; - int alpha = (int) (t * 256 / 20); + int alpha = static_cast(t * 256 / 20); if (alpha > 255) alpha = 255; alpha /= 255; @@ -1573,7 +1574,7 @@ void Gui::renderGraph(int dataLength, int dataPos, int64_t *dataA, float dataASc glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glOrtho(0, static_cast(minecraft->width), static_cast(height), 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -2000); @@ -1604,8 +1605,8 @@ void Gui::renderGraph(int dataLength, int dataPos, int64_t *dataA, float dataASc int64_t aVal = dataA[i] / dataAScale; - 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)); + t->vertex((float)(xScale*i + 0.5f), (float)( height - aVal + 0.5f), static_cast(0)); + t->vertex((float)(xScale*i + 0.5f), (float)( height + 0.5f), static_cast(0)); } if( dataB != NULL ) @@ -1621,8 +1622,8 @@ void Gui::renderGraph(int dataLength, int dataPos, int64_t *dataA, float dataASc int64_t bVal = dataB[i] / dataBScale; - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height - bVal + 0.5f), (float)( 0)); - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height + 0.5f), (float)( 0)); + t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height - bVal + 0.5f), static_cast(0)); + t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height + 0.5f), static_cast(0)); } } t->end(); @@ -1637,7 +1638,7 @@ void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, int64 glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glOrtho(0, static_cast(minecraft->width), static_cast(height), 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -2000); @@ -1666,15 +1667,15 @@ void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, int64 if( thisVal > 0 ) { - float vary = (float)source/dataSources; + float vary = static_cast(source)/dataSources; int fColour = floor(vary * 0xffffff); int colour = 0xff000000 + fColour; //printf("Colour is %x\n", colour); t->color(colour); - t->vertex((float)(i + 0.5f), (float)( height - topVal - thisVal + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - topVal + 0.5f), (float)( 0)); + t->vertex((float)(i + 0.5f), (float)( height - topVal - thisVal + 0.5f), static_cast(0)); + t->vertex((float)(i + 0.5f), (float)( height - topVal + 0.5f), static_cast(0)); topVal += thisVal; } @@ -1685,8 +1686,8 @@ void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, int64 { t->color(0xff000000); - t->vertex((float)(0 + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); - t->vertex((float)(dataLength + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); + t->vertex((float)(0 + 0.5f), (float)( height - (horiz*100) + 0.5f), static_cast(0)); + t->vertex((float)(dataLength + 0.5f), (float)( height - (horiz*100) + 0.5f), static_cast(0)); } } t->end(); diff --git a/Minecraft.Client/Gui.h b/Minecraft.Client/Gui.h index 60ea8b7c1..64b8dfbe8 100644 --- a/Minecraft.Client/Gui.h +++ b/Minecraft.Client/Gui.h @@ -59,7 +59,7 @@ public: void displayClientMessage(int messageId, int iPad); // 4J Added - DWORD getMessagesCount(int iPad) { return (int)guiMessages[iPad].size(); } + DWORD getMessagesCount(int iPad) { return static_cast(guiMessages[iPad].size()); } wstring getMessage(int iPad, DWORD index) { return guiMessages[iPad].at(index).string; } float getOpacity(int iPad, DWORD index); diff --git a/Minecraft.Client/GuiParticle.cpp b/Minecraft.Client/GuiParticle.cpp index 25859c707..1e6bcc708 100644 --- a/Minecraft.Client/GuiParticle.cpp +++ b/Minecraft.Client/GuiParticle.cpp @@ -24,7 +24,7 @@ GuiParticle::GuiParticle(double x, double y, double xa, double ya) friction = 1.0 / (random->nextDouble() * 0.05 + 1.01); - lifeTime = (int) (10.0 / (random->nextDouble() * 2 + 0.1)); + lifeTime = static_cast(10.0 / (random->nextDouble() * 2 + 0.1)); } void GuiParticle::tick(GuiParticles *guiParticles) @@ -37,7 +37,7 @@ void GuiParticle::tick(GuiParticles *guiParticles) ya += 0.1; if (++life > lifeTime) remove(); - a = 2 - (life / (double) lifeTime) * 2; + a = 2 - (life / static_cast(lifeTime)) * 2; if (a > 1) a = 1; a = a * a; a *= 0.5; diff --git a/Minecraft.Client/HugeExplosionParticle.cpp b/Minecraft.Client/HugeExplosionParticle.cpp index 2a104c19e..276b1d160 100644 --- a/Minecraft.Client/HugeExplosionParticle.cpp +++ b/Minecraft.Client/HugeExplosionParticle.cpp @@ -25,12 +25,12 @@ HugeExplosionParticle::HugeExplosionParticle(Textures *textures, Level *level, d gCol = g * br; bCol = b * br; - size = 1 - (float) xa * 0.5f; + size = 1 - static_cast(xa) * 0.5f; } void HugeExplosionParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { - int tex = (int) ((life + a) * 15 / lifeTime); + int tex = static_cast((life + a) * 15 / lifeTime); if (tex > 15) return; textures->bindTexture(&EXPLOSION_LOCATION); @@ -41,9 +41,9 @@ void HugeExplosionParticle::render(Tesselator *t, float a, float xa, float ya, f float r = 2.0f * size; - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing float distSq = (x*x + y*y + z*z); diff --git a/Minecraft.Client/HugeExplosionSeedParticle.cpp b/Minecraft.Client/HugeExplosionSeedParticle.cpp index 7514cc44f..bb8c8f223 100644 --- a/Minecraft.Client/HugeExplosionSeedParticle.cpp +++ b/Minecraft.Client/HugeExplosionSeedParticle.cpp @@ -24,9 +24,9 @@ void HugeExplosionSeedParticle::tick() double xx = x + (random->nextDouble() - random->nextDouble()) * 4; double yy = y + (random->nextDouble() - random->nextDouble()) * 4; double zz = z + (random->nextDouble() - random->nextDouble()) * 4; - level->addParticle(eParticleType_largeexplode, xx, yy, zz, life / (float) lifeTime, 0, 0); + level->addParticle(eParticleType_largeexplode, xx, yy, zz, life / static_cast(lifeTime), 0, 0); } - Minecraft::GetInstance()->animateTickLevel = NULL; + Minecraft::GetInstance()->animateTickLevel = nullptr; life++; if (life == lifeTime) remove(); } diff --git a/Minecraft.Client/HumanoidMobRenderer.cpp b/Minecraft.Client/HumanoidMobRenderer.cpp index 5329f2d9c..284b084d4 100644 --- a/Minecraft.Client/HumanoidMobRenderer.cpp +++ b/Minecraft.Client/HumanoidMobRenderer.cpp @@ -17,8 +17,8 @@ void HumanoidMobRenderer::_init(HumanoidModel *humanoidModel, float scale) { this->humanoidModel = humanoidModel; this->_scale = scale; - armorParts1 = NULL; - armorParts2 = NULL; + armorParts1 = nullptr; + armorParts2 = nullptr; createArmorParts(); } @@ -76,9 +76,9 @@ ResourceLocation *HumanoidMobRenderer::getArmorLocation(ArmorItem *armorItem, in void HumanoidMobRenderer::prepareSecondPassArmor(shared_ptr mob, int layer, float a) { shared_ptr itemInstance = mob->getArmor(3 - layer); - if (itemInstance != NULL) { + if (itemInstance != nullptr) { Item *item = itemInstance->getItem(); - if (dynamic_cast(item) != NULL) + if (dynamic_cast(item) != nullptr) { bindTexture(getArmorLocation(dynamic_cast(item), layer, true)); @@ -99,10 +99,10 @@ int HumanoidMobRenderer::prepareArmor(shared_ptr _mob, int layer, shared_ptr mob = dynamic_pointer_cast(_mob); shared_ptr itemInstance = mob->getArmor(3 - layer); - if (itemInstance != NULL) + if (itemInstance != nullptr) { Item *item = itemInstance->getItem(); - if (dynamic_cast(item) != NULL) + if (dynamic_cast(item) != nullptr) { ArmorItem *armorItem = dynamic_cast(item); bindTexture(getArmorLocation(armorItem, layer)); @@ -126,9 +126,9 @@ int HumanoidMobRenderer::prepareArmor(shared_ptr _mob, int layer, if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) { int color = armorItem->getColor(itemInstance); - float red = (float) ((color >> 16) & 0xFF) / 0xFF; - float green = (float) ((color >> 8) & 0xFF) / 0xFF; - float blue = (float) (color & 0xFF) / 0xFF; + float red = static_cast((color >> 16) & 0xFF) / 0xFF; + float green = static_cast((color >> 8) & 0xFF) / 0xFF; + float blue = static_cast(color & 0xFF) / 0xFF; glColor3f(brightness * red, brightness * green, brightness * blue); if (itemInstance->isEnchanted()) return 0x1f; @@ -171,12 +171,12 @@ void HumanoidMobRenderer::render(shared_ptr _mob, double x, double y, do ResourceLocation *HumanoidMobRenderer::getTextureLocation(shared_ptr mob) { // TODO -- Figure out of we need some data in here - return NULL; + return nullptr; } void HumanoidMobRenderer::prepareCarriedItem(shared_ptr mob, shared_ptr item) { - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != NULL ? 1 : 0; + armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != nullptr ? 1 : 0; armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = mob->isSneaking(); } @@ -187,7 +187,7 @@ void HumanoidMobRenderer::additionalRendering(shared_ptr mob, floa shared_ptr item = mob->getCarriedItem(); shared_ptr headGear = mob->getArmor(3); - if (headGear != NULL) + if (headGear != nullptr) { // don't render the pumpkin of skulls for the skins with that disabled // 4J-PB - need to disable rendering armour/skulls/pumpkins for some special skins (Daleks) @@ -199,7 +199,7 @@ void HumanoidMobRenderer::additionalRendering(shared_ptr mob, floa if (headGear->getItem()->id < 256) { - if (Tile::tiles[headGear->id] != NULL && TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) + if (Tile::tiles[headGear->id] != nullptr && TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) { float s = 10 / 16.0f; glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); @@ -226,7 +226,7 @@ void HumanoidMobRenderer::additionalRendering(shared_ptr mob, floa } } - if (item != NULL) + if (item != nullptr) { glPushMatrix(); diff --git a/Minecraft.Client/HumanoidModel.cpp b/Minecraft.Client/HumanoidModel.cpp index 05d132fae..c6c6b9f4f 100644 --- a/Minecraft.Client/HumanoidModel.cpp +++ b/Minecraft.Client/HumanoidModel.cpp @@ -8,7 +8,7 @@ ModelPart * HumanoidModel::AddOrRetrievePart(SKIN_BOX *pBox) { - ModelPart *pAttachTo=NULL; + ModelPart *pAttachTo=nullptr; switch(pBox->ePart) { @@ -37,17 +37,17 @@ ModelPart * HumanoidModel::AddOrRetrievePart(SKIN_BOX *pBox) if(pNewBox) { - if((pNewBox->getfU()!=(int)pBox->fU) || (pNewBox->getfV()!=(int)pBox->fV)) + if((pNewBox->getfU()!=static_cast(pBox->fU)) || (pNewBox->getfV()!=static_cast(pBox->fV))) { app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Box geometry was found, but with different uvs\n"); - pNewBox=NULL; + pNewBox=nullptr; } } - if(pNewBox==NULL) + if(pNewBox==nullptr) { //app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Adding box to model part\n"); - pNewBox = new ModelPart(this, (int)pBox->fU, (int)pBox->fV); + pNewBox = new ModelPart(this, static_cast(pBox->fU), static_cast(pBox->fV)); pNewBox->visible=false; pNewBox->addHumanoidBox(pBox->fX, pBox->fY, pBox->fZ, pBox->fW, pBox->fH, pBox->fD, 0); // 4J-PB - don't compile here, since the lighting isn't set up. It'll be compiled on first use. @@ -142,7 +142,7 @@ HumanoidModel::HumanoidModel(float g, float yOffset, int texWidth, int texHeight void HumanoidModel::render(shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) { - if(entity != NULL) + if(entity != nullptr) { m_uiAnimOverrideBitmask=entity->getAnimOverrideBitmask(); } diff --git a/Minecraft.Client/Input.cpp b/Minecraft.Client/Input.cpp index 1fd676836..c9b04e78f 100644 --- a/Minecraft.Client/Input.cpp +++ b/Minecraft.Client/Input.cpp @@ -84,7 +84,7 @@ void Input::tick(LocalPlayer *player) } // 4J: In flying mode, don't actually toggle sneaking (unless we're riding in which case we need to sneak to dismount) - if(!player->abilities.flying || player->riding != NULL) + if(!player->abilities.flying || player->riding != nullptr) { if((player->ullButtonsPressed&(1LL<localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SNEAK_TOGGLE)) { @@ -137,9 +137,9 @@ void Input::tick(LocalPlayer *player) float ty = 0.0f; if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_RIGHT) ) - tx = InputManager.GetJoypadStick_RX(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look + tx = InputManager.GetJoypadStick_RX(iPad)*(static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_UP) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_DOWN) ) - ty = InputManager.GetJoypadStick_RY(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look + ty = InputManager.GetJoypadStick_RY(iPad)*(static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look #ifndef _CONTENT_PACKAGE if (app.GetFreezePlayers()) tx = ty = 0.0f; @@ -166,7 +166,7 @@ void Input::tick(LocalPlayer *player) #ifdef _WINDOWS64 if (iPad == 0 && g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsKBMActive()) { - float mouseSensitivity = ((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame)) / 100.0f; + float mouseSensitivity = static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame)) / 100.0f; float mouseLookScale = 5.0f; float mx = g_KBMInput.GetLookX(mouseSensitivity * mouseLookScale); float my = g_KBMInput.GetLookY(mouseSensitivity * mouseLookScale); diff --git a/Minecraft.Client/InventoryScreen.cpp b/Minecraft.Client/InventoryScreen.cpp index 726a5e8dc..b6728533c 100644 --- a/Minecraft.Client/InventoryScreen.cpp +++ b/Minecraft.Client/InventoryScreen.cpp @@ -31,8 +31,8 @@ void InventoryScreen::renderLabels() void InventoryScreen::render(int xm, int ym, float a) { AbstractContainerScreen::render(xm, ym, a); - this->xMouse = (float)xm; - this->yMouse = (float)ym; + this->xMouse = static_cast(xm); + this->yMouse = static_cast(ym); } void InventoryScreen::renderBg(float a) diff --git a/Minecraft.Client/ItemFrameRenderer.cpp b/Minecraft.Client/ItemFrameRenderer.cpp index 2d7493ecb..55354aac8 100644 --- a/Minecraft.Client/ItemFrameRenderer.cpp +++ b/Minecraft.Client/ItemFrameRenderer.cpp @@ -33,15 +33,15 @@ void ItemFrameRenderer::render(shared_ptr _itemframe, double x, double shared_ptr itemFrame = dynamic_pointer_cast(_itemframe); glPushMatrix(); - float xOffs = (float) (itemFrame->x - x) - 0.5f; - float yOffs = (float) (itemFrame->y - y) - 0.5f; - float zOffs = (float) (itemFrame->z - z) - 0.5f; + float xOffs = static_cast(itemFrame->x - x) - 0.5f; + float yOffs = static_cast(itemFrame->y - y) - 0.5f; + float zOffs = static_cast(itemFrame->z - z) - 0.5f; int xt = itemFrame->xTile + Direction::STEP_X[itemFrame->dir]; int yt = itemFrame->yTile; int zt = itemFrame->zTile + Direction::STEP_Z[itemFrame->dir]; - glTranslatef((float) xt - xOffs, (float) yt - yOffs, (float) zt - zOffs); + glTranslatef(static_cast(xt) - xOffs, static_cast(yt) - yOffs, static_cast(zt) - zOffs); drawFrame(itemFrame); drawItem(itemFrame); @@ -110,9 +110,9 @@ void ItemFrameRenderer::drawItem(shared_ptr entity) Minecraft *pMinecraft=Minecraft::GetInstance(); shared_ptr instance = entity->getItem(); - if (instance == NULL) return; + if (instance == nullptr) return; - shared_ptr itemEntity = shared_ptr(new ItemEntity(entity->level, 0, 0, 0, instance)); + shared_ptr itemEntity = std::make_shared(entity->level, 0, 0, 0, instance); itemEntity->getItem()->count = 1; itemEntity->bobOffs = 0; @@ -154,7 +154,7 @@ void ItemFrameRenderer::drawItem(shared_ptr entity) t->end(); shared_ptr data = Item::map->getSavedData(itemEntity->getItem(), entity->level); - if (data != NULL) + if (data != nullptr) { entityRenderDispatcher->itemInHandRenderer->minimap->render(nullptr, entityRenderDispatcher->textures, data, entity->entityId); } @@ -168,7 +168,7 @@ void ItemFrameRenderer::drawItem(shared_ptr entity) double compassRotA = ct->rota; ct->rot = 0; ct->rota = 0; - ct->updateFromPosition(entity->level, entity->x, entity->z, Mth::wrapDegrees( (float)(180 + entity->dir * 90) ), false, true); + ct->updateFromPosition(entity->level, entity->x, entity->z, Mth::wrapDegrees( static_cast(180 + entity->dir * 90) ), false, true); ct->rot = compassRot; ct->rota = compassRotA; } diff --git a/Minecraft.Client/ItemInHandRenderer.cpp b/Minecraft.Client/ItemInHandRenderer.cpp index f9e635893..13d4fc20d 100644 --- a/Minecraft.Client/ItemInHandRenderer.cpp +++ b/Minecraft.Client/ItemInHandRenderer.cpp @@ -226,9 +226,9 @@ void ItemInHandRenderer::renderItem(shared_ptr mob, shared_ptrid]->getColor(item,0); + int col = Item::items[item->id]->getColor(item, layer); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; @@ -238,7 +238,7 @@ void ItemInHandRenderer::renderItem(shared_ptr mob, shared_ptrid]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != nullptr && TileRenderer::canRender(tile->getRenderShape())) { MemSect(31); minecraft->textures->bindTexture(minecraft->textures->getTextureLocation(Icon::TYPE_TERRAIN)); @@ -249,7 +249,7 @@ void ItemInHandRenderer::renderItem(shared_ptr mob, shared_ptrgetItemInHandIcon(item, layer); - if (icon == NULL) + if (icon == nullptr) { glPopMatrix(); MemSect(0); @@ -299,7 +299,7 @@ void ItemInHandRenderer::renderItem(shared_ptr mob, shared_ptrgetSourceWidth(), icon->getSourceHeight(), 1 / 16.0f, false, bIsTerrain); - if (item != NULL && item->isFoil() && layer == 0) + if (item != nullptr && item->isFoil() && layer == 0) { glDepthFunc(GL_EQUAL); glDisable(GL_LIGHTING); @@ -373,6 +373,11 @@ void ItemInHandRenderer::render(float a) float h = oHeight + (height - oHeight) * a; shared_ptr player = minecraft->player; + if (player == nullptr) + { + return; + } + // 4J - added so we can adjust the position of the hands for horizontal & vertical split screens float fudgeX = 0.0f; float fudgeY = 0.0f; @@ -425,7 +430,7 @@ void ItemInHandRenderer::render(float a) glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); } - if (item != NULL) + if (item != nullptr) { int col = Item::items[item->id]->getColor(item,0); float red = ((col >> 16) & 0xff) / 255.0f; @@ -439,7 +444,7 @@ void ItemInHandRenderer::render(float a) glColor4f(br, br, br, 1); } - if (item != NULL && item->id == Item::map->id) + if (item != nullptr && item->id == Item::map->id) { glPushMatrix(); float d = 0.8f; @@ -481,13 +486,13 @@ void ItemInHandRenderer::render(float a) glPushMatrix(); glTranslatef(-0.0f, -0.6f, 1.1f * flip); - glRotatef((float)(-45 * flip), 1, 0, 0); + glRotatef(static_cast(-45 * flip), 1, 0, 0); glRotatef(-90, 0, 0, 1); glRotatef(59, 0, 0, 1); - glRotatef((float)(-65 * flip), 0, 1, 0); + glRotatef(static_cast(-65 * flip), 0, 1, 0); EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(minecraft->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + PlayerRenderer *playerRenderer = static_cast(er); float ss = 1; glScalef(ss, ss, ss); @@ -530,20 +535,20 @@ void ItemInHandRenderer::render(float a) t->begin(); int vo = 7; t->normal(0,0,-1); - t->vertexUV((float)(0 - vo), (float)( 128 + vo), (float)( 0), (float)( 0), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 128 + vo), (float)( 0), (float)( 1), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 0 - vo), (float)( 0), (float)( 1), (float)( 0)); - t->vertexUV((float)(0 - vo), (float)( 0 - vo), (float)( 0), (float)( 0), (float)( 0)); + t->vertexUV(static_cast(0 - vo), static_cast(128 + vo), static_cast(0), static_cast(0), static_cast(1)); + t->vertexUV(static_cast(128 + vo), static_cast(128 + vo), static_cast(0), static_cast(1), static_cast(1)); + t->vertexUV(static_cast(128 + vo), static_cast(0 - vo), static_cast(0), static_cast(1), static_cast(0)); + t->vertexUV(static_cast(0 - vo), static_cast(0 - vo), static_cast(0), static_cast(0), static_cast(0)); t->end(); shared_ptr data = Item::map->getSavedData(item, minecraft->level); PIXBeginNamedEvent(0,"Minimap render"); - if(data != NULL) minimap->render(minecraft->player, minecraft->textures, data, minecraft->player->entityId); + if(data != nullptr) minimap->render(minecraft->player, minecraft->textures, data, minecraft->player->entityId); PIXEndNamedEvent(); glPopMatrix(); } - else if (item != NULL) + else if (item != nullptr) { glPushMatrix(); float d = 0.8f; @@ -617,7 +622,7 @@ void ItemInHandRenderer::render(float a) glRotatef(-8, 1, 0, 0); glTranslatef(-0.9f, 0.2f, 0.0f); float timeHeld = (item->getUseDuration() - (player->getUseItemDuration() - a + 1)); - float pow = timeHeld / (float) (BowItem::MAX_DRAW_DURATION); + float pow = timeHeld / static_cast(BowItem::MAX_DRAW_DURATION); pow = ((pow * pow) + pow * 2) / 3; if (pow > 1) pow = 1; if (pow > 0.1f) @@ -706,7 +711,7 @@ void ItemInHandRenderer::render(float a) glTranslatef(5.6f, 0, 0); EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(minecraft->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + PlayerRenderer *playerRenderer = static_cast(er); float ss = 1; glScalef(ss, ss, ss); MemSect(31); @@ -762,7 +767,7 @@ void ItemInHandRenderer::renderScreenEffect(float a) } } - if (Tile::tiles[tile] != NULL) renderTex(a, Tile::tiles[tile]->getTexture(2)); + if (Tile::tiles[tile] != nullptr) renderTex(a, Tile::tiles[tile]->getTexture(2)); } if (minecraft->player->isUnderLiquid(Material::water)) @@ -905,11 +910,11 @@ void ItemInHandRenderer::tick() shared_ptr nextTile = player->inventory->getSelected(); bool matches = lastSlot == player->inventory->selected && nextTile == selectedItem; - if (selectedItem == NULL && nextTile == NULL) + if (selectedItem == nullptr && nextTile == nullptr) { matches = true; } - if (nextTile != NULL && selectedItem != NULL && nextTile != selectedItem && nextTile->id == selectedItem->id && nextTile->getAuxValue() == selectedItem->getAuxValue()) + if (nextTile != nullptr && selectedItem != nullptr && nextTile != selectedItem && nextTile->id == selectedItem->id && nextTile->getAuxValue() == selectedItem->getAuxValue()) { selectedItem = nextTile; matches = true; diff --git a/Minecraft.Client/ItemRenderer.cpp b/Minecraft.Client/ItemRenderer.cpp index 6fb7e633d..a7a3a1bf6 100644 --- a/Minecraft.Client/ItemRenderer.cpp +++ b/Minecraft.Client/ItemRenderer.cpp @@ -65,7 +65,7 @@ void ItemRenderer::render(shared_ptr _itemEntity, double x, double y, do random->setSeed(187); shared_ptr item = itemEntity->getItem(); - if (item->getItem() == NULL) return; + if (item->getItem() == nullptr) return; glPushMatrix(); float bob = Mth::sin((itemEntity->age + a) / 10.0f + itemEntity->bobOffs) * 0.1f + 0.1f; @@ -77,12 +77,12 @@ void ItemRenderer::render(shared_ptr _itemEntity, double x, double y, do if (itemEntity->getItem()->count > 20) count = 4; if (itemEntity->getItem()->count > 40) count = 5; - glTranslatef((float) x, (float) y + bob, (float) z); + glTranslatef(static_cast(x), static_cast(y) + bob, static_cast(z)); glEnable(GL_RESCALE_NORMAL); Tile *tile = Tile::tiles[item->id]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != nullptr && TileRenderer::canRender(tile->getRenderShape())) { glRotatef(spin, 0, 1, 0); @@ -200,7 +200,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr entity, Icon *icon { Tesselator *t = Tesselator::getInstance(); - if (icon == NULL) icon = entityRenderDispatcher->textures->getMissingIcon(entity->getItem()->getIconType()); + if (icon == nullptr) icon = entityRenderDispatcher->textures->getMissingIcon(entity->getItem()->getIconType()); float u0 = icon->getU0(); float u1 = icon->getU1(); float v0 = icon->getV0(); @@ -264,7 +264,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr entity, Icon *icon glTranslatef(0, 0, width + margin); bool bIsTerrain = false; - if (item->getIconType() == Icon::TYPE_TERRAIN && Tile::tiles[item->id] != NULL) + if (item->getIconType() == Icon::TYPE_TERRAIN && Tile::tiles[item->id] != nullptr) { bIsTerrain = true; bindTexture(&TextureAtlas::LOCATION_BLOCKS); // TODO: Do this sanely by Icon @@ -279,7 +279,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr entity, Icon *icon //ItemInHandRenderer::renderItem3D(t, u1, v0, u0, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false); ItemInHandRenderer::renderItem3D(t, u0, v0, u1, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false, bIsTerrain); - if (item != NULL && item->isFoil()) + if (item != nullptr && item->isFoil()) { glDepthFunc(GL_EQUAL); glDisable(GL_LIGHTING); @@ -332,10 +332,10 @@ void ItemRenderer::renderItemBillboard(shared_ptr entity, Icon *icon glColor4f(red, green, blue, 1); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 0 - yo), static_cast(0), (float)( u0), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 0 - yo), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 1 - yo), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 1 - yo), static_cast(0), (float)( u0), (float)( v0)); t->end(); glPopMatrix(); @@ -416,7 +416,7 @@ void ItemRenderer::renderGuiItem(Font *font, Textures *textures, shared_ptr(x), static_cast(y), fillingIcon, 16, 16); } } glEnable(GL_LIGHTING); @@ -443,7 +443,7 @@ void ItemRenderer::renderGuiItem(Font *font, Textures *textures, shared_ptrgetMissingIcon(item->getIconType()); } @@ -462,7 +462,7 @@ void ItemRenderer::renderGuiItem(Font *font, Textures *textures, shared_ptr(x), static_cast(y), itemIcon, 16, 16); } glEnable(GL_LIGHTING); PIXEndNamedEvent(); @@ -475,13 +475,13 @@ void ItemRenderer::renderGuiItem(Font *font, Textures *textures, shared_ptr item, int x, int y) { - renderGuiItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f ); + renderGuiItem(font, textures, item, static_cast(x), static_cast(y), 1.0f, 1.0f ); } // 4J - this used to take x and y as ints, and no scale, alpha or foil - but this interface is now implemented as a wrapper round this more fully featured one void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const shared_ptr item, float x, float y,float fScale,float fAlpha, bool isFoil) { - if(item==NULL) return; + if(item==nullptr) return; renderAndDecorateItem(font, textures, item, x, y,fScale, fScale, fAlpha, isFoil, true); } @@ -489,7 +489,7 @@ void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const s // (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 item, float x, float y,float fScaleX, float fScaleY,float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled) { - if (item == NULL) + if (item == nullptr) { return; } @@ -535,7 +535,7 @@ void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const s // 4J - original interface, now just a wrapper for preceding overload void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const shared_ptr item, int x, int y) { - renderAndDecorateItem( font, textures, item, (float)x, (float)y, 1.0f, 1.0f, item->isFoil() ); + renderAndDecorateItem( font, textures, item, static_cast(x), static_cast(y), 1.0f, 1.0f, item->isFoil() ); } // 4J - a few changes here to get x, y, w, h in as floats (for xui rendering accuracy), and to align @@ -546,8 +546,8 @@ void ItemRenderer::blitGlint(int id, float x, float y, float w, float h) float vs = 1.0f / 64.0f / 4; // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; + float sfx = static_cast(Minecraft::GetInstance()->width) / static_cast(Minecraft::GetInstance()->width_phys); + float sfy = static_cast(Minecraft::GetInstance()->height) / static_cast(Minecraft::GetInstance()->height_phys); float xx0 = x * sfx; float xx1 = ( x + w ) * sfx; float yy0 = y * sfy; @@ -593,7 +593,7 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, shar void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, shared_ptr item, int x, int y, const wstring &countText, float fAlpha) { - if (item == NULL) + if (item == nullptr) { return; } @@ -617,15 +617,15 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, shar MemSect(0); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); - font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, 0xffffff |(((unsigned int)(fAlpha * 0xff))<<24)); + font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, 0xffffff |(static_cast(fAlpha * 0xff)<<24)); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); } if (item->isDamaged()) { - int p = (int) Math::round(13.0 - (double) item->getDamageValue() * 13.0 / (double) item->getMaxDamage()); - int cc = (int) Math::round(255.0 - (double) item->getDamageValue() * 255.0 / (double) item->getMaxDamage()); + int p = static_cast(Math::round(13.0 - (double)item->getDamageValue() * 13.0 / (double)item->getMaxDamage())); + int cc = static_cast(Math::round(255.0 - (double)item->getDamageValue() * 255.0 / (double)item->getMaxDamage())); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); @@ -676,10 +676,10 @@ void ItemRenderer::fillRect(Tesselator *t, int x, int y, int w, int h, int c) { t->begin(); t->color(c); - t->vertex((float)(x + 0), (float)( y + 0), (float)( 0)); - t->vertex((float)(x + 0), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + 0), (float)( 0)); + t->vertex(static_cast(x + 0), static_cast(y + 0), static_cast(0)); + t->vertex(static_cast(x + 0), static_cast(y + h), static_cast(0)); + t->vertex(static_cast(x + w), static_cast(y + h), static_cast(0)); + t->vertex(static_cast(x + w), static_cast(y + 0), static_cast(0)); t->end(); } @@ -693,8 +693,8 @@ void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) t->begin(); // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; + float sfx = static_cast(Minecraft::GetInstance()->width) / static_cast(Minecraft::GetInstance()->width_phys); + float sfy = static_cast(Minecraft::GetInstance()->height) / static_cast(Minecraft::GetInstance()->height_phys); float xx0 = x * sfx; float xx1 = ( x + w ) * sfx; float yy0 = y * sfy; @@ -716,7 +716,7 @@ void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) float yy1f = yy1 / sfy; // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + float f = ( 0.5f * static_cast(Minecraft::GetInstance()->width) ) / static_cast(Minecraft::GetInstance()->width_phys); t->vertexUV(xx0f, yy1f, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 16) * vs)); t->vertexUV(xx1f, yy1f, (float)( blitOffset), (float)( (sx + 16) * us), (float)( (sy + 16) * vs)); @@ -731,8 +731,8 @@ void ItemRenderer::blit(float x, float y, Icon *tex, float w, float h) t->begin(); // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; + float sfx = static_cast(Minecraft::GetInstance()->width) / static_cast(Minecraft::GetInstance()->width_phys); + float sfy = static_cast(Minecraft::GetInstance()->height) / static_cast(Minecraft::GetInstance()->height_phys); float xx0 = x * sfx; float xx1 = ( x + w ) * sfx; float yy0 = y * sfy; @@ -754,7 +754,7 @@ void ItemRenderer::blit(float x, float y, Icon *tex, float w, float h) float yy1f = yy1 / sfy; // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + float f = ( 0.5f * static_cast(Minecraft::GetInstance()->width) ) / static_cast(Minecraft::GetInstance()->width_phys); t->vertexUV(xx0f, yy1f, blitOffset, tex->getU0(true), tex->getV1(true)); t->vertexUV(xx1f, yy1f, blitOffset, tex->getU1(true), tex->getV1(true)); diff --git a/Minecraft.Client/ItemSpriteRenderer.cpp b/Minecraft.Client/ItemSpriteRenderer.cpp index 5f1c7089b..afe8023ee 100644 --- a/Minecraft.Client/ItemSpriteRenderer.cpp +++ b/Minecraft.Client/ItemSpriteRenderer.cpp @@ -22,14 +22,14 @@ void ItemSpriteRenderer::render(shared_ptr e, double x, double y, double { // the icon is already cached in the item object, so there should not be any performance impact by not caching it here Icon *icon = sourceItem->getIcon(sourceItemAuxValue); - if (icon == NULL) + if (icon == nullptr) { return; } glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); bindTexture(e); @@ -72,10 +72,10 @@ void ItemSpriteRenderer::renderIcon(Tesselator *t, Icon *icon) glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( r - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( r - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( 0 - yo), static_cast(0), (float)( u0), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( 0 - yo), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV((float)(r - xo), (float)( r - yo), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)( r - yo), static_cast(0), (float)( u0), (float)( v0)); t->end(); } diff --git a/Minecraft.Client/JoinMultiplayerScreen.cpp b/Minecraft.Client/JoinMultiplayerScreen.cpp index a98e7bee1..f8e13fbbf 100644 --- a/Minecraft.Client/JoinMultiplayerScreen.cpp +++ b/Minecraft.Client/JoinMultiplayerScreen.cpp @@ -7,7 +7,7 @@ JoinMultiplayerScreen::JoinMultiplayerScreen(Screen *lastScreen) { - ipEdit = NULL; + ipEdit = nullptr; this->lastScreen = lastScreen; } @@ -55,7 +55,7 @@ void JoinMultiplayerScreen::buttonClicked(Button *button) vector parts = stringSplit(ip,L'L'); if (ip[0]==L'[') { - int pos = (int)ip.find(L"]"); + size_t pos = ip.find(L"]"); if (pos != wstring::npos) { wstring path = ip.substr(1, pos); diff --git a/Minecraft.Client/LavaParticle.cpp b/Minecraft.Client/LavaParticle.cpp index ac0608e59..0ff9b1b06 100644 --- a/Minecraft.Client/LavaParticle.cpp +++ b/Minecraft.Client/LavaParticle.cpp @@ -15,7 +15,7 @@ LavaParticle::LavaParticle(Level *level, double x, double y, double z) : Particl size *= (random->nextFloat() * 2 + 0.2f); oSize = size; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(16 / (Math::random() * 0.8 + 0.2)); noPhysics = false; setMiscTex(49); } @@ -40,7 +40,7 @@ float LavaParticle::getBrightness(float a) void LavaParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; + float s = (age + a) / static_cast(lifetime); size = oSize * (1 - s*s); Particle::render(t, a, xa, ya, za, xa2, za2); } @@ -52,7 +52,7 @@ void LavaParticle::tick() zo = z; if (age++ >= lifetime) remove(); - float odds = age / (float) lifetime; + float odds = age / static_cast(lifetime); if (random->nextFloat() > odds) level->addParticle(eParticleType_smoke, x, y, z, xd, yd, zd); yd -= 0.03; diff --git a/Minecraft.Client/LavaSlimeModel.cpp b/Minecraft.Client/LavaSlimeModel.cpp index 052850f81..0f9d6a435 100644 --- a/Minecraft.Client/LavaSlimeModel.cpp +++ b/Minecraft.Client/LavaSlimeModel.cpp @@ -22,7 +22,7 @@ LavaSlimeModel::LavaSlimeModel() v = 19; } bodyCubes[i] = new ModelPart(this, u, v); - bodyCubes[i]->addBox(-4.0f, 16.0f + (float)i, -4.0f, 8, 1, 8); + bodyCubes[i]->addBox(-4.0f, 16.0f + static_cast(i), -4.0f, 8, 1, 8); } insideCube = new ModelPart(this, 0, 16); diff --git a/Minecraft.Client/LavaSlimeRenderer.cpp b/Minecraft.Client/LavaSlimeRenderer.cpp index e828a353b..3d5858eae 100644 --- a/Minecraft.Client/LavaSlimeRenderer.cpp +++ b/Minecraft.Client/LavaSlimeRenderer.cpp @@ -7,7 +7,7 @@ ResourceLocation LavaSlimeRenderer::MAGMACUBE_LOCATION = ResourceLocation(TN_MOB LavaSlimeRenderer::LavaSlimeRenderer() : MobRenderer(new LavaSlimeModel(), .25f) { - this->modelVersion = ((LavaSlimeModel *) model)->getModelVersion(); + this->modelVersion = static_cast(model)->getModelVersion(); } ResourceLocation *LavaSlimeRenderer::getTextureLocation(shared_ptr mob) diff --git a/Minecraft.Client/LeashKnotRenderer.cpp b/Minecraft.Client/LeashKnotRenderer.cpp index b210379fc..3c58ce522 100644 --- a/Minecraft.Client/LeashKnotRenderer.cpp +++ b/Minecraft.Client/LeashKnotRenderer.cpp @@ -19,7 +19,7 @@ void LeashKnotRenderer::render(shared_ptr entity, double x, double y, do glPushMatrix(); glDisable(GL_CULL_FACE); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); float scale = 1 / 16.0f; glEnable(GL_RESCALE_NORMAL); diff --git a/Minecraft.Client/LevelRenderer.cpp b/Minecraft.Client/LevelRenderer.cpp index 594ff4ea9..cf2937f4f 100644 --- a/Minecraft.Client/LevelRenderer.cpp +++ b/Minecraft.Client/LevelRenderer.cpp @@ -112,12 +112,12 @@ const int LevelRenderer::DIMENSION_OFFSETS[3] = { 0, (80 * 80 * CHUNK_Y_COUNT) , LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) { - breakingTextures = NULL; + breakingTextures = nullptr; for( int i = 0; i < 4; i++ ) { - level[i] = NULL; - tileRenderer[i] = NULL; + level[i] = nullptr; + tileRenderer[i] = nullptr; xOld[i] = -9999; yOld[i] = -9999; zOld[i] = -9999; @@ -143,7 +143,7 @@ LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) totalChunks= offscreenChunks= occludedChunks= renderedChunks= emptyChunks = 0; for( int i = 0; i < 4; i++ ) { - // sortedChunks[i] = NULL; // 4J - removed - not sorting our chunks anymore + // sortedChunks[i] = nullptr; // 4J - removed - not sorting our chunks anymore chunks[i] = ClipChunkArray(); lastPlayerCount[i] = 0; } @@ -185,16 +185,16 @@ LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) float yy; int s = 64; int d = 256 / s + 2; - yy = (float) 16; + yy = static_cast(16); for (int xx = -s * d; xx <= s * d; xx += s) { for (int zz = -s * d; zz <= s * d; zz += s) { t->begin(); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); + t->vertex(static_cast(xx + 0), (float)( yy), static_cast(zz + 0)); + t->vertex(static_cast(xx + s), (float)( yy), static_cast(zz + 0)); + t->vertex(static_cast(xx + s), (float)( yy), static_cast(zz + s)); + t->vertex(static_cast(xx + 0), (float)( yy), static_cast(zz + s)); t->end(); } } @@ -202,16 +202,16 @@ LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) darkList = starList + 2; glNewList(darkList, GL_COMPILE); - yy = -(float) 16; + yy = -static_cast(16); t->begin(); for (int xx = -s * d; xx <= s * d; xx += s) { for (int zz = -s * d; zz <= s * d; zz += s) { - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); + t->vertex(static_cast(xx + s), (float)( yy), static_cast(zz + 0)); + t->vertex(static_cast(xx + 0), (float)( yy), static_cast(zz + 0)); + t->vertex(static_cast(xx + 0), (float)( yy), static_cast(zz + s)); + t->vertex(static_cast(xx + s), (float)( yy), static_cast(zz + s)); } } t->end(); @@ -313,7 +313,7 @@ void LevelRenderer::renderStars() double yo = _yo; double zo = _zo * ySin + _xo * yCos; - t->vertex((float)(xp + xo), (float)( yp + yo), (float)( zp + zo)); + t->vertex(static_cast(xp + xo), static_cast(yp + yo), static_cast(zp + zo)); } } } @@ -324,7 +324,7 @@ void LevelRenderer::renderStars() void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) { - if (this->level[playerIndex] != NULL) + if (this->level[playerIndex] != nullptr) { // Remove listener for this level if this is the last player referencing it Level *prevLevel = this->level[playerIndex]; @@ -344,12 +344,12 @@ void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) zOld[playerIndex] = -9999; this->level[playerIndex] = level; - if( tileRenderer[playerIndex] != NULL ) + if( tileRenderer[playerIndex] != nullptr ) { delete tileRenderer[playerIndex]; } tileRenderer[playerIndex] = new TileRenderer(level); - if (level != NULL) + if (level != nullptr) { // If we're the only player referencing this level, add a new listener for it int refCount = 0; @@ -367,7 +367,7 @@ void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) else { // printf("NULLing player %d, chunks @ 0x%x\n",playerIndex,chunks[playerIndex]); - if( chunks[playerIndex].data != NULL ) + if( chunks[playerIndex].data != nullptr ) { for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { @@ -375,21 +375,21 @@ void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) delete chunks[playerIndex][i].chunk; } delete chunks[playerIndex].data; - chunks[playerIndex].data = NULL; + chunks[playerIndex].data = nullptr; chunks[playerIndex].length = 0; // delete sortedChunks[playerIndex]; // 4J - removed - not sorting our chunks anymore - // sortedChunks[playerIndex] = NULL; // 4J - removed - not sorting our chunks anymore + // sortedChunks[playerIndex] = nullptr; // 4J - removed - not sorting our chunks anymore } // 4J Stu - If we do this for splitscreen players leaving, then all the tile entities in the world dissappear - // We should only do this when actually exiting the game, so only when the primary player sets there level to NULL + // We should only do this when actually exiting the game, so only when the primary player sets there level to nullptr if(playerIndex == ProfileManager.GetPrimaryPad()) renderableTileEntities.clear(); } } void LevelRenderer::AddDLCSkinsToMemTextures() { - for(int i=0;iaddMemTexture(app.vSkinNames[i], new MobSkinMemTextureProcessor()); } @@ -417,7 +417,7 @@ void LevelRenderer::allChanged(int playerIndex) // If this CS is entered before DisableUpdateThread is called then (on 360 at least) we can get a // deadlock when starting a game in splitscreen. //EnterCriticalSection(&m_csDirtyChunks); - if( level == NULL ) + if( level == nullptr ) { return; } @@ -431,7 +431,7 @@ void LevelRenderer::allChanged(int playerIndex) int realrenderArea = (realviewDistance * realviewDistance * 4); // Calculate size of area we can render based on number of players we need to render for - int dist = (int)sqrtf( (float)realrenderArea / (float)activePlayers() ); + int dist = static_cast(sqrtf(static_cast(realrenderArea) / static_cast(activePlayers()))); // AP - poor little Vita just can't cope with such a big area #ifdef __PSVITA__ @@ -444,7 +444,7 @@ void LevelRenderer::allChanged(int playerIndex) yChunks = Level::maxBuildHeight / CHUNK_SIZE; zChunks = dist; - if( chunks[playerIndex].data != NULL ) + if( chunks[playerIndex].data != nullptr ) { for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { @@ -467,7 +467,7 @@ void LevelRenderer::allChanged(int playerIndex) yMaxChunk = yChunks; 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 + // 4J removed - we now only fully clear this on exiting the game (setting level to nullptr). Apart from that, the chunk rebuilding is responsible for maintaining this // renderableTileEntities.clear(); for (int x = 0; x < xChunks; x++) @@ -487,10 +487,10 @@ void LevelRenderer::allChanged(int playerIndex) } nonStackDirtyChunksAdded(); - if (level != NULL) + if (level != nullptr) { shared_ptr player = mc->cameraTargetPlayer; - if (player != NULL) + if (player != nullptr) { this->resortChunks(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks anymore @@ -507,6 +507,11 @@ void LevelRenderer::allChanged(int playerIndex) void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) { + if (mc == nullptr || mc->player == nullptr) + { + return; + } + int playerIndex = mc->player->GetXboxPad(); // 4J added // 4J Stu - Set these up every time, even when not rendering as other things (like particle render) may depend on it for those frames. @@ -524,6 +529,10 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) culledEntities = 0; shared_ptr player = mc->cameraTargetPlayer; + if (player == nullptr) + { + return; + } EntityRenderDispatcher::xOff = (player->xOld + (player->x - player->xOld) * a); EntityRenderDispatcher::yOff = (player->yOld + (player->y - player->yOld) * a); @@ -535,7 +544,7 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) mc->gameRenderer->turnOnLightLayer(a); // 4J - brought forward from 1.8.2 vector > entities = level[playerIndex]->getAllEntities(); - totalEntities = (int)entities.size(); + totalEntities = static_cast(entities.size()); for (auto& entity : level[playerIndex]->globalEntities) { @@ -552,7 +561,7 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) if ( !shouldRender && entity->instanceof(eTYPE_MOB) ) { shared_ptr mob = dynamic_pointer_cast(entity); - if ( mob->isLeashed() && (mob->getLeashHolder() != NULL) ) + if ( mob->isLeashed() && (mob->getLeashHolder() != nullptr) ) { shared_ptr leashHolder = mob->getLeashHolder(); shouldRender = culler->isVisible(leashHolder->bb); @@ -734,7 +743,7 @@ int LevelRenderer::render(shared_ptr player, int layer, double alp } Lighting::turnOff(); - int count = renderChunks(0, (int)chunks[playerIndex].length, layer, alpha); + int count = renderChunks(0, static_cast(chunks[playerIndex].length), layer, alpha); return count; @@ -759,18 +768,27 @@ int compare (const void * a, const void * b) int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) { + if (mc == nullptr || mc->player == nullptr) + { + return 0; + } + int playerIndex = mc->player->GetXboxPad(); // 4J added #if 1 // 4J - cut down version, we're not using offsetted render lists, or a sorted chunk list, anymore mc->gameRenderer->turnOnLightLayer(alpha); // 4J - brought forward from 1.8.2 shared_ptr player = mc->cameraTargetPlayer; + if (player == nullptr) + { + return 0; + } double xOff = player->xOld + (player->x - player->xOld) * alpha; double yOff = player->yOld + (player->y - player->yOld) * alpha; double zOff = player->zOld + (player->z - player->zOld) * alpha; glPushMatrix(); - glTranslatef((float)-xOff, (float)-yOff, (float)-zOff); + glTranslatef(static_cast(-xOff), static_cast(-yOff), static_cast(-zOff)); #ifdef __PSVITA__ // AP - also set the camera position so we can work out if a chunk is fogged or not @@ -995,9 +1013,9 @@ void LevelRenderer::renderSky(float alpha) int playerIndex = mc->player->GetXboxPad(); Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + float sr = static_cast(sc->x); + float sg = static_cast(sc->y); + float sb = static_cast(sc->z); if (mc->options->anaglyph3d) { @@ -1032,7 +1050,7 @@ void LevelRenderer::renderSky(float alpha) Lighting::turnOff(); float *c = level[playerIndex]->dimension->getSunriseColor(level[playerIndex]->getTimeOfDay(alpha), alpha); - if (c != NULL) + if (c != nullptr) { glDisable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); @@ -1060,7 +1078,7 @@ void LevelRenderer::renderSky(float alpha) t->begin(GL_TRIANGLE_FAN); t->color(r, g, b, c[3]); - t->vertex((float)(0), (float)( 100), (float)( 0)); + t->vertex(static_cast(0), static_cast(100), static_cast(0)); int steps = 16; t->color(c[0], c[1], c[2], 0.0f); for (int i = 0; i <= steps; i++) @@ -1094,10 +1112,10 @@ void LevelRenderer::renderSky(float alpha) textures->bindTexture(&SUN_LOCATION); MemSect(0); t->begin(); - t->vertexUV((float)(-ss), (float)( 100), (float)( -ss), (float)( 0), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( -ss), (float)( 1), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( +ss), (float)( 1), (float)( 1)); - t->vertexUV((float)(-ss), (float)( 100), (float)( +ss), (float)( 0), (float)( 1)); + t->vertexUV((float)(-ss), static_cast(100), (float)( -ss), static_cast(0), static_cast(0)); + t->vertexUV((float)(+ss), static_cast(100), (float)( -ss), static_cast(1), static_cast(0)); + t->vertexUV((float)(+ss), static_cast(100), (float)( +ss), static_cast(1), static_cast(1)); + t->vertexUV((float)(-ss), static_cast(100), (float)( +ss), static_cast(0), static_cast(1)); t->end(); ss = 20; @@ -1142,7 +1160,7 @@ void LevelRenderer::renderSky(float alpha) if (yy < 0) { glPushMatrix(); - glTranslatef(0, -(float) (-12), 0); + glTranslatef(0, -static_cast(-12), 0); glCallList(darkList); glPopMatrix(); @@ -1193,7 +1211,7 @@ void LevelRenderer::renderSky(float alpha) glColor3f(sr, sg, sb); } glPushMatrix(); - glTranslatef(0, -(float) (yy - 16), 0); + glTranslatef(0, -static_cast(yy - 16), 0); glCallList(darkList); glPopMatrix(); glEnable(GL_TEXTURE_2D); @@ -1214,9 +1232,9 @@ void LevelRenderer::renderHaloRing(float alpha) int playerIndex = mc->player->GetXboxPad(); Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + float sr = static_cast(sc->x); + float sg = static_cast(sc->y); + float sb = static_cast(sc->z); // Rough lumninance calculation float Y = (sr+sr+sb+sg+sg+sg)/6; @@ -1279,7 +1297,7 @@ void LevelRenderer::renderClouds(float alpha) } } glDisable(GL_CULL_FACE); - float yOffs = (float) (mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); + float yOffs = static_cast(mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); int s = 32; int d = 256 / s; Tesselator *t = Tesselator::getInstance(); @@ -1289,9 +1307,9 @@ void LevelRenderer::renderClouds(float alpha) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + float cr = static_cast(cc->x); + float cg = static_cast(cc->y); + float cb = static_cast(cc->z); if (mc->options->anaglyph3d) { @@ -1317,8 +1335,8 @@ void LevelRenderer::renderClouds(float alpha) zo -= zOffs * 2048; float yy = (float) (level[playerIndex]->dimension->getCloudHeight() - yOffs + 0.33f); - float uo = (float) (xo * scale); - float vo = (float) (zo * scale); + float uo = static_cast(xo * scale); + float vo = static_cast(zo * scale); t->begin(); t->color(cr, cg, cb, 0.8f); @@ -1326,10 +1344,10 @@ void LevelRenderer::renderClouds(float alpha) { for (int zz = -s * d; zz < +s * d; zz += s) { - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + s), (float)( (xx + 0) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + s), (float)( (xx + s) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + 0), (float)( (xx + s) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); + t->vertexUV(static_cast(xx + 0), (float)( yy), static_cast(zz + s), (float)( (xx + 0) * scale + uo), (float)( (zz + s) * scale + vo)); + t->vertexUV(static_cast(xx + s), (float)( yy), static_cast(zz + s), (float)( (xx + s) * scale + uo), (float)( (zz + s) * scale + vo)); + t->vertexUV(static_cast(xx + s), (float)( yy), static_cast(zz + 0), (float)( (xx + s) * scale + uo), (float)( (zz + 0) * scale + vo)); + t->vertexUV(static_cast(xx + 0), (float)( yy), static_cast(zz + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); } } t->end(); @@ -1376,13 +1394,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(0.7f, 0.7f, 0.7f, 0.8f); t->normal(0, -1, 0); @@ -1401,13 +1419,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(1.0f, 1.0f, 1.0f, 0.8f); t->normal(0, 1, 0); @@ -1426,13 +1444,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(0.9f, 0.9f, 0.9f, 0.8f); t->normal(-1, 0, 0); @@ -1451,13 +1469,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(0.9f, 0.9f, 0.9f, 0.8f); t->normal(1, 0, 0); @@ -1476,13 +1494,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(0.8f, 0.8f, 0.8f, 0.8f); t->normal(-1, 0, 0); @@ -1501,13 +1519,13 @@ void LevelRenderer::createCloudMesh() { for( int xt = 0; xt < D; xt++ ) { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; + float u = (static_cast(xt) + 0.5f ) / 256.0f; + float v = (static_cast(zt) + 0.5f ) / 256.0f; + float x0 = static_cast(xt); float x1 = x0 + 1.0f; float y0 = 0; float y1 = h; - float z0 = (float)zt; + float z0 = static_cast(zt); float z1 = z0 + 1.0f; t->color(0.8f, 0.8f, 0.8f, 0.8f); t->normal(1, 0, 0); @@ -1532,7 +1550,7 @@ void LevelRenderer::renderAdvancedClouds(float alpha) // 4J - most of our viewports are now rendered with no clip planes but using stencilling to limit the area drawn to. Clouds have a relatively large fill area compared to // the number of vertices that they have, and so enabling clipping here to try and reduce fill rate cost. RenderManager.StateSetEnableViewportClipPlanes(true); - float yOffs = (float) (mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); + float yOffs = static_cast(mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); Tesselator *t = Tesselator::getInstance(); int playerIndex = mc->player->GetXboxPad(); @@ -1582,9 +1600,9 @@ void LevelRenderer::renderAdvancedClouds(float alpha) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + float cr = static_cast(cc->x); + float cg = static_cast(cc->y); + float cb = static_cast(cc->z); if (mc->options->anaglyph3d) { @@ -1597,19 +1615,19 @@ void LevelRenderer::renderAdvancedClouds(float alpha) cb = cbb; } - float uo = (float) (xo * 0); - float vo = (float) (zo * 0); + float uo = static_cast(xo * 0); + float vo = static_cast(zo * 0); float scale = 1 / 256.0f; - uo = (float) (Mth::floor(xo)) * scale; - vo = (float) (Mth::floor(zo)) * scale; + uo = static_cast(Mth::floor(xo)) * scale; + vo = static_cast(Mth::floor(zo)) * scale; // 4J - keep our UVs +ve - there's a small bug in the xbox GPU that incorrectly rounds small -ve UVs (between -1/(64*size) and 0) up to 0, which leaves gaps in our clouds... while( uo < 1.0f ) uo += 1.0f; while( vo < 1.0f ) vo += 1.0f; - float xoffs = (float) (xo - Mth::floor(xo)); - float zoffs = (float) (zo - Mth::floor(zo)); + float xoffs = static_cast(xo - Mth::floor(xo)); + float zoffs = static_cast(zo - Mth::floor(zo)); int D = 8; @@ -1639,8 +1657,8 @@ void LevelRenderer::renderAdvancedClouds(float alpha) // 4J - reimplemented the clouds with full cube-per-texel geometry to get rid of seams. This is a huge amount more quads to render, so // now using command buffers to render each section to cut CPU hit. #if 1 - float xx = (float)(xPos * D); - float zz = (float)(zPos * D); + float xx = static_cast(xPos * D); + float zz = static_cast(zPos * D); float xp = xx - xoffs; float zp = zz - zoffs; @@ -1818,7 +1836,7 @@ bool LevelRenderer::updateDirtyChunks() std::list< std::pair > nearestClipChunks; #endif - ClipChunk *nearChunk = NULL; // Nearest chunk that is dirty + ClipChunk *nearChunk = nullptr; // Nearest chunk that is dirty int veryNearCount = 0; int minDistSq = 0x7fffffff; // Distances to this chunk @@ -1833,7 +1851,7 @@ bool LevelRenderer::updateDirtyChunks() } throttle++; */ - PIXAddNamedCounter(((float)memAlloc)/(1024.0f*1024.0f),"Command buffer allocations"); + PIXAddNamedCounter(static_cast(memAlloc)/(1024.0f*1024.0f),"Command buffer allocations"); bool onlyRebuild = ( memAlloc >= MAX_COMMANDBUFFER_ALLOCATIONS ); EnterCriticalSection(&m_csDirtyChunks); @@ -1896,15 +1914,15 @@ bool LevelRenderer::updateDirtyChunks() g_findNearestChunkDataIn.chunks[i] = (LevelRenderer_FindNearestChunk_DataIn::ClipChunk*)chunks[i].data; g_findNearestChunkDataIn.chunkLengths[i] = chunks[i].length; g_findNearestChunkDataIn.level[i] = level[i]; - g_findNearestChunkDataIn.playerData[i].bValid = mc->localplayers[i] != NULL; - if(mc->localplayers[i] != NULL) + g_findNearestChunkDataIn.playerData[i].bValid = mc->localplayers[i] != nullptr; + if(mc->localplayers[i] != nullptr) { g_findNearestChunkDataIn.playerData[i].x = mc->localplayers[i]->x; g_findNearestChunkDataIn.playerData[i].y = mc->localplayers[i]->y; g_findNearestChunkDataIn.playerData[i].z = mc->localplayers[i]->z; } - if(level[i] != NULL) + if(level[i] != nullptr) { g_findNearestChunkDataIn.multiplayerChunkCache[i].XZOFFSET = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZOFFSET; g_findNearestChunkDataIn.multiplayerChunkCache[i].XZSIZE = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZSIZE; @@ -1928,16 +1946,16 @@ bool LevelRenderer::updateDirtyChunks() // Find nearest chunk that is dirty for( int p = 0; p < XUSER_MAX_COUNT; p++ ) { - // It's possible that the localplayers member can be set to NULL on the main thread when a player chooses to exit the game + // It's possible that the localplayers member can be set to nullptr 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 player = mc->localplayers[p]; - if( player == NULL ) continue; - if( chunks[p].data == NULL ) continue; - if( level[p] == NULL ) continue; + if( player == nullptr ) continue; + if( chunks[p].data == nullptr ) continue; + if( level[p] == nullptr ) 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 px = static_cast(player->x); + int py = static_cast(player->y); + int pz = static_cast(player->z); // app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} ",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, xChunks, zChunks); @@ -2036,7 +2054,7 @@ bool LevelRenderer::updateDirtyChunks() - Chunk *chunk = NULL; + Chunk *chunk = nullptr; #ifdef _LARGE_WORLDS if(!nearestClipChunks.empty()) { @@ -2187,7 +2205,7 @@ void LevelRenderer::renderHit(shared_ptr player, HitResult *h, int mode, glEnable(GL_ALPHA_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glColor4f(1, 1, 1, ((float) (Mth::sin(Minecraft::currentTimeMillis() / 100.0f)) * 0.2f + 0.4f) * 0.5f); - if (mode != 0 && inventoryItem != NULL) + if (mode != 0 && inventoryItem != nullptr) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); float br = (Mth::sin(Minecraft::currentTimeMillis() / 100.0f) * 0.2f + 0.8f); @@ -2226,7 +2244,7 @@ void LevelRenderer::renderDestroyAnimation(Tesselator *t, shared_ptr pla // so just add on a little bit of y to fix this. hacky hacky t->offset((float)-xo, (float)-yo + 0.01f,(float) -zo); #else - t->offset((float)-xo, (float)-yo,(float) -zo); + t->offset(static_cast(-xo), static_cast(-yo),static_cast(-zo)); #endif t->noColor(); @@ -2242,8 +2260,8 @@ void LevelRenderer::renderDestroyAnimation(Tesselator *t, shared_ptr pla { int iPad = mc->player->GetXboxPad(); // 4J added int tileId = level[iPad]->getTile(block->getX(), block->getY(), block->getZ()); - Tile *tile = tileId > 0 ? Tile::tiles[tileId] : NULL; - if (tile == NULL) tile = Tile::stone; + Tile *tile = tileId > 0 ? Tile::tiles[tileId] : nullptr; + if (tile == nullptr) tile = Tile::stone; tileRenderer[iPad]->tesselateInWorldFixedTexture(tile, block->getX(), block->getY(), block->getZ(), breakingTextures[block->getProgress()]); // 4J renamed to differentiate from tesselateInWorld } ++it; @@ -2303,30 +2321,30 @@ void LevelRenderer::render(AABB *b) Tesselator *t = Tesselator::getInstance(); t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); + t->vertex(static_cast(b->x0), static_cast(b->y0), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y0), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y0), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y0), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y0), static_cast(b->z0)); t->end(); t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); + t->vertex(static_cast(b->x0), static_cast(b->y1), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y1), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y1), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y1), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y1), static_cast(b->z0)); t->end(); t->begin(GL_LINES); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y0), static_cast(b->z0)); + t->vertex(static_cast(b->x0), static_cast(b->y1), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y0), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y1), static_cast(b->z0)); + t->vertex(static_cast(b->x1), static_cast(b->y0), static_cast(b->z1)); + t->vertex(static_cast(b->x1), static_cast(b->y1), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y0), static_cast(b->z1)); + t->vertex(static_cast(b->x0), static_cast(b->y1), static_cast(b->z1)); t->end(); } @@ -2334,7 +2352,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 == nullptr ) level = this->level[mc->player->GetXboxPad()]; // EnterCriticalSection(&m_csDirtyChunks); int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); @@ -2355,7 +2373,7 @@ void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Lev // These chunks are then added to the global flags in the render update thread. // An XLockFreeQueue actually implements a queue of pointers to its templated type, and I don't want to have to go allocating ints here just to store the // pointer to them in a queue. Hence actually pretending that the int Is a pointer here. Our Index has a a valid range from 0 to something quite big, - // but including zero. The lock free queue, since it thinks it is dealing with pointers, uses a NULL pointer to signify that a Pop hasn't succeeded. + // but including zero. The lock free queue, since it thinks it is dealing with pointers, uses a nullptr pointer to signify that a Pop hasn't succeeded. // We also want to reserve one special value (of 1 ) for use when multiple chunks not individually listed are made dirty. Therefore adding 2 to our // index value here to move our valid range from 1 to something quite big + 2 if( index > -1 ) @@ -2413,12 +2431,12 @@ void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Lev void LevelRenderer::tileChanged(int x, int y, int z) { - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, nullptr); } void LevelRenderer::tileLightChanged(int x, int y, int z) { - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, nullptr); } void LevelRenderer::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) // 4J - added level param @@ -2532,7 +2550,7 @@ void LevelRenderer::cull(Culler *culler, float a) #endif // __PS3__ - FrustumCuller *fc = (FrustumCuller *)culler; + FrustumCuller *fc = static_cast(culler); FrustumData *fd = fc->frustum; float fdraw[6 * 4]; for( int i = 0; i < 6; i++ ) @@ -2540,10 +2558,10 @@ void LevelRenderer::cull(Culler *culler, float a) double fx = fd->m_Frustum[i][0]; double fy = fd->m_Frustum[i][1]; double fz = fd->m_Frustum[i][2]; - fdraw[i * 4 + 0] = (float)fx; - fdraw[i * 4 + 1] = (float)fy; - fdraw[i * 4 + 2] = (float)fz; - fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + ( fx * -fc->xOff ) + ( fy * - fc->yOff ) + ( fz * -fc->zOff )); + fdraw[i * 4 + 0] = static_cast(fx); + fdraw[i * 4 + 1] = static_cast(fy); + fdraw[i * 4 + 2] = static_cast(fz); + fdraw[i * 4 + 3] = static_cast(fd->m_Frustum[i][3] + (fx * -fc->xOff) + (fy * -fc->yOff) + (fz * -fc->zOff)); } ClipChunk *pClipChunk = chunks[playerIndex].data; @@ -2582,7 +2600,7 @@ void LevelRenderer::playStreamingMusic(const wstring& name, int x, int y, int z) { mc->gui->setNowPlaying(L"C418 - " + name); } - mc->soundEngine->playStreaming(name, (float) x, (float) y, (float) z, 1, 1); + mc->soundEngine->playStreaming(name, static_cast(x), static_cast(y), static_cast(z), 1, 1); } void LevelRenderer::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist) @@ -2625,7 +2643,7 @@ void LevelRenderer::playSoundExceptPlayer(shared_ptr player, int iSound, /* void LevelRenderer::addParticle(const wstring& name, double x, double y, double z, double xa, double ya, double za) { -if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) return; +if (mc == nullptr || mc->cameraTargetPlayer == nullptr || mc->particleEngine == nullptr) return; double xd = mc->cameraTargetPlayer->x - x; double yd = mc->cameraTargetPlayer->y - y; @@ -2661,7 +2679,7 @@ void LevelRenderer::addParticle(ePARTICLE_TYPE eParticleType, double x, double y shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za) { - if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) + if (mc == nullptr || mc->cameraTargetPlayer == nullptr || mc->particleEngine == nullptr) { return nullptr; } @@ -2696,12 +2714,12 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle distCull = false; } - // 4J - this is a bit of hack to get communication through from the level itself, but if Minecraft::animateTickLevel is NULL then + // 4J - this is a bit of hack to get communication through from the level itself, but if Minecraft::animateTickLevel is nullptr then // we are to behave as normal, and if it is set, then we should use that as a pointer to the level the particle is to be created with // rather than try to work it out from the current player. This is because in this state we are calling from a loop that is trying // to amalgamate particle creation between all players for a particular level. Also don't do distance clipping as it isn't for a particular // player, and distance is already taken into account before we get here anyway by the code in Level::animateTickDoWork - if( mc->animateTickLevel == NULL ) + if( mc->animateTickLevel == nullptr ) { double particleDistanceSquared = 16 * 16; double xd = 0.0f; @@ -2714,7 +2732,7 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { shared_ptr thisPlayer = mc->localplayers[i]; - if(thisPlayer != NULL && level[i] == lev) + if(thisPlayer != nullptr && level[i] == lev) { xd = thisPlayer->x - x; yd = thisPlayer->y - y; @@ -2741,32 +2759,32 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle switch(eParticleType) { case eParticleType_hugeexplosion: - particle = shared_ptr(new HugeExplosionSeedParticle(lev, x, y, z, xa, ya, za)); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_largeexplode: - particle = shared_ptr(new HugeExplosionParticle(textures, lev, x, y, z, xa, ya, za)); + particle = std::make_shared(textures, lev, x, y, z, xa, ya, za); break; case eParticleType_fireworksspark: - particle = shared_ptr(new FireworksParticles::FireworksSparkParticle(lev, x, y, z, xa, ya, za, mc->particleEngine)); + particle = std::make_shared(lev, x, y, z, xa, ya, za, mc->particleEngine); particle->setAlpha(0.99f); break; case eParticleType_bubble: - particle = shared_ptr( new BubbleParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_suspended: - particle = shared_ptr( new SuspendedParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_depthsuspend: - particle = shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_townaura: - particle = shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_crit: { - shared_ptr critParticle2 = shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); + shared_ptr critParticle2 = std::make_shared(lev, x, y, z, xa, ya, za); critParticle2->CritParticle2PostConstructor(); particle = shared_ptr( critParticle2 ); // request from 343 to set pink for the needler in the Halo Texture Pack @@ -2782,8 +2800,8 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle } else { - float fStart=((float)(cStart&0xFF)); - float fDiff=(float)((cEnd-cStart)&0xFF); + float fStart=static_cast(cStart & 0xFF); + float fDiff=static_cast((cEnd - cStart) & 0xFF); float fCol = (fStart + (Math::random() * fDiff))/255.0f; particle->setColor( fCol, fCol, fCol ); @@ -2792,7 +2810,7 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle break; case eParticleType_magicCrit: { - shared_ptr critParticle2 = shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); + shared_ptr critParticle2 = std::make_shared(lev, x, y, z, xa, ya, za); critParticle2->CritParticle2PostConstructor(); particle = shared_ptr(critParticle2); particle->setColor(particle->getRedCol() * 0.3f, particle->getGreenCol() * 0.8f, particle->getBlueCol()); @@ -2800,7 +2818,7 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle } break; case eParticleType_smoke: - particle = shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_endportal: // 4J - Added. { @@ -2814,107 +2832,107 @@ shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle } break; case eParticleType_mobSpell: - particle = shared_ptr(new SpellParticle(lev, x, y, z, 0, 0, 0)); - particle->setColor((float) xa, (float) ya, (float) za); + particle = std::make_shared(lev, x, y, z, 0, 0, 0); + particle->setColor(static_cast(xa), static_cast(ya), static_cast(za)); break; case eParticleType_mobSpellAmbient: - particle = shared_ptr(new SpellParticle(lev, x, y, z, 0, 0, 0)); + particle = std::make_shared(lev, x, y, z, 0, 0, 0); particle->setAlpha(0.15f); - particle->setColor((float) xa, (float) ya, (float) za); + particle->setColor(static_cast(xa), static_cast(ya), static_cast(za)); break; case eParticleType_spell: - particle = shared_ptr( new SpellParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_witchMagic: { - particle = shared_ptr(new SpellParticle(lev, x, y, z, xa, ya, za)); + particle = std::make_shared(lev, x, y, z, xa, ya, za); dynamic_pointer_cast(particle)->setBaseTex(9 * 16); float randBrightness = lev->random->nextFloat() * 0.5f + 0.35f; particle->setColor(1 * randBrightness, 0 * randBrightness, 1 * randBrightness); } break; case eParticleType_instantSpell: - particle = shared_ptr(new SpellParticle(lev, x, y, z, xa, ya, za)); + particle = std::make_shared(lev, x, y, z, xa, ya, za); dynamic_pointer_cast(particle)->setBaseTex(9 * 16); break; case eParticleType_note: - particle = shared_ptr( new NoteParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_netherportal: - particle = shared_ptr( new NetherPortalParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_ender: - particle = shared_ptr( new EnderParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_enchantmenttable: - particle = shared_ptr(new EchantmentTableParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_explode: - particle = shared_ptr( new ExplodeParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_flame: - particle = shared_ptr( new FlameParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_lava: - particle = shared_ptr( new LavaParticle(lev, x, y, z) ); + particle = std::make_shared(lev, x, y, z); break; case eParticleType_footstep: - particle = shared_ptr( new FootstepParticle(textures, lev, x, y, z) ); + particle = std::make_shared(textures, lev, x, y, z); break; case eParticleType_splash: - particle = shared_ptr( new SplashParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_largesmoke: - particle = shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za, 2.5f) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za, 2.5f); break; case eParticleType_reddust: - particle = shared_ptr( new RedDustParticle(lev, x, y, z, (float) xa, (float) ya, (float) za) ); + particle = std::make_shared(lev, x, y, z, static_cast(xa), static_cast(ya), static_cast(za)); break; case eParticleType_snowballpoof: - particle = shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::snowBall, textures) ); + particle = std::make_shared(lev, x, y, z, Item::snowBall, textures); break; case eParticleType_dripWater: - particle = shared_ptr( new DripParticle(lev, x, y, z, Material::water) ); + particle = std::make_shared(lev, x, y, z, Material::water); break; case eParticleType_dripLava: - particle = shared_ptr( new DripParticle(lev, x, y, z, Material::lava) ); + particle = std::make_shared(lev, x, y, z, Material::lava); break; case eParticleType_snowshovel: - particle = shared_ptr( new SnowShovelParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_slime: - particle = shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::slimeBall, textures)); + particle = std::make_shared(lev, x, y, z, Item::slimeBall, textures); break; case eParticleType_heart: - particle = shared_ptr( new HeartParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; case eParticleType_angryVillager: - particle = shared_ptr( new HeartParticle(lev, x, y + 0.5f, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y + 0.5f, z, xa, ya, za); particle->setMiscTex(1 + 16 * 5); particle->setColor(1, 1, 1); break; case eParticleType_happyVillager: - particle = shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); particle->setMiscTex(2 + 16 * 5); particle->setColor(1, 1, 1); break; case eParticleType_dragonbreath: - particle = shared_ptr( new DragonBreathParticle(lev, x, y, z, xa, ya, za) ); + particle = std::make_shared(lev, x, y, z, xa, ya, za); break; default: if( ( eParticleType >= eParticleType_iconcrack_base ) && ( eParticleType <= eParticleType_iconcrack_last ) ) { int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = shared_ptr(new BreakingItemParticle(lev, x, y, z, xa, ya, za, Item::items[id], textures, data)); + particle = std::make_shared(lev, x, y, z, xa, ya, za, Item::items[id], textures, data); } else if( ( eParticleType >= eParticleType_tilecrack_base ) && ( eParticleType <= eParticleType_tilecrack_last ) ) { int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = dynamic_pointer_cast( shared_ptr(new TerrainParticle(lev, x, y, z, xa, ya, za, Tile::tiles[id], 0, data, textures))->init(data) ); + particle = dynamic_pointer_cast(std::make_shared(lev, x, y, z, xa, ya, za, Tile::tiles[id], 0, data, textures)->init(data) ); } } - if (particle != NULL) + if (particle != nullptr) { mc->particleEngine->add(particle); } @@ -2990,7 +3008,7 @@ void LevelRenderer::globalLevelEvent(int type, int sourceX, int sourceY, int sou { case LevelEvent::SOUND_WITHER_BOSS_SPAWN: case LevelEvent::SOUND_DRAGON_DEATH: - if (mc->cameraTargetPlayer != NULL) + if (mc->cameraTargetPlayer != nullptr) { // play the sound at an offset from the player double dx = sourceX - mc->cameraTargetPlayer->x; @@ -3029,7 +3047,7 @@ void LevelRenderer::levelEvent(shared_ptr 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 != nullptr) { // play the sound at an offset from the player double dx = x - mc->cameraTargetPlayer->x; @@ -3115,9 +3133,9 @@ void LevelRenderer::levelEvent(shared_ptr source, int type, int x, int y int colorValue = Item::potion->getColor(data); - float red = (float) ((colorValue >> 16) & 0xff) / 255.0f; - float green = (float) ((colorValue >> 8) & 0xff) / 255.0f; - float blue = (float) ((colorValue >> 0) & 0xff) / 255.0f; + float red = static_cast((colorValue >> 16) & 0xff) / 255.0f; + float green = static_cast((colorValue >> 8) & 0xff) / 255.0f; + float blue = static_cast((colorValue >> 0) & 0xff) / 255.0f; ePARTICLE_TYPE particleName = eParticleType_spell; if (Item::potion->hasInstantenousEffects(data)) @@ -3134,11 +3152,11 @@ void LevelRenderer::levelEvent(shared_ptr source, int type, int x, int y double zs = sin(angle) * dist; shared_ptr spellParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (spellParticle != NULL) + if (spellParticle != nullptr) { float randBrightness = 0.75f + random->nextFloat() * 0.25f; spellParticle->setColor(red * randBrightness, green * randBrightness, blue * randBrightness); - spellParticle->setPower((float) dist); + spellParticle->setPower(static_cast(dist)); } } level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_GLASS, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f, false); @@ -3161,10 +3179,10 @@ void LevelRenderer::levelEvent(shared_ptr source, int type, int x, int y double zs = sin(angle) * dist; shared_ptr acidParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (acidParticle != NULL) + if (acidParticle != nullptr) { float randBrightness = 0.75f + random->nextFloat() * 0.25f; - acidParticle->setPower((float) dist); + acidParticle->setPower(static_cast(dist)); } } level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_EXPLODE, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); @@ -3222,7 +3240,7 @@ void LevelRenderer::levelEvent(shared_ptr source, int type, int x, int y case LevelEvent::SOUND_PLAY_RECORDING: { RecordingItem *rci = dynamic_cast(Item::items[data]); - if (rci != NULL) + if (rci != nullptr) { level[playerIndex]->playStreamingMusic(rci->recording, x, y, z); } @@ -3231,7 +3249,7 @@ void LevelRenderer::levelEvent(shared_ptr source, int type, int x, int y // 4J-PB - only play streaming music if there isn't already some playing - the CD playing may have finished, and game music started playing already if(!mc->soundEngine->GetIsPlayingStreamingGameMusic()) { - level[playerIndex]->playStreamingMusic(L"", x, y, z); // 4J - used to pass NULL, but using empty string here now instead + level[playerIndex]->playStreamingMusic(L"", x, y, z); // 4J - used to pass nullptr, but using empty string here now instead } } mc->localplayers[playerIndex]->updateRichPresence(); @@ -3291,12 +3309,12 @@ void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, int progres } else { - BlockDestructionProgress *entry = NULL; + BlockDestructionProgress *entry = nullptr; auto it = destroyingBlocks.find(id); if(it != destroyingBlocks.end()) entry = it->second; - if (entry == NULL || entry->getX() != x || entry->getY() != y || entry->getZ() != z) + if (entry == nullptr || entry->getX() != x || entry->getY() != y || entry->getZ() != z) { entry = new BlockDestructionProgress(id, x, y, z); destroyingBlocks.insert( unordered_map::value_type(id, entry) ); @@ -3555,10 +3573,10 @@ void LevelRenderer::DestroyedTileManager::destroyingTileAt( Level *level, int x, // ones, so make a temporary list and then copy over RecentTile *recentTile = new RecentTile(x, y, z, level); - AABB *box = AABB::newTemp((float)x, (float)y, (float)z, (float)(x+1), (float)(y+1), (float)(z+1)); + AABB *box = AABB::newTemp(static_cast(x), static_cast(y), static_cast(z), static_cast(x + 1), static_cast(y + 1), static_cast(z + 1)); Tile *tile = Tile::tiles[level->getTile(x, y, z)]; - if (tile != NULL) + if (tile != nullptr) { tile->addAABBs(level, x, y, z, box, &recentTile->boxes, nullptr); } diff --git a/Minecraft.Client/Lighting.cpp b/Minecraft.Client/Lighting.cpp index 50529d516..ef9feaa14 100644 --- a/Minecraft.Client/Lighting.cpp +++ b/Minecraft.Client/Lighting.cpp @@ -44,7 +44,7 @@ void Lighting::turnOn() FloatBuffer *Lighting::getBuffer(double a, double b, double c, double d) { - return getBuffer((float) a, (float) b, (float) c, (float) d); + return getBuffer(static_cast(a), static_cast(b), static_cast(c), static_cast(d)); } FloatBuffer *Lighting::getBuffer(float a, float b, float c, float d) diff --git a/Minecraft.Client/LightningBoltRenderer.cpp b/Minecraft.Client/LightningBoltRenderer.cpp index d02ea7f71..46b628dfb 100644 --- a/Minecraft.Client/LightningBoltRenderer.cpp +++ b/Minecraft.Client/LightningBoltRenderer.cpp @@ -79,8 +79,8 @@ void LightningBoltRenderer::render(shared_ptr _bolt, double x, double y, if (i == 1 || i == 2) xx2 += rr2 * 2; if (i == 2 || i == 3) zz2 += rr2 * 2; - t->vertex((float)(xx2 + xo0), (float)( y + (h) * 16), (float)( zz2 + zo0)); - t->vertex((float)(xx1 + xo1), (float)( y + (h + 1) * 16), (float)( zz1 + zo1)); + t->vertex(static_cast(xx2 + xo0), static_cast(y + (h) * 16), static_cast(zz2 + zo0)); + t->vertex(static_cast(xx1 + xo1), static_cast(y + (h + 1) * 16), static_cast(zz1 + zo1)); } diff --git a/Minecraft.Client/LivingEntityRenderer.cpp b/Minecraft.Client/LivingEntityRenderer.cpp index 757948a37..b3478ba92 100644 --- a/Minecraft.Client/LivingEntityRenderer.cpp +++ b/Minecraft.Client/LivingEntityRenderer.cpp @@ -17,7 +17,7 @@ LivingEntityRenderer::LivingEntityRenderer(Model *model, float shadow) { this->model = model; shadowRadius = shadow; - armor = NULL; + armor = nullptr; } void LivingEntityRenderer::setArmor(Model *armor) @@ -37,17 +37,27 @@ float LivingEntityRenderer::rotlerp(float from, float to, float a) void LivingEntityRenderer::render(shared_ptr _mob, double x, double y, double z, float rot, float a) { + if (_mob == nullptr) + { + return; + } + shared_ptr mob = dynamic_pointer_cast(_mob); + if (mob == nullptr) + { + return; + } + glPushMatrix(); glDisable(GL_CULL_FACE); model->attackTime = getAttackAnim(mob, a); - if (armor != NULL) armor->attackTime = model->attackTime; + if (armor != nullptr) armor->attackTime = model->attackTime; model->riding = mob->isRiding(); - if (armor != NULL) armor->riding = model->riding; + if (armor != nullptr) armor->riding = model->riding; model->young = mob->isBaby(); - if (armor != NULL) armor->young = model->young; + if (armor != nullptr) armor->young = model->young; /*try*/ { @@ -259,7 +269,7 @@ void LivingEntityRenderer::renderModel(shared_ptr mob, float wp, f void LivingEntityRenderer::setupPosition(shared_ptr mob, double x, double y, double z) { - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); } void LivingEntityRenderer::setupRotations(shared_ptr mob, float bob, float bodyRot, float a) @@ -306,7 +316,7 @@ void LivingEntityRenderer::renderArrows(shared_ptr mob, float a) int arrowCount = mob->getArrowCount(); if (arrowCount > 0) { - shared_ptr arrow = shared_ptr(new Arrow(mob->level, mob->x, mob->y, mob->z)); + shared_ptr arrow = std::make_shared(mob->level, mob->x, mob->y, mob->z); Random random = Random(mob->entityId); Lighting::turnOff(); for (int i = 0; i < arrowCount; i++) @@ -405,7 +415,7 @@ void LivingEntityRenderer::renderName(shared_ptr mob, double x, do Font *font = getFont(); glPushMatrix(); - glTranslatef((float) x + 0, (float) y + mob->bbHeight + 0.5f, (float) z); + glTranslatef(static_cast(x) + 0, static_cast(y) + mob->bbHeight + 0.5f, static_cast(z)); glNormal3f(0, 1, 0); glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -448,7 +458,7 @@ void LivingEntityRenderer::renderName(shared_ptr mob, double x, do bool LivingEntityRenderer::shouldShowName(shared_ptr mob) { - return Minecraft::renderNames() && mob != entityRenderDispatcher->cameraEntity && !mob->isInvisibleTo(Minecraft::GetInstance()->player) && mob->rider.lock() == NULL; + return Minecraft::renderNames() && mob != entityRenderDispatcher->cameraEntity && !mob->isInvisibleTo(Minecraft::GetInstance()->player) && mob->rider.lock() == nullptr; } void LivingEntityRenderer::renderNameTags(shared_ptr mob, double x, double y, double z, const wstring &msg, float scale, double dist) @@ -595,10 +605,10 @@ void LivingEntityRenderer::renderNameTag(shared_ptr mob, const wst { t->color(0.0f, 0.0f, 0.0f, 0.25f); } - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); + t->vertex(static_cast(-w - 1), static_cast(-1 + offs), static_cast(0)); + t->vertex(static_cast(-w - 1), static_cast(+8 + offs + 1), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(+8 + offs + 1), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(-1 + offs), static_cast(0)); t->end(); glEnable(GL_DEPTH_TEST); @@ -607,11 +617,11 @@ void LivingEntityRenderer::renderNameTag(shared_ptr mob, const wst glLineWidth(2.0f); t->begin(GL_LINE_STRIP); t->color(color, 255 * textOpacity); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); + t->vertex(static_cast(-w - 1), static_cast(-1 + offs), static_cast(0)); + t->vertex(static_cast(-w - 1), static_cast(+8 + offs + 1), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(+8 + offs + 1), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(-1 + offs), static_cast(0)); + t->vertex(static_cast(-w - 1), static_cast(-1 + offs), static_cast(0)); t->end(); glDepthFunc(GL_LEQUAL); glDepthMask(false); @@ -632,10 +642,10 @@ void LivingEntityRenderer::renderNameTag(shared_ptr mob, const wst t->begin(); int w = font->width(playerName) / 2; t->color(color, 255); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); + t->vertex(static_cast(-w - 1), static_cast(-1 + offs), static_cast(0)); + t->vertex(static_cast(-w - 1), static_cast(+8 + offs), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(+8 + offs), static_cast(0)); + t->vertex(static_cast(+w + 1), static_cast(-1 + offs), static_cast(0)); t->end(); glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_2D); @@ -645,7 +655,7 @@ void LivingEntityRenderer::renderNameTag(shared_ptr mob, const wst if( textOpacity > 0.0f ) { - int textColor = ( ( (int)(textOpacity*255) << 24 ) | 0xffffff ); + int textColor = ( ( static_cast(textOpacity * 255) << 24 ) | 0xffffff ); font->draw(playerName, -font->width(playerName) / 2, offs, textColor); } diff --git a/Minecraft.Client/LocalPlayer.cpp b/Minecraft.Client/LocalPlayer.cpp index d743543e5..7988416ad 100644 --- a/Minecraft.Client/LocalPlayer.cpp +++ b/Minecraft.Client/LocalPlayer.cpp @@ -56,7 +56,7 @@ #ifndef _DURANGO #include "..\Minecraft.World\CommonStats.h" #endif - +extern ConsoleUIController ui; LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension) : Player(level, user->name) @@ -79,11 +79,11 @@ LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dim this->minecraft = minecraft; this->dimension = dimension; - if (user != NULL && user->name.length() > 0) + if (user != nullptr && user->name.length() > 0) { customTextureUrl = L"http://s3.amazonaws.com/MinecraftSkins/" + user->name + L".png"; } - if( user != NULL ) + if( user != nullptr ) { this->name = user->name; //wprintf(L"Created LocalPlayer with name %ls\n", name.c_str() ); @@ -95,7 +95,7 @@ LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dim } } - input = NULL; + input = nullptr; m_iPad = -1; m_iScreenSection=C4JRender::VIEWPORT_TYPE_FULLSCREEN; // assume singleplayer default m_bPlayerRespawned=false; @@ -124,7 +124,7 @@ LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dim LocalPlayer::~LocalPlayer() { - if( this->input != NULL ) + if( this->input != nullptr ) delete input; } @@ -188,9 +188,9 @@ void LocalPlayer::aiStep() { if (!level->isClientSide) { - if (riding != NULL) this->ride(nullptr); + if (riding != nullptr) this->ride(nullptr); } - if (minecraft->screen != NULL) minecraft->setScreen(NULL); + if (minecraft->screen != nullptr) minecraft->setScreen(nullptr); if (portalTime == 0) { @@ -389,11 +389,11 @@ void LocalPlayer::aiStep() jumpRidingTicks++; if (jumpRidingTicks < 10) { - jumpRidingScale = (float) jumpRidingTicks * .1f; + jumpRidingScale = static_cast(jumpRidingTicks) * .1f; } else { - jumpRidingScale = .8f + (2.f / ((float) (jumpRidingTicks - 9))) * .1f; + jumpRidingScale = .8f + (2.f / static_cast(jumpRidingTicks - 9)) * .1f; } } } @@ -427,9 +427,9 @@ void LocalPlayer::aiStep() #ifdef _DEBUG_MENUS_ENABLED if(abilities.debugflying) { - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; + flyX = static_cast(viewVector->x) * input->ya; + flyY = static_cast(viewVector->y) * input->ya; + flyZ = static_cast(viewVector->z) * input->ya; } else #endif @@ -437,11 +437,11 @@ void LocalPlayer::aiStep() if( isSprinting() ) { // Accelrate up to full speed if we are sprinting, moving in the direction of the view vector - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; + flyX = static_cast(viewVector->x) * input->ya; + flyY = static_cast(viewVector->y) * input->ya; + flyZ = static_cast(viewVector->z) * input->ya; - float scale = ((float)(SPRINT_DURATION - sprintTime))/10.0f; + float scale = static_cast(SPRINT_DURATION - sprintTime)/10.0f; scale = scale * scale; if ( scale > 1.0f ) scale = 1.0f; flyX *= scale; @@ -544,7 +544,7 @@ float LocalPlayer::getFieldOfViewModifier() if (isUsingItem() && getUseItem()->id == Item::bow->id) { int ticksHeld = getTicksUsingItem(); - float scale = (float) ticksHeld / BowItem::MAX_DRAW_DURATION; + float scale = static_cast(ticksHeld) / BowItem::MAX_DRAW_DURATION; if (scale > 1) { scale = 1; @@ -574,7 +574,7 @@ void LocalPlayer::readAdditionalSaveData(CompoundTag *entityTag) void LocalPlayer::closeContainer() { Player::closeContainer(); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // 4J - Close any xui here // Fix for #9164 - CRASH: MP: Title crashes upon opening a chest and having another user destroy it. @@ -705,21 +705,21 @@ bool LocalPlayer::openTrading(shared_ptr traderTarget, const wstring & void LocalPlayer::crit(shared_ptr e) { - shared_ptr critParticle = shared_ptr( new CritParticle((Level *)minecraft->level, e) ); + shared_ptr critParticle = std::make_shared(reinterpret_cast(minecraft->level), e); critParticle->CritParticlePostConstructor(); minecraft->particleEngine->add(critParticle); } void LocalPlayer::magicCrit(shared_ptr e) { - shared_ptr critParticle = shared_ptr( new CritParticle((Level *)minecraft->level, e, eParticleType_magicCrit) ); + shared_ptr critParticle = std::make_shared(reinterpret_cast(minecraft->level), e, eParticleType_magicCrit); critParticle->CritParticlePostConstructor(); minecraft->particleEngine->add(critParticle); } void LocalPlayer::take(shared_ptr e, int orgCount) { - minecraft->particleEngine->add( shared_ptr( new TakeAnimationParticle((Level *)minecraft->level, e, shared_from_this(), -0.5f) ) ); + minecraft->particleEngine->add(std::make_shared(reinterpret_cast(minecraft->level), e, shared_from_this(), -0.5f)); } void LocalPlayer::chat(const wstring& message) @@ -754,8 +754,8 @@ void LocalPlayer::hurtTo(float newHealth, ETelemetryChallenges damageSource) if( this->getHealth() <= 0) { - int deathTime = (int)(level->getGameTime() % Level::TICKS_PER_DAY)/1000; - int carriedId = inventory->getSelected() == NULL ? 0 : inventory->getSelected()->id; + int deathTime = static_cast(level->getGameTime() % Level::TICKS_PER_DAY)/1000; + int carriedId = inventory->getSelected() == nullptr ? 0 : inventory->getSelected()->id; TelemetryManager->RecordPlayerDiedOrFailed(GetXboxPad(), 0, y, 0, 0, carriedId, 0, damageSource); // if there are any xuiscenes up for this player, close them @@ -800,11 +800,11 @@ void LocalPlayer::awardStat(Stat *stat, byteArray param) delete [] param.data; if (!app.CanRecordStatsAndAchievements()) return; - if (stat == NULL) return; + if (stat == nullptr) return; if (stat->isAchievement()) { - Achievement *ach = (Achievement *) stat; + Achievement *ach = static_cast(stat); // 4J-PB - changed to attempt to award everytime - the award may need a storage device, so needs a primary player, and the player may not have been a primary player when they first 'got' the award // so let the award manager figure it out //if (!minecraft->stats[m_iPad]->hasTaken(ach)) @@ -830,7 +830,7 @@ void LocalPlayer::awardStat(Stat *stat, byteArray param) } // 4J-JEV: To stop spamming trophies. - unsigned long long achBit = ((unsigned long long)1) << ach->getAchievementID(); + unsigned long long achBit = static_cast(1) << ach->getAchievementID(); if ( !(achBit & m_awardedThisSession) ) { ProfileManager.Award(m_iPad, ach->getAchievementID()); @@ -1196,7 +1196,7 @@ void LocalPlayer::playSound(int soundId, float volume, float pitch) bool LocalPlayer::isRidingJumpable() { - return riding != NULL && riding->GetType() == eTYPE_HORSE; + return riding != nullptr && riding->GetType() == eTYPE_HORSE; } float LocalPlayer::getJumpRidingScale() @@ -1215,9 +1215,9 @@ bool LocalPlayer::hasPermission(EGameCommand command) void LocalPlayer::onCrafted(shared_ptr item) { - if( minecraft->localgameModes[m_iPad] != NULL ) + if( minecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(minecraft->localgameModes[m_iPad]); gameMode->getTutorial()->onCrafted(item); } } @@ -1239,8 +1239,8 @@ void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) int cx = this->xChunk; int cz = this->zChunk; - int pZ = ((int) floor(this->z)) %16; - int pX = ((int) floor(this->x)) %16; + int pZ = static_cast(floor(this->z)) %16; + int pX = static_cast(floor(this->x)) %16; cout<<"player in chunk ("<x<<","<y<<","<z<<")\n"; @@ -1272,14 +1272,14 @@ void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) void LocalPlayer::handleMouseDown(int button, bool down) { // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) + if(isSleeping() && level != nullptr && level->isClientSide) { return; } if (!down) missTime = 0; if (button == 0 && missTime > 0) return; - if (down && minecraft->hitResult != NULL && minecraft->hitResult->type == HitResult::TILE && button == 0) + if (down && minecraft->hitResult != nullptr && minecraft->hitResult->type == HitResult::TILE && button == 0) { int x = minecraft->hitResult->x; int y = minecraft->hitResult->y; @@ -1328,9 +1328,9 @@ bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) } // Get distance from last click point in each axis - float dX = (float)x - lastClickX; - float dY = (float)y - lastClickY; - float dZ = (float)z - lastClickZ; + float dX = static_cast(x) - lastClickX; + float dY = static_cast(y) - lastClickY; + float dZ = static_cast(z) - lastClickZ; bool newClick = false; float ddx = dX - lastClickdX; @@ -1436,9 +1436,9 @@ bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) else { // First click - just record position & handle - lastClickX = (float)x; - lastClickY = (float)y; - lastClickZ = (float)z; + lastClickX = static_cast(x); + lastClickY = static_cast(y); + lastClickZ = static_cast(z); // If we actually placed an item, then move into the init state as we are going to be doing the special creative mode auto repeat bool itemPlaced = handleMouseClick(button); // If we're sprinting or riding, don't auto-repeat at all. With auto repeat on, we can quickly place fires causing photosensitivity issues due to rapid flashing @@ -1486,7 +1486,7 @@ bool LocalPlayer::handleMouseClick(int button) // 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button - if(button==1 && (isSleeping() && level != NULL && level->isClientSide)) + if(button==1 && (isSleeping() && level != nullptr && level->isClientSide)) { if(lastClickState == lastClick_oldRepeat) return false; @@ -1497,14 +1497,14 @@ bool LocalPlayer::handleMouseClick(int button) } // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) + if(isSleeping() && level != nullptr && level->isClientSide) { return false; } shared_ptr oldItem = inventory->getSelected(); - if (minecraft->hitResult == NULL) + if (minecraft->hitResult == nullptr) { if (button == 0 && minecraft->localgameModes[GetXboxPad()]->hasMissTime()) missTime = 10; } @@ -1555,7 +1555,7 @@ bool LocalPlayer::handleMouseClick(int button) else { shared_ptr item = oldItem; - int oldCount = item != NULL ? item->count : 0; + int oldCount = item != nullptr ? item->count : 0; bool usedItem = false; if (minecraft->gameMode->useItemOn(minecraft->localplayers[GetXboxPad()], level, item, x, y, z, face, minecraft->hitResult->pos, false, &usedItem)) { @@ -1568,7 +1568,7 @@ bool LocalPlayer::handleMouseClick(int button) //app.DebugPrintf("Player %d is swinging\n",GetXboxPad()); swing(); } - if (item == NULL) + if (item == nullptr) { return false; } @@ -1587,7 +1587,7 @@ bool LocalPlayer::handleMouseClick(int button) if (mayUse && button == 1) { shared_ptr item = inventory->getSelected(); - if (item != NULL) + if (item != nullptr) { if (minecraft->gameMode->useItem(minecraft->localplayers[GetXboxPad()], level, item)) { @@ -1603,23 +1603,23 @@ void LocalPlayer::updateRichPresence() if((m_iPad!=-1)/* && !ui.GetMenuDisplayed(m_iPad)*/ ) { shared_ptr selectedItem = inventory->getSelected(); - if(selectedItem != NULL && selectedItem->id == Item::fishingRod_Id) + if(selectedItem != nullptr && selectedItem->id == Item::fishingRod_Id) { app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_FISHING); } - else if(selectedItem != NULL && selectedItem->id == Item::map_Id) + else if(selectedItem != nullptr && selectedItem->id == Item::map_Id) { app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_MAP); } - else if ( (riding != NULL) && riding->instanceof(eTYPE_MINECART) ) + else if ( (riding != nullptr) && riding->instanceof(eTYPE_MINECART) ) { app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_MINECART); } - else if ( (riding != NULL) && riding->instanceof(eTYPE_BOAT) ) + else if ( (riding != nullptr) && riding->instanceof(eTYPE_BOAT) ) { app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_BOATING); } - else if ( (riding != NULL) && riding->instanceof(eTYPE_PIG) ) + else if ( (riding != nullptr) && riding->instanceof(eTYPE_PIG) ) { app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_PIG); } @@ -1660,13 +1660,13 @@ float LocalPlayer::getAndResetChangeDimensionTimer() void LocalPlayer::handleCollectItem(shared_ptr item) { - if(item != NULL) + if(item != nullptr) { unsigned int itemCountAnyAux = 0; unsigned int itemCountThisAux = 0; for (unsigned int k = 0; k < inventory->items.length; ++k) { - if (inventory->items[k] != NULL) + if (inventory->items[k] != nullptr) { // do they have the item if(inventory->items[k]->id == item->id) @@ -1682,7 +1682,7 @@ void LocalPlayer::handleCollectItem(shared_ptr item) } } } - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(minecraft->localgameModes[m_iPad]); gameMode->getTutorial()->onTake(item, itemCountAnyAux, itemCountThisAux); } diff --git a/Minecraft.Client/MemTexture.cpp b/Minecraft.Client/MemTexture.cpp index f587e82f1..ee3ba7981 100644 --- a/Minecraft.Client/MemTexture.cpp +++ b/Minecraft.Client/MemTexture.cpp @@ -15,7 +15,7 @@ MemTexture::MemTexture(const wstring& _url, PBYTE pbData,DWORD dwBytes, MemTextu //loadedImage=Textures::getTexture() // 4J - remember to add deletes in here for any created BufferedImages when implemented loadedImage = new BufferedImage(pbData,dwBytes); - if(processor==NULL) + if(processor==nullptr) { } diff --git a/Minecraft.Client/MinecartModel.cpp b/Minecraft.Client/MinecartModel.cpp index 8a1ce0d7f..0cb0764fb 100644 --- a/Minecraft.Client/MinecartModel.cpp +++ b/Minecraft.Client/MinecartModel.cpp @@ -16,23 +16,23 @@ MinecartModel::MinecartModel() : Model() int h = 16; int yOff = 4; - cubes[0]->addBox((float)(-w / 2), (float)(-h / 2), -1, w, h, 2, 0); - cubes[0]->setPos(0, (float)(0 + yOff), 0); + cubes[0]->addBox(static_cast(-w / 2), static_cast(-h / 2), -1, w, h, 2, 0); + cubes[0]->setPos(0, static_cast(0 + yOff), 0); - cubes[5]->addBox((float)(-w / 2 + 1), (float)(-h / 2 + 1), -1, w - 2, h - 2, 1, 0); - cubes[5]->setPos(0, (float)(0 + yOff), 0); + cubes[5]->addBox(static_cast(-w / 2 + 1), static_cast(-h / 2 + 1), -1, w - 2, h - 2, 1, 0); + cubes[5]->setPos(0, static_cast(0 + yOff), 0); - cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); + cubes[1]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[1]->setPos(static_cast(-w / 2 + 1), static_cast(0 + yOff), 0); - cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); + cubes[2]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[2]->setPos(static_cast(+w / 2 - 1), static_cast(0 + yOff), 0); - cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); + cubes[3]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[3]->setPos(0, static_cast(0 + yOff), static_cast(-h / 2 + 1)); - cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); + cubes[4]->addBox(static_cast(-w / 2 + 2), static_cast(-d - 1), -1, w - 4, d, 2, 0); + cubes[4]->setPos(0, static_cast(0 + yOff), static_cast(+h / 2 - 1)); cubes[0]->xRot = PI / 2; cubes[1]->yRot = PI / 2 * 3; diff --git a/Minecraft.Client/MinecartRenderer.cpp b/Minecraft.Client/MinecartRenderer.cpp index 34205d33f..0ecb7f583 100644 --- a/Minecraft.Client/MinecartRenderer.cpp +++ b/Minecraft.Client/MinecartRenderer.cpp @@ -42,12 +42,12 @@ void MinecartRenderer::render(shared_ptr _cart, double x, double y, doub float xRot = cart->xRotO + (cart->xRot - cart->xRotO) * a; - if (p != NULL) + if (p != nullptr) { Vec3 *p0 = cart->getPosOffs(xx, yy, zz, r); Vec3 *p1 = cart->getPosOffs(xx, yy, zz, -r); - if (p0 == NULL) p0 = p; - if (p1 == NULL) p1 = p; + if (p0 == nullptr) p0 = p; + if (p1 == nullptr) p1 = p; x += p->x - xx; y += (p0->y + p1->y) / 2 - yy; @@ -60,11 +60,11 @@ void MinecartRenderer::render(shared_ptr _cart, double x, double y, doub else { dir = dir->normalize(); - rot = (float) (atan2(dir->z, dir->x) * 180 / PI); - xRot = (float) (atan(dir->y) * 73); + rot = static_cast(atan2(dir->z, dir->x) * 180 / PI); + xRot = static_cast(atan(dir->y) * 73); } } - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glRotatef(180 - rot, 0, 1, 0); glRotatef(-xRot, 0, 0, 1); @@ -80,7 +80,7 @@ void MinecartRenderer::render(shared_ptr _cart, double x, double y, doub Tile *tile = cart->getDisplayTile(); int tileData = cart->getDisplayData(); - if (tile != NULL) + if (tile != nullptr) { glPushMatrix(); diff --git a/Minecraft.Client/Minecraft.cpp b/Minecraft.Client/Minecraft.cpp index 2be178c54..85d36b3b1 100644 --- a/Minecraft.Client/Minecraft.cpp +++ b/Minecraft.Client/Minecraft.cpp @@ -86,13 +86,15 @@ // from the main thread, and have longer to run, since it's called at 20Hz instead of 60 #define DISABLE_LEVELTICK_THREAD -Minecraft *Minecraft::m_instance = NULL; +Minecraft *Minecraft::m_instance = nullptr; int64_t Minecraft::frameTimes[512]; int64_t Minecraft::tickTimes[512]; int Minecraft::frameTimePos = 0; int64_t Minecraft::warezTime = 0; File Minecraft::workDir = File(L""); +extern ConsoleUIController ui; + #ifdef __PSVITA__ TOUCHSCREENRECT QuickSelectRect[3]= @@ -121,33 +123,33 @@ ResourceLocation Minecraft::ALT_FONT_LOCATION = ResourceLocation(TN_ALT_FONT); Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen) { // 4J - added this block of initialisers - gameMode = NULL; + gameMode = nullptr; hasCrashed = false; timer = new Timer(SharedConstants::TICKS_PER_SECOND); - oldLevel = NULL; //4J Stu added - level = NULL; + oldLevel = nullptr; //4J Stu added + level = nullptr; levels = MultiPlayerLevelArray(3); // 4J Added - levelRenderer = NULL; + levelRenderer = nullptr; player = nullptr; cameraTargetPlayer = nullptr; - particleEngine = NULL; - user = NULL; - parent = NULL; + particleEngine = nullptr; + user = nullptr; + parent = nullptr; pause = false; - textures = NULL; - font = NULL; - screen = NULL; + textures = nullptr; + font = nullptr; + screen = nullptr; localPlayerIdx = 0; rightClickDelay = 0; // 4J Stu Added InitializeCriticalSection( &ProgressRenderer::s_progress ); InitializeCriticalSection(&m_setLevelCS); - //m_hPlayerRespawned = CreateEvent(NULL, FALSE, FALSE, NULL); + //m_hPlayerRespawned = CreateEvent(nullptr, FALSE, FALSE, nullptr); - progressRenderer = NULL; - gameRenderer = NULL; - bgLoader = NULL; + progressRenderer = nullptr; + gameRenderer = nullptr; + bgLoader = nullptr; ticks = 0; // 4J-PB - moved into the local player @@ -158,20 +160,20 @@ Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet orgWidth = orgHeight = 0; achievementPopup = new AchievementPopup(this); - gui = NULL; + gui = nullptr; noRender = false; humanoidModel = new HumanoidModel(0); - hitResult = 0; - options = NULL; + hitResult = nullptr; + options = nullptr; soundEngine = new SoundEngine(); - mouseHandler = NULL; - skins = NULL; + mouseHandler = nullptr; + skins = nullptr; workingDirectory = File(L""); - levelSource = NULL; - stats[0] = NULL; - stats[1] = NULL; - stats[2] = NULL; - stats[3] = NULL; + levelSource = nullptr; + stats[0] = nullptr; + stats[1] = nullptr; + stats[2] = nullptr; + stats[3] = nullptr; connectToPort = 0; workDir = File(L""); // 4J removed @@ -188,7 +190,7 @@ Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet orgHeight = height; this->fullscreen = fullscreen; - this->minecraftApplet = NULL; + this->minecraftApplet = nullptr; this->parent = parent; // 4J - Our actual physical frame buffer is always 1280x720 ie in a 16:9 ratio. If we want to do a 4:3 mode, we are telling the original minecraft code @@ -215,13 +217,13 @@ Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet for(int i=0;isoundEngine->init(NULL); + this->soundEngine->init(nullptr); #endif #ifndef DISABLE_LEVELTICK_THREAD @@ -356,7 +358,7 @@ void Minecraft::init() stats[i] = new StatsCounter(); /* 4J - TODO, 4J-JEV: Unnecessary. - Achievements::openInventory->setDescFormatter(NULL); + Achievements::openInventory->setDescFormatter(nullptr); Achievements.openInventory.setDescFormatter(new DescFormatter(){ public String format(String i18nValue) { return String.format(i18nValue, Keyboard.getKeyName(options.keyBuild.key)); @@ -417,7 +419,7 @@ void Minecraft::init() MemSect(0); gui = new Gui(this); - if (connectToIp != L"") // 4J - was NULL comparison + if (connectToIp != L"") // 4J - was nullptr comparison { // setScreen(new ConnectScreen(this, connectToIp, connectToPort)); // 4J TODO - put back in } @@ -487,10 +489,10 @@ void Minecraft::blit(int x, int y, int sx, int sy, int w, int h) float vs = 1 / 256.0f; Tesselator *t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(x + 0), (float)( y + h), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + h), (float)( 0), (float)( (sx + w) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + 0), (float)( 0), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); - t->vertexUV((float)(x + 0), (float)( y + 0), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); + t->vertexUV(static_cast(x + 0), static_cast(y + h), static_cast(0), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); + t->vertexUV(static_cast(x + w), static_cast(y + h), static_cast(0), (float)( (sx + w) * us), (float)( (sy + h) * vs)); + t->vertexUV(static_cast(x + w), static_cast(y + 0), static_cast(0), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); + t->vertexUV(static_cast(x + 0), static_cast(y + 0), static_cast(0), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); t->end(); } @@ -501,30 +503,30 @@ LevelStorageSource *Minecraft::getLevelSource() void Minecraft::setScreen(Screen *screen) { - if (this->screen != NULL) + if (this->screen != nullptr) { this->screen->removed(); } #ifdef _WINDOWS64 - if (screen != NULL && g_KBMInput.IsMouseGrabbed()) + if (screen != nullptr && g_KBMInput.IsMouseGrabbed()) { g_KBMInput.SetMouseGrabbed(false); } #endif //4J Gordon: Do not force a stats save here - /*if (dynamic_cast(screen)!=NULL) + /*if (dynamic_cast(screen)!=nullptr) { stats->forceSend(); } stats->forceSave();*/ - if (screen == NULL && level == NULL) + if (screen == nullptr && level == nullptr) { screen = new TitleScreen(); } - else if (player != NULL && !ui.GetMenuDisplayed(player->GetXboxPad()) && player->getHealth() <= 0) + else if (player != nullptr && !ui.GetMenuDisplayed(player->GetXboxPad()) && player->getHealth() <= 0) { //screen = new DeathScreen(); @@ -537,18 +539,18 @@ void Minecraft::setScreen(Screen *screen) } else { - ui.NavigateToScene(player->GetXboxPad(),eUIScene_DeathMenu,NULL); + ui.NavigateToScene(player->GetXboxPad(),eUIScene_DeathMenu,nullptr); } } - if (dynamic_cast(screen)!=NULL) + if (dynamic_cast(screen)!=nullptr) { options->renderDebug = false; gui->clearMessages(); } this->screen = screen; - if (screen != NULL) + if (screen != nullptr) { // releaseMouse(); // 4J - removed ScreenSizeCalculator ssc(options, width, height); @@ -564,7 +566,7 @@ void Minecraft::setScreen(Screen *screen) // 4J-PB - if a screen has been set, go into menu mode // it's possible that player doesn't exist here yet - /*if(screen!=NULL) + /*if(screen!=nullptr) { if(player && player->GetXboxPad()!=-1) { @@ -601,7 +603,7 @@ void Minecraft::destroy() stats->forceSave();*/ // try { - setLevel(NULL); + setLevel(nullptr); // } catch (Throwable e) { // } @@ -648,11 +650,11 @@ void Minecraft::run() AABB::resetPool(); Vec3::resetPool(); - // if (parent == NULL && Display.isCloseRequested()) { // 4J - removed + // if (parent == nullptr && Display.isCloseRequested()) { // 4J - removed // stop(); // } - if (pause && level != NULL) + if (pause && level != nullptr) { float lastA = timer->a; timer->advanceTime(); @@ -685,14 +687,14 @@ void Minecraft::run() soundEngine->update(player, timer->a); glEnable(GL_TEXTURE_2D); - if (level != NULL) level->updateLights(); + if (level != nullptr) level->updateLights(); // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) Display.update(); // 4J - removed - if (player != NULL && player->isInWall()) options->thirdPersonView = false; + if (player != nullptr && player->isInWall()) options->thirdPersonView = false; if (!noRender) { - if (gameMode != NULL) gameMode->render(timer->a); + if (gameMode != nullptr) gameMode->render(timer->a); gameRenderer->render(timer->a); } @@ -726,7 +728,7 @@ void Minecraft::run() // checkScreenshot(); // 4J - removed /* 4J - removed - if (parent != NULL && !fullscreen) + if (parent != nullptr && !fullscreen) { if (parent.getWidth() != width || parent.getHeight() != height) { @@ -741,7 +743,7 @@ void Minecraft::run() */ checkGlError(L"Post render"); frames++; - pause = !isClientSide() && screen != NULL && screen->isPauseScreen(); + pause = !isClientSide() && screen != nullptr && screen->isPauseScreen(); while (System::currentTimeMillis() >= lastTime + 1000) { @@ -795,7 +797,7 @@ bool Minecraft::setLocalPlayerIdx(int idx) localPlayerIdx = idx; // If the player is not null, but the game mode is then this is just a temp player // whose only real purpose is to hold the viewport position - if( localplayers[idx] == NULL || localgameModes[idx] == NULL ) return false; + if( localplayers[idx] == nullptr || localgameModes[idx] == nullptr ) return false; gameMode = localgameModes[idx]; player = localplayers[idx]; @@ -819,7 +821,7 @@ void Minecraft::updatePlayerViewportAssignments() int viewportsRequired = 0; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if( localplayers[i] != NULL ) viewportsRequired++; + if( localplayers[i] != nullptr ) viewportsRequired++; } if( viewportsRequired == 3 ) viewportsRequired = 4; @@ -829,7 +831,7 @@ void Minecraft::updatePlayerViewportAssignments() // Single viewport for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if( localplayers[i] != NULL ) localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; + if( localplayers[i] != nullptr ) localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; } } else if( viewportsRequired == 2 ) @@ -838,7 +840,7 @@ void Minecraft::updatePlayerViewportAssignments() int found = 0; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if( localplayers[i] != NULL ) + if( localplayers[i] != nullptr ) { // Primary player settings decide what the mode is if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_SplitScreenVertical)) @@ -861,7 +863,7 @@ void Minecraft::updatePlayerViewportAssignments() for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if( localplayers[i] != NULL ) + if( localplayers[i] != nullptr ) { // 4J Stu - If the game hasn't started, ignore current allocations (as the players won't have seen them) @@ -885,7 +887,7 @@ void Minecraft::updatePlayerViewportAssignments() // Found which quadrants are currently in use, now allocate out any spares that are required for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if( localplayers[i] != NULL ) + if( localplayers[i] != nullptr ) { if( ( localplayers[i]->m_iScreenSection < C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT ) || ( localplayers[i]->m_iScreenSection > C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT ) ) @@ -921,22 +923,22 @@ void Minecraft::updatePlayerViewportAssignments() bool Minecraft::addLocalPlayer(int idx) { //int iLocalPlayerC=app.GetLocalPlayerCount(); - if( m_pendingLocalConnections[idx] != NULL ) + if( m_pendingLocalConnections[idx] != nullptr ) { // 4J Stu - Should we ever be in a state where this happens? assert(false); m_pendingLocalConnections[idx]->close(); } m_connectionFailed[idx] = false; - m_pendingLocalConnections[idx] = NULL; + m_pendingLocalConnections[idx] = nullptr; bool success=g_NetworkManager.AddLocalPlayerByUserIndex(idx); if(success) { app.DebugPrintf("Adding temp local player on pad %d\n", idx); - localplayers[idx] = shared_ptr( new MultiplayerLocalPlayer(this, level, user, NULL ) ); - localgameModes[idx] = NULL; + localplayers[idx] = shared_ptr(new MultiplayerLocalPlayer(this, level, user, nullptr)); + localgameModes[idx] = nullptr; updatePlayerViewportAssignments(); @@ -949,7 +951,7 @@ bool Minecraft::addLocalPlayer(int idx) // send the message for(int i=0;i Minecraft::createExtraLocalPlayer(int idx, const wstring& name, int iPad, int iDimension, ClientConnection *clientConnection /*= NULL*/,MultiPlayerLevel *levelpassedin) +shared_ptr Minecraft::createExtraLocalPlayer(int idx, const wstring& name, int iPad, int iDimension, ClientConnection *clientConnection /*= nullptr*/,MultiPlayerLevel *levelpassedin) { - if( clientConnection == NULL) return nullptr; + if( clientConnection == nullptr) return nullptr; if( clientConnection == m_pendingLocalConnections[idx] ) { int tempScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - if( localplayers[idx] != NULL && localgameModes[idx] == NULL ) + if( localplayers[idx] != nullptr && localgameModes[idx] == nullptr ) { // A temp player displaying a connecting screen tempScreenSection = localplayers[idx]->m_iScreenSection; @@ -999,7 +1001,7 @@ shared_ptr Minecraft::createExtraLocalPlayer(int idx, co user->name = name; // Don't need this any more - m_pendingLocalConnections[idx] = NULL; + m_pendingLocalConnections[idx] = nullptr; // Add the connection to the level which will now take responsibility for ticking it // 4J-PB - can't use the dimension from localplayers[idx], since there may be no localplayers at this point @@ -1046,7 +1048,7 @@ shared_ptr Minecraft::createExtraLocalPlayer(int idx, co // Compatibility rule for Win64 id migration // host keeps legacy host XUID, non-host uses persistent uid.dat XUID. INetworkPlayer *localNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(idx); - if(localNetworkPlayer != NULL && localNetworkPlayer->IsHost()) + if(localNetworkPlayer != nullptr && localNetworkPlayer->IsHost()) { playerXUIDOffline = Win64Xuid::GetLegacyEmbeddedHostXuid(); } @@ -1063,11 +1065,11 @@ shared_ptr Minecraft::createExtraLocalPlayer(int idx, co localplayers[idx]->m_iScreenSection = tempScreenSection; - if( levelpassedin == NULL) level->addEntity(localplayers[idx]); // Don't add if we're passing the level in, we only do this from the client connection & we'll be handling adding it ourselves + if( levelpassedin == nullptr) level->addEntity(localplayers[idx]); // Don't add if we're passing the level in, we only do this from the client connection & we'll be handling adding it ourselves localplayers[idx]->SetXboxPad(iPad); - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; + if( localplayers[idx]->input != nullptr ) delete localplayers[idx]->input; localplayers[idx]->input = new Input(); localplayers[idx]->resetPos(); @@ -1096,7 +1098,7 @@ void Minecraft::storeExtraLocalPlayer(int idx) { localplayers[idx] = player; - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; + if( localplayers[idx]->input != nullptr ) delete localplayers[idx]->input; localplayers[idx]->input = new Input(); if(ProfileManager.IsSignedIn(idx)) @@ -1108,14 +1110,14 @@ void Minecraft::storeExtraLocalPlayer(int idx) void Minecraft::removeLocalPlayerIdx(int idx) { bool updateXui = true; - if(localgameModes[idx] != NULL) + if(localgameModes[idx] != nullptr) { if( getLevel( localplayers[idx]->dimension )->isClientSide ) { shared_ptr mplp = localplayers[idx]; ( (MultiPlayerLevel *)getLevel( localplayers[idx]->dimension ) )->removeClientConnection(mplp->connection, true); delete mplp->connection; - mplp->connection = NULL; + mplp->connection = nullptr; g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); } getLevel( localplayers[idx]->dimension )->removeEntity(localplayers[idx]); @@ -1130,13 +1132,13 @@ void Minecraft::removeLocalPlayerIdx(int idx) playerLeftTutorial( idx ); delete localgameModes[idx]; - localgameModes[idx] = NULL; + localgameModes[idx] = nullptr; } - else if( m_pendingLocalConnections[idx] != NULL ) + else if( m_pendingLocalConnections[idx] != nullptr ) { - m_pendingLocalConnections[idx]->sendAndDisconnect( shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) );; + m_pendingLocalConnections[idx]->sendAndDisconnect(std::make_shared(DisconnectPacket::eDisconnect_Quitting));; delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; + m_pendingLocalConnections[idx] = nullptr; g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); } else @@ -1161,18 +1163,18 @@ void Minecraft::removeLocalPlayerIdx(int idx) /* // If we are removing the primary player then there can't be a valid gamemode left anymore, this // pointer will be referring to the one we've just deleted - gameMode = NULL; + gameMode = nullptr; // Remove references to player - player = NULL; - cameraTargetPlayer = NULL; - EntityRenderDispatcher::instance->cameraEntity = NULL; - TileEntityRenderDispatcher::instance->cameraEntity = NULL; + player = nullptr; + cameraTargetPlayer = nullptr; + EntityRenderDispatcher::instance->cameraEntity = nullptr; + TileEntityRenderDispatcher::instance->cameraEntity = nullptr; */ } else if( updateXui ) { gameRenderer->DisableUpdateThread(); - levelRenderer->setLevel(idx, NULL); + levelRenderer->setLevel(idx, nullptr); gameRenderer->EnableUpdateThread(); ui.CloseUIScenes(idx,true); updatePlayerViewportAssignments(); @@ -1200,22 +1202,22 @@ void Minecraft::applyFrameMouseLook() // Per-frame mouse look: consume mouse deltas every frame instead of waiting // for the 20Hz game tick. Apply the same delta to both xRot/yRot AND xRotO/yRotO // so the render interpolation instantly reflects the change without waiting for a tick. - if (level == NULL) return; + if (level == nullptr) return; for (int i = 0; i < XUSER_MAX_COUNT; i++) { - if (localplayers[i] == NULL) continue; + if (localplayers[i] == nullptr) continue; int iPad = localplayers[i]->GetXboxPad(); if (iPad != 0) continue; // Mouse only applies to pad 0 if (!g_KBMInput.IsMouseGrabbed()) continue; - if (localgameModes[iPad] == NULL) continue; + if (localgameModes[iPad] == nullptr) continue; float rawDx, rawDy; g_KBMInput.ConsumeMouseDelta(rawDx, rawDy); if (rawDx == 0.0f && rawDy == 0.0f) continue; - float mouseSensitivity = ((float)app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame)) / 100.0f; + float mouseSensitivity = static_cast(app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame)) / 100.0f; float mdx = rawDx * mouseSensitivity; float mdy = -rawDy * mouseSensitivity; if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook)) @@ -1268,12 +1270,12 @@ void Minecraft::run_middle() AABB::resetPool(); Vec3::resetPool(); - // if (parent == NULL && Display.isCloseRequested()) { // 4J - removed + // if (parent == nullptr && Display.isCloseRequested()) { // 4J - removed // stop(); // } // 4J-PB - AUTOSAVE TIMER - only in the full game and if the player is the host - if(level!=NULL && ProfileManager.IsFullVersion() && g_NetworkManager.IsHost()) + if(level!=nullptr && ProfileManager.IsFullVersion() && g_NetworkManager.IsHost()) { /*if(!bAutosaveTimerSet) { @@ -1296,7 +1298,7 @@ void Minecraft::run_middle() if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack(); @@ -1393,7 +1395,7 @@ void Minecraft::run_middle() } // When we go into the first loaded level, check if the console has active joypads that are not in the game, and bring up the quadrant display to remind them to press start (if the session has space) - if(level!=NULL && bFirstTimeIntoGame && g_NetworkManager.SessionHasSpace()) + if(level!=nullptr && bFirstTimeIntoGame && g_NetworkManager.SessionHasSpace()) { // have a short delay before the display if(iFirstTimeCountdown==0) @@ -1404,7 +1406,7 @@ void Minecraft::run_middle() { for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if((localplayers[i] == NULL) && InputManager.IsPadConnected(i)) + if((localplayers[i] == nullptr) && InputManager.IsPadConnected(i)) { if(!ui.PressStartPlaying(i)) { @@ -1421,10 +1423,10 @@ void Minecraft::run_middle() for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { #ifdef __ORBIS__ - if ( m_pPsPlusUpsell != NULL && m_pPsPlusUpsell->hasResponse() && m_pPsPlusUpsell->m_userIndex == i ) + if ( m_pPsPlusUpsell != nullptr && m_pPsPlusUpsell->hasResponse() && m_pPsPlusUpsell->m_userIndex == i ) { delete m_pPsPlusUpsell; - m_pPsPlusUpsell = NULL; + m_pPsPlusUpsell = nullptr; if ( ProfileManager.HasPlayStationPlus(i) ) { @@ -1633,7 +1635,7 @@ void Minecraft::run_middle() s_prevXButtons[i] = xCurButtons; } bool startJustPressed = s_startPressLatch[i] > 0; - bool tryJoin = !pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && xCurButtons != 0; + bool tryJoin = !pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && xCurButtons != 0 && g_KBMInput.IsWindowFocused(); #else bool tryJoin = !pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef() && InputManager.ButtonPressed(i); #endif @@ -1644,7 +1646,7 @@ void Minecraft::run_middle() // 4J Stu - Check that content restriction information has been received if( !g_NetworkManager.IsLocalGame() ) { - tryJoin = tryJoin && ProfileManager.GetChatAndContentRestrictions(i,true,NULL,NULL,NULL); + tryJoin = tryJoin && ProfileManager.GetChatAndContentRestrictions(i,true,nullptr,nullptr,nullptr); } #endif if(tryJoin) @@ -1684,7 +1686,7 @@ void Minecraft::run_middle() { #ifdef __ORBIS__ bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,NULL,&contentRestricted,NULL); // TODO! + ProfileManager.GetChatAndContentRestrictions(i,false,nullptr,&contentRestricted,nullptr); // TODO! if (!g_NetworkManager.IsLocalGame() && contentRestricted) { @@ -1712,7 +1714,7 @@ void Minecraft::run_middle() if(g_NetworkManager.IsLocalGame() == false) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,nullptr,nullptr); if(chatRestricted) { ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, i ); @@ -1725,7 +1727,7 @@ void Minecraft::run_middle() { // create the localplayer shared_ptr player = localplayers[i]; - if( player == NULL) + if( player == nullptr) { player = createExtraLocalPlayer(i, (convStringToWstring( ProfileManager.GetGamertag(i) )).c_str(), i, level->dimension->id); } @@ -1799,7 +1801,7 @@ void Minecraft::run_middle() int firstEmptyUser = 0; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - if(localplayers[i] == NULL) + if(localplayers[i] == nullptr) { firstEmptyUser = i; break; @@ -1833,7 +1835,7 @@ void Minecraft::run_middle() } #endif - if (pause && level != NULL) + if (pause && level != nullptr) { float lastA = timer->a; timer->advanceTime(); @@ -1862,13 +1864,13 @@ void Minecraft::run_middle() { // 4J - If we are waiting for this connection to do something, then tick it here. // This replaces many of the original Java scenes which would tick the connection while showing that scene - if( m_pendingLocalConnections[idx] != NULL ) + if( m_pendingLocalConnections[idx] != nullptr ) { m_pendingLocalConnections[idx]->tick(); } // reset the player inactive tick - if(localplayers[idx]!=NULL) + if(localplayers[idx]!=nullptr) { // any input received? if((localplayers[idx]->ullButtonsPressed!=0) || InputManager.GetJoypadStick_LX(idx,false)!=0.0f || @@ -1952,8 +1954,8 @@ void Minecraft::run_middle() // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) Display.update(); // 4J - removed // 4J-PB - changing this to be per player - //if (player != NULL && player->isInWall()) options->thirdPersonView = false; - if (player != NULL && player->isInWall()) player->SetThirdPersonView(0); + //if (player != nullptr && player->isInWall()) options->thirdPersonView = false; + if (player != nullptr && player->isInWall()) player->SetThirdPersonView(0); if (!noRender) { @@ -1964,7 +1966,7 @@ void Minecraft::run_middle() if( setLocalPlayerIdx(i) ) { PIXBeginNamedEvent(0,"Game render player idx %d",i); - RenderManager.StateSetViewport((C4JRender::eViewportType)player->m_iScreenSection); + RenderManager.StateSetViewport(static_cast(player->m_iScreenSection)); gameRenderer->render(timer->a, bFirst); bFirst = false; PIXEndNamedEvent(); @@ -1992,7 +1994,7 @@ void Minecraft::run_middle() if( unoccupiedQuadrant > -1 ) { // render a logo - RenderManager.StateSetViewport((C4JRender::eViewportType)(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant)); + RenderManager.StateSetViewport(static_cast(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant)); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); @@ -2063,7 +2065,7 @@ void Minecraft::run_middle() // checkScreenshot(); // 4J - removed /* 4J - removed - if (parent != NULL && !fullscreen) + if (parent != nullptr && !fullscreen) { if (parent.getWidth() != width || parent.getHeight() != height) { @@ -2080,7 +2082,7 @@ void Minecraft::run_middle() checkGlError(L"Post render"); MemSect(0); frames++; - //pause = !isClientSide() && screen != NULL && screen->isPauseScreen(); + //pause = !isClientSide() && screen != nullptr && screen->isPauseScreen(); //pause = g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()); pause = app.IsAppPaused(); @@ -2132,7 +2134,7 @@ void Minecraft::emergencySave() levelRenderer->clear(); AABB::clearPool(); Vec3::clearPool(); - setLevel(NULL); + setLevel(nullptr); } void Minecraft::renderFpsMeter(int64_t tickTime) @@ -2151,7 +2153,7 @@ void Minecraft::renderFpsMeter(int64_t tickTime) glMatrixMode(GL_PROJECTION); glEnable(GL_COLOR_MATERIAL); glLoadIdentity(); - glOrtho(0, (float)width, (float)height, 0, 1000, 3000); + glOrtho(0, static_cast(width), static_cast(height), 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -2000); @@ -2162,16 +2164,16 @@ void Minecraft::renderFpsMeter(int64_t tickTime) t->begin(GL_QUADS); int hh1 = (int) (nsPer60Fps / 200000); t->color(0x20000000); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); + t->vertex(static_cast(0), static_cast(height - hh1), static_cast(0)); + t->vertex(static_cast(0), static_cast(height), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height - hh1), static_cast(0)); t->color(0x20200000); - t->vertex((float)(0), (float)( height - hh1 * 2), (float)( 0)); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1 * 2), (float)( 0)); + t->vertex(static_cast(0), static_cast(height - hh1 * 2), static_cast(0)); + t->vertex(static_cast(0), static_cast(height - hh1), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height - hh1), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height - hh1 * 2), static_cast(0)); t->end(); int64_t totalTime = 0; @@ -2179,13 +2181,13 @@ void Minecraft::renderFpsMeter(int64_t tickTime) { totalTime += Minecraft::frameTimes[i]; } - int hh = (int) (totalTime / 200000 / Minecraft::frameTimes_length); + int hh = static_cast(totalTime / 200000 / Minecraft::frameTimes_length); t->begin(GL_QUADS); t->color(0x20400000); - t->vertex((float)(0), (float)( height - hh), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh), (float)( 0)); + t->vertex(static_cast(0), static_cast(height - hh), static_cast(0)); + t->vertex(static_cast(0), static_cast(height), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height), static_cast(0)); + t->vertex(static_cast(Minecraft::frameTimes_length), static_cast(height - hh), static_cast(0)); t->end(); t->begin(GL_LINES); for (int i = 0; i < Minecraft::frameTimes_length; i++) @@ -2207,16 +2209,16 @@ void Minecraft::renderFpsMeter(int64_t tickTime) int64_t time = Minecraft::frameTimes[i] / 200000; int64_t time2 = Minecraft::tickTimes[i] / 200000; - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height + 0.5f), (float)( 0)); + t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), static_cast(0)); + t->vertex((float)(i + 0.5f), (float)( height + 0.5f), static_cast(0)); // if (Minecraft.frameTimes[i]>nsPer60Fps) { t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); // } else { // t.color(0xff808080 + cc/2 * 256); // } - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - (time - time2) + 0.5f), (float)( 0)); + t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), static_cast(0)); + t->vertex((float)(i + 0.5f), (float)( height - (time - time2) + 0.5f), static_cast(0)); } t->end(); @@ -2231,7 +2233,7 @@ void Minecraft::stop() void Minecraft::pauseGame() { - if (screen != NULL) return; + if (screen != nullptr) return; // setScreen(new PauseScreen()); // 4J - TODO put back in } @@ -2243,7 +2245,7 @@ void Minecraft::resize(int width, int height) this->width = width; this->height = height; - if (screen != NULL) + if (screen != nullptr) { ScreenSizeCalculator ssc(options, width, height); int screenWidth = ssc.getWidth(); @@ -2277,7 +2279,7 @@ void Minecraft::verify() void Minecraft::levelTickUpdateFunc(void* pParam) { - Level* pLevel = (Level*)pParam; + Level* pLevel = static_cast(pParam); pLevel->tick(); } @@ -2310,10 +2312,10 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) gameRenderer->pick(1); #if 0 // 4J - removed - we don't use ChunkCache anymore - if (player != NULL) + if (player != nullptr) { ChunkSource *cs = level->getChunkSource(); - if (dynamic_cast(cs) != NULL) + if (dynamic_cast(cs) != nullptr) { ChunkCache *spcc = (ChunkCache *)cs; @@ -2327,7 +2329,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // soundEngine.playMusicTick(); - if (!pause && level != NULL) gameMode->tick(); + if (!pause && level != nullptr) gameMode->tick(); MemSect(31); glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_TERRAIN)); //L"/terrain.png")); MemSect(0); @@ -2345,33 +2347,33 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) * progressRenderer.progressStagePercentage(0); } else { * serverConnection.tick(); serverConnection.sendPosition(player); } } */ - if (screen == NULL && player != NULL ) + if (screen == nullptr && player != nullptr ) { if (player->getHealth() <= 0 && !ui.GetMenuDisplayed(iPad) ) { - setScreen(NULL); + setScreen(nullptr); } - else if (player->isSleeping() && level != NULL && level->isClientSide) + else if (player->isSleeping() && level != nullptr && level->isClientSide) { // setScreen(new InBedChatScreen()); // 4J - TODO put back in } } - else if (screen != NULL && (dynamic_cast(screen)!=NULL) && !player->isSleeping()) + else if (screen != nullptr && (dynamic_cast(screen)!=nullptr) && !player->isSleeping()) { - setScreen(NULL); + setScreen(nullptr); } - if (screen != NULL) + if (screen != nullptr) { player->missTime = 10000; player->lastClickTick[0] = ticks + 10000; player->lastClickTick[1] = ticks + 10000; } - if (screen != NULL) + if (screen != nullptr) { screen->updateEvents(); - if (screen != NULL) + if (screen != nullptr) { screen->particles->tick(); screen->tick(); @@ -2379,16 +2381,21 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #ifdef _WINDOWS64 - if ((screen != NULL || ui.GetMenuDisplayed(iPad)) && g_KBMInput.IsMouseGrabbed()) + // Mouse grab/release only for the primary (KBM) player — splitscreen + // players use controllers and must never fight over the cursor state. + if (iPad == ProfileManager.GetPrimaryPad()) { - g_KBMInput.SetMouseGrabbed(false); + if ((screen != nullptr || ui.GetMenuDisplayed(iPad)) && g_KBMInput.IsMouseGrabbed()) + { + g_KBMInput.SetMouseGrabbed(false); + } } #endif - if (screen == NULL && !ui.GetMenuDisplayed(iPad) ) + if (screen == nullptr && !ui.GetMenuDisplayed(iPad) ) { #ifdef _WINDOWS64 - if (!g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsWindowFocused()) + if (iPad == ProfileManager.GetPrimaryPad() && !g_KBMInput.IsMouseGrabbed() && g_KBMInput.IsWindowFocused()) { g_KBMInput.SetMouseGrabbed(true); } @@ -2497,7 +2504,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) *piAlt=-1; // 4J-PB another special case for when the player is sleeping in a bed - if (player->isSleeping() && (level != NULL) && level->isClientSide) + if (player->isSleeping() && (level != nullptr) && level->isClientSide) { *piUse=IDS_TOOLTIPS_WAKEUP; } @@ -2553,8 +2560,8 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case Item::spiderEye_Id: // Check that we are actually hungry so will eat this item { - FoodItem *food = (FoodItem *)itemInstance->getItem(); - if (food != NULL && food->canEat(player)) + FoodItem *food = static_cast(itemInstance->getItem()); + if (food != nullptr && food->canEat(player)) { *piUse=IDS_TOOLTIPS_EAT; } @@ -2632,7 +2639,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } } - if (hitResult!=NULL) + if (hitResult!=nullptr) { switch(hitResult->type) { @@ -2647,7 +2654,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) int iTileID=level->getTile(x,y ,z ); int iData = level->getData(x, y, z); - if( gameMode != NULL && gameMode->getTutorial() != NULL ) + if( gameMode != nullptr && gameMode->getTutorial() != nullptr ) { // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints gameMode->getTutorial()->onLookAt(iTileID,iData); @@ -2661,7 +2668,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) * for noteblocks, enderportals and flowerpots in case of non-standard items. * (ie. ignite behaviour) */ - if (bUseItemOn && itemInstance!=NULL) + if (bUseItemOn && itemInstance!=nullptr) { switch (itemInstance->getItem()->id) { @@ -2756,7 +2763,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case Tile::chest_Id: *piAction = IDS_TOOLTIPS_MINE; - *piUse = (Tile::chest->getContainer(level,x,y,z) != NULL) ? IDS_TOOLTIPS_OPEN : -1; + *piUse = (Tile::chest->getContainer(level,x,y,z) != nullptr) ? IDS_TOOLTIPS_OPEN : -1; break; case Tile::enderChest_Id: @@ -2825,7 +2832,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) break; case Tile::jukebox_Id: - if (!bUseItemOn && itemInstance!=NULL) + if (!bUseItemOn && itemInstance!=nullptr) { int iID=itemInstance->getItem()->id; if ( (iID>=Item::record_01_Id) && (iID<=Item::record_12_Id) ) @@ -2845,7 +2852,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) break; case Tile::flowerPot_Id: - if ( !bUseItemOn && (itemInstance != NULL) && (iData == 0) ) + if ( !bUseItemOn && (itemInstance != nullptr) && (iData == 0) ) { int iID = itemInstance->getItem()->id; if (iID<256) // is it a tile? @@ -2906,7 +2913,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case HitResult::ENTITY: eINSTANCEOF entityType = hitResult->entity->GetType(); - if ( (gameMode != NULL) && (gameMode->getTutorial() != NULL) ) + if ( (gameMode != nullptr) && (gameMode->getTutorial() != nullptr) ) { // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints gameMode->getTutorial()->onLookAtEntity(hitResult->entity); @@ -2917,7 +2924,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) { heldItem = player->inventory->getSelected(); } - int heldItemId = heldItem != NULL ? heldItem->getItem()->id : -1; + int heldItemId = heldItem != nullptr ? heldItem->getItem()->id : -1; switch(entityType) { @@ -3352,7 +3359,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) shared_ptr itemFrame = dynamic_pointer_cast(hitResult->entity); // is the frame occupied? - if(itemFrame->getItem()!=NULL) + if(itemFrame->getItem()!=nullptr) { // rotate the item *piUse=IDS_TOOLTIPS_ROTATE; @@ -3383,7 +3390,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case eTYPE_ZOMBIE: { shared_ptr zomb = dynamic_pointer_cast(hitResult->entity); - static GoldenAppleItem *goldapple = (GoldenAppleItem *) Item::apple_gold; + static GoldenAppleItem *goldapple = static_cast(Item::apple_gold); //zomb->hasEffect(MobEffect::weakness) - not present on client. if ( zomb->isVillager() && zomb->isWeakened() && (heldItemId == Item::apple_gold_Id) && !goldapple->isFoil(heldItem) ) @@ -3555,7 +3562,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) { player->inventory->swapPaint(wheel); - if( gameMode != NULL && gameMode->getTutorial() != NULL ) + if( gameMode != nullptr && gameMode->getTutorial() != nullptr ) { // 4J Stu - For the tutorial we want to be able to record what items we are using so that we can give hints gameMode->getTutorial()->onSelectedItemChanged(player->inventory->getSelected()); @@ -3705,7 +3712,9 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) app.EnableDebugOverlay(options->renderDebug,iPad); #else // 4J Stu - The xbox uses a completely different way of navigating to this scene - ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, eUILayer_Debug); + // Always open in the fullscreen group so the overlay spans the full window + // regardless of split-screen viewport configuration. + ui.NavigateToScene(0, eUIScene_DebugOverlay, nullptr, eUILayer_Debug, eUIGroup_Fullscreen); #endif #endif } @@ -3769,7 +3778,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) app.LoadCreativeMenu(iPad,player); } // 4J-PB - Microsoft request that we use the 3x3 crafting if someone presses X while at the workbench - else if ((hitResult!=NULL) && (hitResult->type == HitResult::TILE) && (level->getTile(hitResult->x, hitResult->y, hitResult->z) == Tile::workBench_Id)) + else if ((hitResult!=nullptr) && (hitResult->type == HitResult::TILE) && (level->getTile(hitResult->x, hitResult->y, hitResult->z) == Tile::workBench_Id)) { //ui.PlayUISFX(eSFX_Press); //app.LoadXuiCrafting3x3Menu(iPad,player,hitResult->x, hitResult->y, hitResult->z); @@ -3791,7 +3800,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) { app.DebugPrintf("PAUSE PRESS PROCESSING - ipad = %d, NavigateToScene\n",player->GetXboxPad()); ui.PlayUISFX(eSFX_Press); - ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); + ui.NavigateToScene(iPad, eUIScene_PauseMenu, nullptr, eUILayer_Scene); } if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_DROP)) @@ -3826,12 +3835,12 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // 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<GetCount() == 1)) + if(selectedItem != nullptr) iCount=selectedItem->GetCount(); + if(selectedItem != nullptr && !( (player->ullButtonsPressed&(1LL<GetCount() == 1)) { itemName = selectedItem->getHoverName(); } - if( !(player->ullButtonsPressed&(1LL<GetCount() <= 1) ) ui.SetSelectedItem( iPad, itemName ); + if( !(player->ullButtonsPressed&(1LL<GetCount() <= 1) ) ui.SetSelectedItem( iPad, itemName ); } if (player->ullButtonsPressed&(1LL<type == HitResult::TILE) @@ -3918,7 +3927,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // 4J-PB if (InputManager.GetValue(iPad, ACTION_MENU_CANCEL) > 0 && gameMode->isInputAllowed(ACTION_MENU_CANCEL)) { - setScreen(NULL); + setScreen(nullptr); } } @@ -3942,7 +3951,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) #if 0 // 4J - TODO - some replacement for input handling... - if (screen == NULL || screen.passEvents) + if (screen == nullptr || screen.passEvents) { while (Mouse.next()) { @@ -4085,9 +4094,9 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #endif - if (level != NULL) + if (level != nullptr) { - if (player != NULL) + if (player != nullptr) { recheckPlayerIn++; if (recheckPlayerIn == 30) @@ -4133,7 +4142,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // 4J - this doesn't fully tick the animateTick here, but does register this player's position. The actual // work is now done in Level::animateTickDoWork() so we can take into account multiple players in the one level. - if (!pause && levels[i] != NULL) levels[i]->animateTick(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + if (!pause && levels[i] != nullptr) levels[i]->animateTick(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); if( levelsTickedFlags & ( 1 << i ) ) continue; // Don't tick further if we've already ticked this level this frame levelsTickedFlags |= (1 << i); @@ -4146,7 +4155,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // level.addEntity(player); // } // } - if( levels[i] != NULL ) + if( levels[i] != nullptr ) { if (!pause) { @@ -4162,7 +4171,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) int currPlayerIdx = getLocalPlayerIdx(); for( int idx = 0; idx < XUSER_MAX_COUNT; idx++ ) { - if(localplayers[idx]!=NULL) + if(localplayers[idx]!=nullptr) { if( localplayers[idx]->level == levels[i] ) { @@ -4240,7 +4249,7 @@ void Minecraft::reloadSound() bool Minecraft::isClientSide() { - return level != NULL && level->isClientSide; + return level != nullptr && level->isClientSide; } void Minecraft::selectLevel(ConsoleSaveFile *saveFile, const wstring& levelId, const wstring& levelName, LevelSettings *levelSettings) @@ -4259,8 +4268,8 @@ bool Minecraft::loadSlot(const wstring& userName, int slot) void Minecraft::releaseLevel(int message) { - //this->level = NULL; - setLevel(NULL, message); + //this->level = nullptr; + setLevel(nullptr, message); } // 4J Stu - This code was within setLevel, but I moved it out so that I can call it at a better @@ -4291,14 +4300,14 @@ MultiPlayerLevel *Minecraft::getLevel(int dimension) // 4J Stu - Removed as redundant with default values in params. //void Minecraft::setLevel(Level *level, bool doForceStatsSave /*= true*/) //{ -// setLevel(level, -1, NULL, doForceStatsSave); +// setLevel(level, -1, nullptr, doForceStatsSave); //} // Also causing ambiguous call for some reason // as it is matching shared_ptr from the func below with bool from this one //void Minecraft::setLevel(Level *level, const wstring& message, bool doForceStatsSave /*= true*/) //{ -// setLevel(level, message, NULL, doForceStatsSave); +// setLevel(level, message, nullptr, doForceStatsSave); //} void Minecraft::forceaddLevel(MultiPlayerLevel *level) @@ -4309,13 +4318,13 @@ void Minecraft::forceaddLevel(MultiPlayerLevel *level) else levels[0] = level; } -void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_ptr forceInsertPlayer /*=NULL*/, bool doForceStatsSave /*=true*/, bool bPrimaryPlayerSignedOut /*=false*/) +void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_ptr forceInsertPlayer /*=nullptr*/, bool doForceStatsSave /*=true*/, bool bPrimaryPlayerSignedOut /*=false*/) { EnterCriticalSection(&m_setLevelCS); bool playerAdded = false; this->cameraTargetPlayer = nullptr; - if(progressRenderer != NULL) + if(progressRenderer != nullptr) { this->progressRenderer->progressStart(message); this->progressRenderer->progressStage(-1); @@ -4324,14 +4333,14 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt // 4J-PB - since we now play music in the menu, just let it keep playing //soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); - // 4J - stop update thread from processing this level, which blocks until it is safe to move on - will be re-enabled if we set the level to be non-NULL + // 4J - stop update thread from processing this level, which blocks until it is safe to move on - will be re-enabled if we set the level to be non-nullptr gameRenderer->DisableUpdateThread(); - if (level == NULL || player == NULL) + if (level == nullptr || player == nullptr) { for (int i = 0; i < XUSER_MAX_COUNT; ++i) { - if (localitemInHandRenderers[i] != NULL) + if (localitemInHandRenderers[i] != nullptr) { localitemInHandRenderers[i]->reset(); } @@ -4340,75 +4349,75 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt for(unsigned int i = 0; i < levels.length; ++i) { - // 4J We only need to save out in multiplayer is we are setting the level to NULL + // 4J We only need to save out in multiplayer is we are setting the level to nullptr // If we ever go back to making single player only then this will not work properly! - if (levels[i] != NULL && level == NULL) + if (levels[i] != nullptr && level == nullptr) { // 4J Stu - This is really only relevant for single player (ie not what we do at the moment) - if((doForceStatsSave==true) && player!=NULL) + if((doForceStatsSave==true) && player!=nullptr) forceStatsSave(player->GetXboxPad() ); - // 4J Stu - Added these for the case when we exit a level so we are setting the level to NULL - // The level renderer needs to have it's stored level set to NULL so that it doesn't break next time we set one - if (levelRenderer != NULL) + // 4J Stu - Added these for the case when we exit a level so we are setting the level to nullptr + // The level renderer needs to have it's stored level set to nullptr so that it doesn't break next time we set one + if (levelRenderer != nullptr) { for(DWORD p = 0; p < XUSER_MAX_COUNT; ++p) { - levelRenderer->setLevel(p, NULL); + levelRenderer->setLevel(p, nullptr); } } - if (particleEngine != NULL) particleEngine->setLevel(NULL); + if (particleEngine != nullptr) particleEngine->setLevel(nullptr); } } - // 4J If we are setting the level to NULL then we are exiting, so delete the levels - if( level == NULL ) + // 4J If we are setting the level to nullptr then we are exiting, so delete the levels + if( level == nullptr ) { - if(levels[0]!=NULL) + if(levels[0]!=nullptr) { delete levels[0]; - levels[0] = NULL; + levels[0] = nullptr; // Both level share the same savedDataStorage - if(levels[1]!=NULL) levels[1]->savedDataStorage = NULL; + if(levels[1]!=nullptr) levels[1]->savedDataStorage = nullptr; } - if(levels[1]!=NULL) + if(levels[1]!=nullptr) { delete levels[1]; - levels[1] = NULL; + levels[1] = nullptr; } - if(levels[2]!=NULL) + if(levels[2]!=nullptr) { delete levels[2]; - levels[2] = NULL; + levels[2] = nullptr; } // Delete all the player objects for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { shared_ptr mplp = localplayers[idx]; - if(mplp != NULL && mplp->connection != NULL ) + if(mplp != nullptr && mplp->connection != nullptr ) { delete mplp->connection; - mplp->connection = NULL; + mplp->connection = nullptr; } - if( localgameModes[idx] != NULL ) + if( localgameModes[idx] != nullptr ) { delete localgameModes[idx]; - localgameModes[idx] = NULL; + localgameModes[idx] = nullptr; } - if( m_pendingLocalConnections[idx] != NULL ) + if( m_pendingLocalConnections[idx] != nullptr ) { delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; + m_pendingLocalConnections[idx] = nullptr; } localplayers[idx] = nullptr; } // If we are removing the primary player then there can't be a valid gamemode left anymore, this // pointer will be referring to the one we've just deleted - gameMode = NULL; + gameMode = nullptr; // Remove references to player player = nullptr; cameraTargetPlayer = nullptr; @@ -4417,7 +4426,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt } this->level = level; - if (level != NULL) + if (level != nullptr) { int dimId = level->dimension->id; if (dimId == -1) levels[1] = level; @@ -4426,7 +4435,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt // If no player has been set, then this is the first level to be set this game, so set up // a primary player & initialise some other things - if (player == NULL) + if (player == nullptr) { int iPrimaryPlayer = ProfileManager.GetPrimaryPad(); @@ -4447,7 +4456,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt // On Windows, the implementation has been changed to use a per-client pseudo XUID based on `uid.dat`. // To maintain player data compatibility with existing worlds, the world host (the first player) will use the previous embedded pseudo XUID. INetworkPlayer *localNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(iPrimaryPlayer); - if(localNetworkPlayer != NULL && localNetworkPlayer->IsHost()) + if(localNetworkPlayer != nullptr && localNetworkPlayer->IsHost()) { playerXUIDOffline = Win64Xuid::GetLegacyEmbeddedHostXuid(); } @@ -4470,32 +4479,32 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt for(int i=0;iresetPos(); // gameMode.initPlayer(player); - if (level != NULL) + if (level != nullptr) { level->addEntity(player); playerAdded = true; } } - if(player->input != NULL) delete player->input; + if(player->input != nullptr) delete player->input; player->input = new Input(); - if (levelRenderer != NULL) levelRenderer->setLevel(player->GetXboxPad(), level); - if (particleEngine != NULL) particleEngine->setLevel(level); + if (levelRenderer != nullptr) levelRenderer->setLevel(player->GetXboxPad(), level); + if (particleEngine != nullptr) particleEngine->setLevel(level); #if 0 // 4J - removed - we don't use ChunkCache anymore ChunkSource *cs = level->getChunkSource(); - if (dynamic_cast(cs) != NULL) + if (dynamic_cast(cs) != nullptr) { ChunkCache *spcc = (ChunkCache *)cs; @@ -4510,7 +4519,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt for(int i=0;iclearAll(); player = nullptr; - // Clear all players if the new level is NULL + // Clear all players if the new level is nullptr for(int i=0;iclose(); - m_pendingLocalConnections[i] = NULL; + if( m_pendingLocalConnections[i] != nullptr ) m_pendingLocalConnections[i]->close(); + m_pendingLocalConnections[i] = nullptr; localplayers[i] = nullptr; - localgameModes[i] = NULL; + localgameModes[i] = nullptr; } } @@ -4542,7 +4551,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt void Minecraft::prepareLevel(int title) { - if(progressRenderer != NULL) + if(progressRenderer != nullptr) { this->progressRenderer->progressStart(title); this->progressRenderer->progressStage(IDS_PROGRESS_BUILDING_TERRAIN); @@ -4555,15 +4564,15 @@ void Minecraft::prepareLevel(int title) ChunkSource *cs = level->getChunkSource(); Pos *spawnPos = level->getSharedSpawnPos(); - if (player != NULL) + if (player != nullptr) { - spawnPos->x = (int) player->x; - spawnPos->z = (int) player->z; + spawnPos->x = static_cast(player->x); + spawnPos->z = static_cast(player->z); } #if 0 // 4J - removed - we don't use ChunkCache anymore - if (dynamic_cast(cs)!=NULL) + if (dynamic_cast(cs)!=nullptr) { ChunkCache *spcc = (ChunkCache *) cs; @@ -4575,7 +4584,7 @@ void Minecraft::prepareLevel(int title) { for (int z = -r; z <= r; z += 16) { - if(progressRenderer != NULL) this->progressRenderer->progressStagePercentage((pp++) * 100 / max); + if(progressRenderer != nullptr) this->progressRenderer->progressStagePercentage((pp++) * 100 / max); level->getTile(spawnPos->x + x, 64, spawnPos->z + z); if (!gameMode->isCutScene()) { } @@ -4584,7 +4593,7 @@ void Minecraft::prepareLevel(int title) delete spawnPos; if (!gameMode->isCutScene()) { - if(progressRenderer != NULL) this->progressRenderer->progressStage(IDS_PROGRESS_SIMULATING_WORLD); + if(progressRenderer != nullptr) this->progressRenderer->progressStage(IDS_PROGRESS_SIMULATING_WORLD); max = 2000; } } @@ -4620,7 +4629,7 @@ void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) level->validateSpawn(); level->removeAllPendingEntityRemovals(); - if (localPlayer != NULL) + if (localPlayer != nullptr) { level->removeEntity(localPlayer); } @@ -4641,7 +4650,7 @@ void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) #ifdef _WINDOWS64 // Same compatibility rule as create/init paths. INetworkPlayer *localNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(iTempPad); - if(localNetworkPlayer != NULL && localNetworkPlayer->IsHost()) + if(localNetworkPlayer != nullptr && localNetworkPlayer->IsHost()) { playerXUIDOffline = Win64Xuid::GetLegacyEmbeddedHostXuid(); } @@ -4705,7 +4714,7 @@ void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) level->addEntity(player); gameMode->initPlayer(player); - if(player->input != NULL) delete player->input; + if(player->input != nullptr) delete player->input; player->input = new Input(); player->entityId = newEntityId; player->animateRespawn(); @@ -4721,7 +4730,7 @@ void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) //SetEvent(m_hPlayerRespawned); player->SetPlayerRespawned(true); - if (dynamic_cast(screen) != NULL) setScreen(NULL); + if (dynamic_cast(screen) != nullptr) setScreen(nullptr); gameRenderer->EnableUpdateThread(); } @@ -4733,8 +4742,8 @@ void Minecraft::start(const wstring& name, const wstring& sid) void Minecraft::startAndConnectTo(const wstring& name, const wstring& sid, const wstring& url) { - bool fullScreen = false; - wstring userName = name; + const bool fullScreen = false; + const wstring userName = name; /* 4J - removed window handling things here final Frame frame = new Frame("Minecraft"); @@ -4754,9 +4763,14 @@ void Minecraft::startAndConnectTo(const wstring& name, const wstring& sid, const Minecraft *minecraft; // 4J - was new Minecraft(frame, canvas, NULL, 854, 480, fullScreen); + // Logical width is proportional to the real screen aspect ratio so that + // the ortho projection and HUD layout match the viewport without stretching. + extern int g_iScreenWidth; + extern int g_iScreenHeight; + constexpr int logicalH = 720; + const int logicalW = logicalH * g_iScreenWidth / g_iScreenHeight; - minecraft = new Minecraft(NULL, NULL, NULL, 1280, 720, fullScreen); - + minecraft = new Minecraft(nullptr, nullptr, nullptr, logicalW, logicalH, fullScreen); /* - 4J - removed { @Override @@ -4776,7 +4790,7 @@ void Minecraft::startAndConnectTo(const wstring& name, const wstring& sid, const // 4J Stu - We never want the player to be DemoUser, we always want them to have their gamertag displayed //if (ProfileManager.IsFullVersion()) { - if (userName != L"" && sid != L"") // 4J - username & side were compared with NULL rather than empty strings + if (userName != L"" && sid != L"") // 4J - username & side were compared with nullptr rather than empty strings { minecraft->user = new User(userName, sid); } @@ -4791,7 +4805,7 @@ void Minecraft::startAndConnectTo(const wstring& name, const wstring& sid, const //} /* 4J - TODO - if (url != NULL) + if (url != nullptr) { String[] tokens = url.split(":"); minecraft.connectTo(tokens[0], Integer.parseInt(tokens[1])); @@ -4856,7 +4870,7 @@ void Minecraft::main() #if 0 for(unsigned int i = 0; i < Item::items.length; ++i) { - if(Item::items[i] != NULL) + if(Item::items[i] != nullptr) { app.DebugPrintf("%ls\n", i, app.GetString( Item::items[i]->getDescriptionId() )); } @@ -4866,7 +4880,7 @@ void Minecraft::main() for(unsigned int i = 0; i < 256; ++i) { - if(Tile::tiles[i] != NULL) + if(Tile::tiles[i] != nullptr) { app.DebugPrintf("%ls\n", i, app.GetString( Tile::tiles[i]->getDescriptionId() )); } @@ -4898,7 +4912,7 @@ void Minecraft::main() bool Minecraft::renderNames() { - if (m_instance == NULL || !m_instance->options->hideGui) + if (m_instance == nullptr || !m_instance->options->hideGui) { return true; } @@ -4907,17 +4921,17 @@ bool Minecraft::renderNames() bool Minecraft::useFancyGraphics() { - return (m_instance != NULL && m_instance->options->fancyGraphics); + return (m_instance != nullptr && m_instance->options->fancyGraphics); } bool Minecraft::useAmbientOcclusion() { - return (m_instance != NULL && m_instance->options->ambientOcclusion != Options::AO_OFF); + return (m_instance != nullptr && m_instance->options->ambientOcclusion != Options::AO_OFF); } bool Minecraft::renderDebug() { - return (m_instance != NULL && m_instance->options->renderDebug); + return (m_instance != nullptr && m_instance->options->renderDebug); } bool Minecraft::handleClientSideCommand(const wstring& chatMessage) @@ -4956,7 +4970,7 @@ if (gameMode->instaBuild) return; if (!down) missTime = 0; if (button == 0 && missTime > 0) return; -if (down && hitResult != NULL && hitResult->type == HitResult::TILE && button == 0) +if (down && hitResult != nullptr && hitResult->type == HitResult::TILE && button == 0) { int x = hitResult->x; int y = hitResult->y; @@ -4988,7 +5002,7 @@ bool mayUse = true; // 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button -if(button==1 && (player->isSleeping() && level != NULL && level->isClientSide)) +if(button==1 && (player->isSleeping() && level != nullptr && level->isClientSide)) { shared_ptr mplp = dynamic_pointer_cast( player ); @@ -5002,9 +5016,9 @@ if(mplp) mplp->StopSleeping(); //} } -if (hitResult == NULL) +if (hitResult == nullptr) { -if (button == 0 && !(dynamic_cast(gameMode) != NULL)) missTime = 10; +if (button == 0 && !(dynamic_cast(gameMode) != nullptr)) missTime = 10; } else if (hitResult->type == HitResult::ENTITY) { @@ -5040,21 +5054,21 @@ gameMode->startDestroyBlock(x, y, z, hitResult->f); else { shared_ptr item = player->inventory->getSelected(); -int oldCount = item != NULL ? item->count : 0; +int oldCount = item != nullptr ? item->count : 0; if (gameMode->useItemOn(player, level, item, x, y, z, face)) { mayUse = false; app.DebugPrintf("Player %d is swinging\n",player->GetXboxPad()); player->swing(); } -if (item == NULL) +if (item == nullptr) { return; } if (item->count == 0) { -player->inventory->items[player->inventory->selected] = NULL; +player->inventory->items[player->inventory->selected] = nullptr; } else if (item->count != oldCount) { @@ -5066,7 +5080,7 @@ gameRenderer->itemInHandRenderer->itemPlaced(); if (mayUse && button == 1) { shared_ptr item = player->inventory->getSelected(); -if (item != NULL) +if (item != nullptr) { if (gameMode->useItem(player, level, item)) { @@ -5087,7 +5101,7 @@ bool Minecraft::isTutorial() { return m_inFullTutorialBits > 0; - /*if( gameMode != NULL && gameMode->isTutorial() ) + /*if( gameMode != nullptr && gameMode->isTutorial() ) { return true; } @@ -5122,7 +5136,7 @@ void Minecraft::playerLeftTutorial(int iPad) #ifndef _XBOX_ONE for(DWORD idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(localplayers[idx] != NULL) + if(localplayers[idx] != nullptr) { TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } @@ -5153,7 +5167,7 @@ void Minecraft::inGameSignInCheckAllPrivilegesCallback(LPVOID lpParam, bool hasP { // create the local player for the iPad shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) + if( player == nullptr) { if( pClass->level->isClientSide ) { @@ -5163,7 +5177,7 @@ void Minecraft::inGameSignInCheckAllPrivilegesCallback(LPVOID lpParam, bool hasP { // create the local player for the iPad shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) + if( player == nullptr) { player = pClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pClass->level->dimension->id); } @@ -5180,7 +5194,7 @@ int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad, int int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) #endif { - Minecraft* pMinecraftClass = (Minecraft*)pParam; + Minecraft* pMinecraftClass = static_cast(pParam); if(g_NetworkManager.IsInSession()) { @@ -5191,7 +5205,7 @@ int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) } // If sign in succeded, we're in game and this player isn't already playing, continue - if(bContinue==true && g_NetworkManager.IsInSession() && pMinecraftClass->localplayers[iPad] == NULL) + if(bContinue==true && g_NetworkManager.IsInSession() && pMinecraftClass->localplayers[iPad] == nullptr) { // It's possible that the player has not signed in - they can back out or choose no for the converttoguest if(ProfileManager.IsSignedIn(iPad)) @@ -5217,7 +5231,7 @@ int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) { #ifdef __ORBIS__ bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(iPad,false,NULL,&contentRestricted,NULL); // TODO! + ProfileManager.GetChatAndContentRestrictions(iPad,false,nullptr,&contentRestricted,nullptr); // TODO! if (!g_NetworkManager.IsLocalGame() && contentRestricted) { @@ -5238,7 +5252,7 @@ int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) { // create the local player for the iPad shared_ptr player = pMinecraftClass->localplayers[iPad]; - if( player == NULL) + if( player == nullptr) { player = pMinecraftClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pMinecraftClass->level->dimension->id); } @@ -5307,7 +5321,7 @@ ColourTable *Minecraft::getColourTable() ColourTable *colours = selected->getColourTable(); - if(colours == NULL) + if(colours == nullptr) { colours = skins->getDefault()->getColourTable(); } diff --git a/Minecraft.Client/Minecraft.h b/Minecraft.Client/Minecraft.h index 91c20c142..2c5203d82 100644 --- a/Minecraft.Client/Minecraft.h +++ b/Minecraft.Client/Minecraft.h @@ -114,7 +114,7 @@ public: void addPendingLocalConnection(int idx, ClientConnection *connection); void connectionDisconnected(int idx, DisconnectPacket::eDisconnectReason reason) { m_connectionFailed[idx] = true; m_connectionFailedReason[idx] = reason; } - shared_ptr createExtraLocalPlayer(int idx, const wstring& name, int pad, int iDimension, ClientConnection *clientConnection = NULL,MultiPlayerLevel *levelpassedin=NULL); + shared_ptr createExtraLocalPlayer(int idx, const wstring& name, int pad, int iDimension, ClientConnection *clientConnection = nullptr,MultiPlayerLevel *levelpassedin=nullptr); void createPrimaryLocalPlayer(int iPad); bool setLocalPlayerIdx(int idx); int getLocalPlayerIdx(); diff --git a/Minecraft.Client/MinecraftServer.cpp b/Minecraft.Client/MinecraftServer.cpp index 55b02cb98..1e3ed74ef 100644 --- a/Minecraft.Client/MinecraftServer.cpp +++ b/Minecraft.Client/MinecraftServer.cpp @@ -66,7 +66,7 @@ #define DEBUG_SERVER_DONT_SPAWN_MOBS 0 //4J Added -MinecraftServer *MinecraftServer::server = NULL; +MinecraftServer *MinecraftServer::server = nullptr; bool MinecraftServer::setTimeAtEndOfTick = false; int64_t MinecraftServer::setTime = 0; bool MinecraftServer::setTimeOfDayAtEndOfTick = false; @@ -97,17 +97,17 @@ static bool ShouldUseDedicatedServerProperties() static int GetDedicatedServerInt(Settings *settings, const wchar_t *key, int defaultValue) { - return (ShouldUseDedicatedServerProperties() && settings != NULL) ? settings->getInt(key, defaultValue) : defaultValue; + return (ShouldUseDedicatedServerProperties() && settings != nullptr) ? settings->getInt(key, defaultValue) : defaultValue; } static bool GetDedicatedServerBool(Settings *settings, const wchar_t *key, bool defaultValue) { - return (ShouldUseDedicatedServerProperties() && settings != NULL) ? settings->getBoolean(key, defaultValue) : defaultValue; + return (ShouldUseDedicatedServerProperties() && settings != nullptr) ? settings->getBoolean(key, defaultValue) : defaultValue; } static wstring GetDedicatedServerString(Settings *settings, const wchar_t *key, const wstring &defaultValue) { - return (ShouldUseDedicatedServerProperties() && settings != NULL) ? settings->getString(key, defaultValue) : defaultValue; + return (ShouldUseDedicatedServerProperties() && settings != nullptr) ? settings->getString(key, defaultValue) : defaultValue; } static void PrintConsoleLine(const wchar_t *prefix, const wstring &message) @@ -148,12 +148,12 @@ static wstring JoinConsoleCommandTokens(const vector &tokens, size_t st static shared_ptr FindPlayerByName(PlayerList *playerList, const wstring &name) { - if (playerList == NULL) return nullptr; + if (playerList == nullptr) return nullptr; for (size_t i = 0; i < playerList->players.size(); ++i) { shared_ptr player = playerList->players[i]; - if (player != NULL && equalsIgnoreCase(player->getName(), name)) + if (player != nullptr && equalsIgnoreCase(player->getName(), name)) { return player; } @@ -166,7 +166,7 @@ static void SetAllLevelTimes(MinecraftServer *server, int value) { for (unsigned int i = 0; i < server->levels.length; ++i) { - if (server->levels[i] != NULL) + if (server->levels[i] != nullptr) { server->levels[i]->setDayTime(value); } @@ -175,7 +175,7 @@ static void SetAllLevelTimes(MinecraftServer *server, int value) static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCommand) { - if (server == NULL) + if (server == nullptr) return false; wstring command = trimString(rawCommand); @@ -209,9 +209,9 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom if (action == L"list") { - wstring playerNames = (playerList != NULL) ? playerList->getPlayerNames() : L""; + wstring playerNames = (playerList != nullptr) ? playerList->getPlayerNames() : L""; if (playerNames.empty()) playerNames = L"(none)"; - server->info(L"Players (" + std::to_wstring((playerList != NULL) ? playerList->getPlayerCount() : 0) + L"): " + playerNames); + server->info(L"Players (" + std::to_wstring((playerList != nullptr) ? playerList->getPlayerCount() : 0) + L"): " + playerNames); return true; } @@ -224,9 +224,9 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } wstring message = L"[Server] " + JoinConsoleCommandTokens(tokens, 1); - if (playerList != NULL) + if (playerList != nullptr) { - playerList->broadcastAll(shared_ptr(new ChatPacket(message))); + playerList->broadcastAll(std::make_shared(message)); } server->info(message); return true; @@ -234,9 +234,9 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom if (action == L"save-all") { - if (playerList != NULL) + if (playerList != nullptr) { - playerList->saveAll(NULL, false); + playerList->saveAll(nullptr, false); } server->info(L"World saved."); return true; @@ -267,7 +267,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom for (unsigned int i = 0; i < server->levels.length; ++i) { - if (server->levels[i] != NULL) + if (server->levels[i] != nullptr) { server->levels[i]->setDayTime(server->levels[i]->getDayTime() + delta); } @@ -323,7 +323,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom return false; } - if (server->levels[0] == NULL) + if (server->levels[0] == nullptr) { server->warn(L"The overworld is not loaded."); return false; @@ -370,12 +370,12 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom shared_ptr subject = FindPlayerByName(playerList, tokens[1]); shared_ptr destination = FindPlayerByName(playerList, tokens[2]); - if (subject == NULL) + if (subject == nullptr) { server->warn(L"Unknown player: " + tokens[1]); return false; } - if (destination == NULL) + if (destination == nullptr) { server->warn(L"Unknown player: " + tokens[2]); return false; @@ -401,7 +401,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } shared_ptr player = FindPlayerByName(playerList, tokens[1]); - if (player == NULL) + if (player == nullptr) { server->warn(L"Unknown player: " + tokens[1]); return false; @@ -425,7 +425,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom server->warn(L"Invalid aux value: " + tokens[4]); return false; } - if (itemId <= 0 || Item::items[itemId] == NULL) + if (itemId <= 0 || Item::items[itemId] == nullptr) { server->warn(L"Unknown item id: " + std::to_wstring(itemId)); return false; @@ -438,7 +438,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom shared_ptr itemInstance(new ItemInstance(itemId, amount, aux)); shared_ptr drop = player->drop(itemInstance); - if (drop != NULL) + if (drop != nullptr) { drop->throwTime = 0; } @@ -455,7 +455,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } shared_ptr player = FindPlayerByName(playerList, tokens[1]); - if (player == NULL) + if (player == nullptr) { server->warn(L"Unknown player: " + tokens[1]); return false; @@ -475,14 +475,14 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } shared_ptr selectedItem = player->getSelectedItem(); - if (selectedItem == NULL) + if (selectedItem == nullptr) { server->warn(L"The player is not holding an item."); return false; } Enchantment *enchantment = Enchantment::enchantments[enchantmentId]; - if (enchantment == NULL) + if (enchantment == nullptr) { server->warn(L"Unknown enchantment id: " + std::to_wstring(enchantmentId)); return false; @@ -499,12 +499,12 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom if (selectedItem->hasTag()) { ListTag *enchantmentTags = selectedItem->getEnchantmentTags(); - if (enchantmentTags != NULL) + if (enchantmentTags != nullptr) { for (int i = 0; i < enchantmentTags->size(); i++) { int type = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - if (Enchantment::enchantments[type] != NULL && !Enchantment::enchantments[type]->isCompatibleWith(enchantment)) + if (Enchantment::enchantments[type] != nullptr && !Enchantment::enchantments[type]->isCompatibleWith(enchantment)) { server->warn(L"That enchantment conflicts with an existing enchantment on the selected item."); return false; @@ -527,7 +527,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } shared_ptr player = FindPlayerByName(playerList, tokens[1]); - if (player == NULL) + if (player == nullptr) { server->warn(L"Unknown player: " + tokens[1]); return false; @@ -545,10 +545,10 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom MinecraftServer::MinecraftServer() { // 4J - added initialisers - connection = NULL; - settings = NULL; - players = NULL; - commands = NULL; + connection = nullptr; + settings = nullptr; + players = nullptr; + commands = nullptr; running = true; m_bLoaded = false; stopped = false; @@ -567,8 +567,9 @@ MinecraftServer::MinecraftServer() m_texturePackId = 0; maxBuildHeight = Level::maxBuildHeight; playerIdleTimeout = 0; - m_postUpdateThread = NULL; + m_postUpdateThread = nullptr; forceGameType = false; + m_spawnProtectionRadius = 0; commandDispatcher = new ServerCommandDispatcher(); InitializeCriticalSection(&m_consoleInputCS); @@ -615,6 +616,10 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW logger.info("Loading properties"); #endif settings = new Settings(new File(L"server.properties")); + // Dedicated-only: spawn-protection radius in blocks; 0 disables protection. + m_spawnProtectionRadius = GetDedicatedServerInt(settings, L"spawn-protection", 0); + if (m_spawnProtectionRadius < 0) m_spawnProtectionRadius = 0; + if (m_spawnProtectionRadius > 256) m_spawnProtectionRadius = 256; app.SetGameHostOption(eGameHostOption_Difficulty, GetDedicatedServerInt(settings, L"difficulty", app.GetGameHostOption(eGameHostOption_Difficulty))); app.SetGameHostOption(eGameHostOption_GameType, GetDedicatedServerInt(settings, L"gamemode", app.GetGameHostOption(eGameHostOption_GameType))); @@ -631,6 +636,7 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW app.DebugPrintf("ServerSettings: pvp is %s\n",(app.GetGameHostOption(eGameHostOption_PvP)>0)?"on":"off"); app.DebugPrintf("ServerSettings: fire spreads is %s\n",(app.GetGameHostOption(eGameHostOption_FireSpreads)>0)?"on":"off"); app.DebugPrintf("ServerSettings: tnt explodes is %s\n",(app.GetGameHostOption(eGameHostOption_TNT)>0)?"on":"off"); + app.DebugPrintf("ServerSettings: spawn protection radius is %d\n", m_spawnProtectionRadius); app.DebugPrintf("\n"); // TODO 4J Stu - Init a load of settings based on data passed as params @@ -651,7 +657,7 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW setFlightAllowed(GetDedicatedServerBool(settings, L"allow-flight", true)); // 4J Stu - Enabling flight to stop it kicking us when we use it -#ifdef _DEBUG_MENUS_ENABLED +#if (defined _DEBUG_MENUS_ENABLED && defined _DEBUG) setFlightAllowed(true); #endif @@ -690,10 +696,10 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW #endif // 4J-JEV: Need to wait for levelGenerationOptions to load. - while ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->hasLoadedData() ) + while ( app.getLevelGenerationOptions() != nullptr && !app.getLevelGenerationOptions()->hasLoadedData() ) Sleep(1); - if ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->ready() ) + if ( app.getLevelGenerationOptions() != nullptr && !app.getLevelGenerationOptions()->ready() ) { // TODO: Stop loading, add error message. } @@ -704,7 +710,7 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW wstring levelTypeString; bool gameRuleUseFlatWorld = false; - if(app.getLevelGenerationOptions() != NULL) + if(app.getLevelGenerationOptions() != nullptr) { gameRuleUseFlatWorld = app.getLevelGenerationOptions()->getuseFlatWorld(); } @@ -718,7 +724,7 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW } LevelType *pLevelType = LevelType::getLevelType(levelTypeString); - if (pLevelType == NULL) + if (pLevelType == nullptr) { pLevelType = LevelType::lvl_normal; } @@ -773,7 +779,7 @@ int MinecraftServer::runPostUpdate(void* lpParam) { ShutdownManager::HasStarted(ShutdownManager::ePostProcessThread); - MinecraftServer *server = (MinecraftServer *)lpParam; + MinecraftServer *server = static_cast(lpParam); Entity::useSmallIds(); // This thread can end up spawning entities as resources IntCache::CreateNewThreadStorage(); AABB::CreateNewThreadStorage(); @@ -868,7 +874,7 @@ void MinecraftServer::postProcessTerminate(ProgressRenderer *mcprogress) } } while ( status == WAIT_TIMEOUT ); delete m_postUpdateThread; - m_postUpdateThread = NULL; + m_postUpdateThread = nullptr; DeleteCriticalSection(&m_postProcessCS); } @@ -894,7 +900,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring // 4J - temp - load existing level shared_ptr storage = nullptr; bool levelChunksNeedConverted = false; - if( initData->saveData != NULL ) + if( initData->saveData != nullptr ) { // We are loading a file from disk with the data passed in @@ -910,7 +916,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring levelChunksNeedConverted = true; pSave->ConvertToLocalPlatform(); // check if we need to convert this file from PS3->PS4 - storage = shared_ptr(new McRegionLevelStorage(pSave, File(L"."), name, true)); + storage = std::make_shared(pSave, File(L"."), name, true); } else { @@ -918,13 +924,13 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring #ifdef SPLIT_SAVES bool bLevelGenBaseSave = false; LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if( levelGen != NULL && levelGen->requiresBaseSave()) + if( levelGen != nullptr && levelGen->requiresBaseSave()) { DWORD fileSize = 0; LPVOID pvSaveData = levelGen->getBaseSaveData(fileSize); if(pvSaveData && fileSize != 0) bLevelGenBaseSave = true; } - ConsoleSaveFileSplit *newFormatSave = NULL; + ConsoleSaveFileSplit *newFormatSave = nullptr; if(bLevelGenBaseSave) { ConsoleSaveFileOriginal oldFormatSave( L"" ); @@ -937,7 +943,11 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring storage = shared_ptr(new McRegionLevelStorage(newFormatSave, File(L"."), name, true)); #else - storage = shared_ptr(new McRegionLevelStorage(new ConsoleSaveFileOriginal( L"" ), File(L"."), name, true)); + ConsoleSaveFileOriginal* pSave = new ConsoleSaveFileOriginal(L""); + + pSave->ConvertToLocalPlatform(); + storage = std::make_shared(pSave, File(L"."), name, true); + #endif } @@ -958,11 +968,11 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring if (i == 0) { levels[i] = new ServerLevel(this, storage, name, dimension, levelSettings); - if(app.getLevelGenerationOptions() != NULL) + if(app.getLevelGenerationOptions() != nullptr) { LevelGenerationOptions *mapOptions = app.getLevelGenerationOptions(); Pos *spawnPos = mapOptions->getSpawnPos(); - if( spawnPos != NULL ) + if( spawnPos != nullptr ) { levels[i]->setSpawnPos( spawnPos ); } @@ -987,7 +997,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring #endif levels[i]->getLevelData()->setGameType(gameType); - if(app.getLevelGenerationOptions() != NULL) + if(app.getLevelGenerationOptions() != nullptr) { LevelGenerationOptions *mapOptions = app.getLevelGenerationOptions(); levels[i]->getLevelData()->setHasBeenInCreative(mapOptions->getLevelHasBeenInCreative() ); @@ -1044,7 +1054,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring ba_gameRules.length = fe->getFileSize(); ba_gameRules.data = new BYTE[ ba_gameRules.length ]; - csf->setFilePointer(fe,0,NULL,FILE_BEGIN); + csf->setFilePointer(fe,0,nullptr,FILE_BEGIN); csf->readFile(fe, ba_gameRules.data, ba_gameRules.length, &numberOfBytesRead); assert(numberOfBytesRead == ba_gameRules.length); @@ -1355,7 +1365,7 @@ void MinecraftServer::saveAllChunks() // with the data from the nethers leveldata. // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. ServerLevel *level = levels[levels.length - 1 - i]; - if( level ) // 4J - added check as level can be NULL if we end up in stopServer really early on due to network failure + if( level ) // 4J - added check as level can be nullptr if we end up in stopServer really early on due to network failure { level->save(true, Minecraft::GetInstance()->progressRenderer); @@ -1381,14 +1391,14 @@ void MinecraftServer::saveGameRules() #endif { byteArray ba; - ba.data = NULL; + ba.data = nullptr; app.m_gameRules.saveGameRules( &ba.data, &ba.length ); - if (ba.data != NULL) + if (ba.data != nullptr) { ConsoleSaveFile *csf = getLevel(0)->getLevelStorage()->getSaveFile(); FileEntry *fe = csf->createFile(ConsoleSavePath(GAME_RULE_SAVENAME)); - csf->setFilePointer(fe, 0, NULL, FILE_BEGIN); + csf->setFilePointer(fe, 0, nullptr, FILE_BEGIN); DWORD length; csf->writeFile(fe, ba.data, ba.length, &length ); @@ -1407,14 +1417,14 @@ void MinecraftServer::Suspend() LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; float fElapsedTime = 0.0f; QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + float fSecsPerTick = 1.0f / static_cast(qwTicksPerSec.QuadPart); // Save the start time QueryPerformanceCounter( &qwTime ); if(m_bLoaded && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) { - if (players != NULL) + if (players != nullptr) { - players->saveAll(NULL); + players->saveAll(nullptr); } for (unsigned int j = 0; j < levels.length; j++) { @@ -1428,13 +1438,13 @@ void MinecraftServer::Suspend() if( !s_bServerHalted ) { saveGameRules(); - levels[0]->saveToDisc(NULL, true); + levels[0]->saveToDisc(nullptr, true); } } QueryPerformanceCounter( &qwNewTime ); qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + fElapsedTime = fSecsPerTick * static_cast(qwDeltaTime.QuadPart); // 4J-JEV: Flush stats and call PlayerSessionExit. for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) @@ -1487,7 +1497,7 @@ void MinecraftServer::stopServer(bool didInit) // 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) + if (players != nullptr) { players->saveAll(Minecraft::GetInstance()->progressRenderer, true); } @@ -1497,7 +1507,7 @@ void MinecraftServer::stopServer(bool didInit) //for (unsigned int i = levels.length - 1; i >= 0; i--) //{ // ServerLevel *level = levels[i]; - // if (level != NULL) + // if (level != nullptr) // { saveAllChunks(); // } @@ -1505,7 +1515,7 @@ void MinecraftServer::stopServer(bool didInit) saveGameRules(); app.m_gameRules.unloadCurrentGameRules(); - if( levels[0] != NULL ) // This can be null if stopServer happens very quickly due to network error + if( levels[0] != nullptr ) // This can be null if stopServer happens very quickly due to network error { levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, false); } @@ -1528,10 +1538,10 @@ void MinecraftServer::stopServer(bool didInit) unsigned int iServerLevelC=levels.length; for (unsigned int i = 0; i < iServerLevelC; i++) { - if(levels[i]!=NULL) + if(levels[i]!=nullptr) { delete levels[i]; - levels[i] = NULL; + levels[i] = nullptr; } } @@ -1541,11 +1551,11 @@ void MinecraftServer::stopServer(bool didInit) #endif delete connection; - connection = NULL; + connection = nullptr; delete players; - players = NULL; + players = nullptr; delete settings; - settings = NULL; + settings = nullptr; g_NetworkManager.ServerStopped(); } @@ -1657,7 +1667,9 @@ Level *MinecraftServer::getCommandSenderWorld() int MinecraftServer::getSpawnProtectionRadius() { - return 16; + // Client-host mode must never apply dedicated-server spawn protection settings. + if (!ShouldUseDedicatedServerProperties()) return 0; + return m_spawnProtectionRadius; } bool MinecraftServer::isUnderSpawnProtection(Level *level, int x, int y, int z, shared_ptr player) @@ -1703,330 +1715,345 @@ void MinecraftServer::setPlayerIdleTimeout(int playerIdleTimeout) extern int c0a, c0b, c1a, c1b, c1c, c2a, c2b; void MinecraftServer::run(int64_t seed, void *lpParameter) { - NetworkGameInitData *initData = NULL; - DWORD initSettings = 0; - bool findSeed = false; - if(lpParameter != NULL) - { - initData = (NetworkGameInitData *)lpParameter; - initSettings = app.GetGameHostOption(eGameHostOption_All); - findSeed = initData->findSeed; - m_texturePackId = initData->texturePackId; - } - // try { // 4J - removed try/catch/finally - bool didInit = false; + NetworkGameInitData *initData = nullptr; + DWORD initSettings = 0; + bool findSeed = false; + if(lpParameter != nullptr) + { + initData = static_cast(lpParameter); + initSettings = app.GetGameHostOption(eGameHostOption_All); + findSeed = initData->findSeed; + m_texturePackId = initData->texturePackId; + } + // try { // 4J - removed try/catch/finally + bool didInit = false; if (initServer(seed, initData, initSettings,findSeed)) - { - didInit = true; - ServerLevel *levelNormalDimension = levels[0]; - // 4J-PB - Set the Stronghold position in the leveldata if there isn't one in there - Minecraft *pMinecraft = Minecraft::GetInstance(); + { + didInit = true; + ServerLevel *levelNormalDimension = levels[0]; + // 4J-PB - Set the Stronghold position in the leveldata if there isn't one in there + Minecraft *pMinecraft = Minecraft::GetInstance(); LevelData *pLevelData=levelNormalDimension->getLevelData(); if(pLevelData && pLevelData->getHasStronghold()==false) - { + { int x,z; if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) - { - pLevelData->setXStronghold(x); - pLevelData->setZStronghold(z); - pLevelData->setHasStronghold(); - } - } + { + pLevelData->setXStronghold(x); + pLevelData->setZStronghold(z); + pLevelData->setHasStronghold(); + } + } - int64_t lastTime = getCurrentTimeMillis(); - int64_t unprocessedTime = 0; - while (running && !s_bServerHalted) - { - int64_t now = getCurrentTimeMillis(); + int64_t lastTime = getCurrentTimeMillis(); + int64_t unprocessedTime = 0; + while (running && !s_bServerHalted) + { + int64_t now = getCurrentTimeMillis(); - // 4J Stu - When we pause the server, we don't want to count that as time passed - // 4J Stu - TU-1 hotifx - Remove this line. We want to make sure that we tick connections at the proper rate when paused + // 4J Stu - When we pause the server, we don't want to count that as time passed + // 4J Stu - TU-1 hotifx - Remove this line. We want to make sure that we tick connections at the proper rate when paused //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost //if(m_isServerPaused) lastTime = now; - int64_t passedTime = now - lastTime; - if (passedTime > MS_PER_TICK * 40) - { - // logger.warning("Can't keep up! Did the system time change, or is the server overloaded?"); - passedTime = MS_PER_TICK * 40; - } - if (passedTime < 0) - { - // logger.warning("Time ran backwards! Did the system time change?"); - passedTime = 0; - } - unprocessedTime += passedTime; - lastTime = now; + int64_t passedTime = now - lastTime; + if (passedTime > MS_PER_TICK * 40) + { + // logger.warning("Can't keep up! Did the system time change, or is the server overloaded?"); + passedTime = MS_PER_TICK * 40; + } + if (passedTime < 0) + { + // logger.warning("Time ran backwards! Did the system time change?"); + passedTime = 0; + } + unprocessedTime += passedTime; + lastTime = now; - // 4J Added ability to pause the server + // 4J Added ability to pause the server if( !m_isServerPaused ) - { - bool didTick = false; - if (levels[0]->allPlayersAreSleeping()) - { - tick(); - unprocessedTime = 0; - } - else - { - // int tickcount = 0; - // int64_t beforeall = System::currentTimeMillis(); - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; - chunkPacketManagement_PreTick(); -// int64_t before = System::currentTimeMillis(); - tick(); -// int64_t after = System::currentTimeMillis(); -// PIXReportCounter(L"Server time",(float)(after-before)); + { + bool didTick = false; + if (levels[0]->allPlayersAreSleeping()) + { + tick(); + unprocessedTime = 0; + } + else + { + // int tickcount = 0; + // int64_t beforeall = System::currentTimeMillis(); + while (unprocessedTime > MS_PER_TICK) + { + unprocessedTime -= MS_PER_TICK; + chunkPacketManagement_PreTick(); + // int64_t before = System::currentTimeMillis(); + tick(); + // int64_t after = System::currentTimeMillis(); + // PIXReportCounter(L"Server time",(float)(after-before)); - chunkPacketManagement_PostTick(); - } -// int64_t afterall = System::currentTimeMillis(); -// PIXReportCounter(L"Server time all",(float)(afterall-beforeall)); -// PIXReportCounter(L"Server ticks",(float)tickcount); - } - } - else - { - // 4J Stu - TU1-hotfix + chunkPacketManagement_PostTick(); + } + // int64_t afterall = System::currentTimeMillis(); + // PIXReportCounter(L"Server time all",(float)(afterall-beforeall)); + // PIXReportCounter(L"Server ticks",(float)tickcount); + } + } + else + { + // 4J Stu - TU1-hotfix //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - // The connections should tick at the same frequency even when paused - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; - // Keep ticking the connections to stop them timing out - connection->tick(); - } - } + // The connections should tick at the same frequency even when paused + while (unprocessedTime > MS_PER_TICK) + { + unprocessedTime -= MS_PER_TICK; + // Keep ticking the connections to stop them timing out + connection->tick(); + } + } if(MinecraftServer::setTimeAtEndOfTick) - { - MinecraftServer::setTimeAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { - // if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether - { - ServerLevel *level = levels[i]; + { + MinecraftServer::setTimeAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) + { + // if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether + { + ServerLevel *level = levels[i]; level->setGameTime( MinecraftServer::setTime ); - } - } - } + } + } + } if(MinecraftServer::setTimeOfDayAtEndOfTick) - { - MinecraftServer::setTimeOfDayAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { - if (i == 0 || GetDedicatedServerBool(settings, L"allow-nether", true)) - { - ServerLevel *level = levels[i]; + { + MinecraftServer::setTimeOfDayAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) + { + if (i == 0 || GetDedicatedServerBool(settings, L"allow-nether", true)) + { + ServerLevel *level = levels[i]; level->setDayTime( MinecraftServer::setTimeOfDay ); - } - } - } + } + } + } - // Process delayed actions - eXuiServerAction eAction; - LPVOID param; + // Process delayed actions + eXuiServerAction eAction; + LPVOID param; for(int i=0;isaveAll(NULL); - } - - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - PIXBeginNamedEvent(0, "Saving level %d",levels.length - 1 - j); - level->save(false, NULL, true); - PIXEndNamedEvent(); - } - if( !s_bServerHalted ) - { - PIXBeginNamedEvent(0,"Saving game rules"); - saveGameRules(); - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Save to disc"); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, true); - PIXEndNamedEvent(); - } - PIXEndNamedEvent(); - - QueryPerformanceCounter( &qwNewTime ); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Autosave: Elapsed time %f\n", fElapsedTime); - } - break; + // Save the start time + QueryPerformanceCounter(&qwTime); #endif - case eXuiServerAction_SaveGame: - app.EnterSaveNotificationSection(); - if (players != NULL) - { - players->saveAll(Minecraft::GetInstance()->progressRenderer); - } - players->broadcastAll( shared_ptr( new UpdateProgressPacket(20) ) ); + if (players != nullptr) + { + players->saveAll(nullptr); + } - for (unsigned int j = 0; j < levels.length; j++) - { + for (unsigned int j = 0; j < levels.length; j++) + { + if( s_bServerHalted ) break; + // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat + // with the data from the nethers leveldata. + // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. + ServerLevel *level = levels[levels.length - 1 - j]; +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXBeginNamedEvent(0, "Saving level %d", levels.length - 1 - j); +#endif + level->save(false, nullptr, true); +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXEndNamedEvent(); +#endif + } + if (!s_bServerHalted) + { +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXBeginNamedEvent(0, "Saving game rules"); +#endif + saveGameRules(); +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Save to disc"); +#endif + levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, true); +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXEndNamedEvent(); +#endif + } + +#if defined(_XBOX_ONE) || defined(__ORBIS__) + PIXEndNamedEvent(); + + QueryPerformanceCounter(&qwNewTime); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + app.DebugPrintf("Autosave: Elapsed time %f\n", fElapsedTime); +#endif + } + break; +#endif + case eXuiServerAction_SaveGame: + app.EnterSaveNotificationSection(); + if (players != nullptr) + { + players->saveAll(Minecraft::GetInstance()->progressRenderer); + } + + players->broadcastAll(std::make_shared(20)); + + for (unsigned int j = 0; j < levels.length; j++) + { if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; + // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat + // with the data from the nethers leveldata. + // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. + ServerLevel *level = levels[levels.length - 1 - j]; level->save(true, Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - players->broadcastAll( shared_ptr( new UpdateProgressPacket(33 + (j*33) ) ) ); - } + players->broadcastAll(std::make_shared(33 + (j * 33))); + } if( !s_bServerHalted ) - { - saveGameRules(); + { + saveGameRules(); levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - } - app.LeaveSaveNotificationSection(); - break; - case eXuiServerAction_DropItem: - // Find the player, and drop the id at their feet - { - shared_ptr player = players->players.at(0); + } + app.LeaveSaveNotificationSection(); + break; + case eXuiServerAction_DropItem: + // Find the player, and drop the id at their feet + { + shared_ptr player = players->players.at(0); size_t id = (size_t) param; - player->drop( shared_ptr( new ItemInstance(id, 1, 0 ) ) ); - } - break; - case eXuiServerAction_SpawnMob: - { - shared_ptr player = players->players.at(0); - eINSTANCEOF factory = (eINSTANCEOF)((size_t)param); + player->drop(std::make_shared(id, 1, 0)); + } + break; + case eXuiServerAction_SpawnMob: + { + shared_ptr player = players->players.at(0); + eINSTANCEOF factory = static_cast((size_t)param); shared_ptr mob = dynamic_pointer_cast(EntityIO::newByEnumType(factory,player->level )); mob->moveTo(player->x+1, player->y, player->z+1, player->level->random->nextFloat() * 360, 0); mob->setDespawnProtected(); // 4J added, default to being protected against despawning (has to be done after initial position is set) - player->level->addEntity(mob); - } - break; - case eXuiServerAction_PauseServer: + player->level->addEntity(mob); + } + break; + 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); - } - break; - case eXuiServerAction_ServerSettingChanged_Gamertags: - players->broadcastAll( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_OPTIONS, app.GetGameHostOption(eGameHostOption_Gamertags)) ) ); - break; - case eXuiServerAction_ServerSettingChanged_BedrockFog: - players->broadcastAll( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, app.GetGameHostOption(eGameHostOption_All)) ) ); - break; + { + 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); + } + break; + case eXuiServerAction_ServerSettingChanged_Gamertags: + players->broadcastAll(std::make_shared(ServerSettingsChangedPacket::HOST_OPTIONS, app.GetGameHostOption(eGameHostOption_Gamertags))); + break; + case eXuiServerAction_ServerSettingChanged_BedrockFog: + players->broadcastAll(std::make_shared(ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, app.GetGameHostOption(eGameHostOption_All))); + break; - case eXuiServerAction_ServerSettingChanged_Difficulty: - players->broadcastAll( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_DIFFICULTY, Minecraft::GetInstance()->options->difficulty) ) ); - break; - case eXuiServerAction_ExportSchematic: + case eXuiServerAction_ServerSettingChanged_Difficulty: + players->broadcastAll(std::make_shared(ServerSettingsChangedPacket::HOST_DIFFICULTY, Minecraft::GetInstance()->options->difficulty)); + break; + case eXuiServerAction_ExportSchematic: #ifndef _CONTENT_PACKAGE - app.EnterSaveNotificationSection(); + app.EnterSaveNotificationSection(); //players->broadcastAll( shared_ptr( new UpdateProgressPacket(20) ) ); if( !s_bServerHalted ) - { - ConsoleSchematicFile::XboxSchematicInitParam *initData = (ConsoleSchematicFile::XboxSchematicInitParam *)param; + { + ConsoleSchematicFile::XboxSchematicInitParam *initData = static_cast(param); #ifdef _XBOX - File targetFileDir(File::pathRoot + File::pathSeparator + L"Schematics"); + File targetFileDir(File::pathRoot + File::pathSeparator + L"Schematics"); #else - File targetFileDir(L"Schematics"); + File targetFileDir(L"Schematics"); #endif if(!targetFileDir.exists()) targetFileDir.mkdir(); - wchar_t filename[128]; + wchar_t filename[128]; swprintf(filename,128,L"%ls%dx%dx%d.sch",initData->name,(initData->endX - initData->startX + 1), (initData->endY - initData->startY + 1), (initData->endZ - initData->startZ + 1)); File dataFile = File( targetFileDir, wstring(filename) ); if(dataFile.exists()) dataFile._delete(); - FileOutputStream fos = FileOutputStream(dataFile); - 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(); + FileOutputStream fos = FileOutputStream(dataFile); + 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(); - delete initData; - } - app.LeaveSaveNotificationSection(); + delete initData; + } + app.LeaveSaveNotificationSection(); #endif - break; - case eXuiServerAction_SetCameraLocation: + break; + case eXuiServerAction_SetCameraLocation: #ifndef _CONTENT_PACKAGE - { - DebugSetCameraPosition *pos = (DebugSetCameraPosition *)param; + { + DebugSetCameraPosition *pos = static_cast(param); 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_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, pos->m_elev ); - shared_ptr player = players->players.at(pos->player); + shared_ptr player = players->players.at(pos->player); player->debug_setPosition( pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, pos->m_elev ); - // Doesn't work + // Doesn't work //player->setYHeadRot(pos->m_yRot); //player->absMoveTo(pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, pos->m_elev); - } + } #endif - break; - } + break; + } app.SetXuiServerAction(i,eXuiServerAction_Idle); - } + } - Sleep(1); - } - } + Sleep(1); + } + } //else - //{ + //{ // while (running) - // { + // { // handleConsoleInputs(); - // Sleep(10); + // Sleep(10); // } //} #if 0 @@ -2053,21 +2080,21 @@ void MinecraftServer::run(int64_t seed, void *lpParameter) } #endif - // 4J Stu - Stop the server when the loops complete, as the finally would do - stopServer(didInit); - stopped = true; + // 4J Stu - Stop the server when the loops complete, as the finally would do + stopServer(didInit); + stopped = true; } void MinecraftServer::broadcastStartSavingPacket() { - players->broadcastAll( shared_ptr( new GameEventPacket(GameEventPacket::START_SAVING, 0) ) );; + players->broadcastAll(std::make_shared(GameEventPacket::START_SAVING, 0));; } void MinecraftServer::broadcastStopSavingPacket() { if( !s_bServerHalted ) { - players->broadcastAll( shared_ptr( new GameEventPacket(GameEventPacket::STOP_SAVING, 0) ) );; + players->broadcastAll(std::make_shared(GameEventPacket::STOP_SAVING, 0));; } } @@ -2122,13 +2149,13 @@ void MinecraftServer::tick() if (tickCount % 20 == 0) { - players->broadcastAll( shared_ptr( new SetTimePacket(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT) ) ), level->dimension->id); + players->broadcastAll(std::make_shared(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)), level->dimension->id); } // #ifndef __PS3__ static int64_t stc = 0; int64_t st0 = System::currentTimeMillis(); PIXBeginNamedEvent(0,"Level tick %d",i); - ((Level *)level)->tick(); + static_cast(level)->tick(); int64_t st1 = System::currentTimeMillis(); PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Update lights %d",i); @@ -2169,16 +2196,20 @@ void MinecraftServer::tick() } Entity::tickExtraWandering(); // 4J added - PIXBeginNamedEvent(0,"Connection tick"); - connection->tick(); - PIXEndNamedEvent(); + // Process player disconnect/kick queue BEFORE ticking connections. + // PendingConnection::handleLogin rejects duplicate XUIDs, so the old + // player must be removed from PlayerList before a reconnecting client's + // LoginPacket is processed. PIXBeginNamedEvent(0,"Players tick"); players->tick(); PIXEndNamedEvent(); + PIXBeginNamedEvent(0,"Connection tick"); + connection->tick(); + PIXEndNamedEvent(); // 4J - removed #if 0 - for (int i = 0; i < tickables.size(); i++) { + for (size_t i = 0; i < tickables.size(); i++) { tickables.get(i)-tick(); } #endif @@ -2220,14 +2251,14 @@ void MinecraftServer::main(int64_t seed, void *lpParameter) server = new MinecraftServer(); server->run(seed, lpParameter); delete server; - server = NULL; + server = nullptr; ShutdownManager::HasFinished(ShutdownManager::eServerThread ); } void MinecraftServer::HaltServer(bool bPrimaryPlayerSignedOut) { s_bServerHalted = true; - if( server != NULL ) + if( server != nullptr ) { m_bPrimaryPlayerSignedOut=bPrimaryPlayerSignedOut; server->halt(); @@ -2273,9 +2304,9 @@ void MinecraftServer::setLevel(int dimension, ServerLevel *level) bool MinecraftServer::chunkPacketManagement_CanSendTo(INetworkPlayer *player) { if( s_hasSentEnoughPackets ) return false; - if( player == NULL ) return false; + if( player == nullptr ) return false; - for( int i = 0; i < s_sentTo.size(); i++ ) + for( size_t i = 0; i < s_sentTo.size(); i++ ) { if( s_sentTo[i]->IsSameSystem(player) ) { @@ -2357,8 +2388,11 @@ void MinecraftServer::chunkPacketManagement_PostTick() // not GetSessionIndex() (smallId), so reused smallIds after many connect/disconnects still get chunk sends. bool MinecraftServer::chunkPacketManagement_CanSendTo(INetworkPlayer *player) { - if( player == NULL ) return false; + if( player == nullptr ) return false; +#ifdef MINECRAFT_SERVER_BUILD + return true; +#else int time = GetTickCount(); DWORD currentPlayerCount = g_NetworkManager.GetPlayerCount(); if( currentPlayerCount == 0 ) return false; @@ -2370,6 +2404,7 @@ bool MinecraftServer::chunkPacketManagement_CanSendTo(INetworkPlayer *player) } return false; +#endif } void MinecraftServer::chunkPacketManagement_DidSendTo(INetworkPlayer *player) @@ -2403,7 +2438,7 @@ void MinecraftServer::cycleSlowQueueIndex() if( !g_NetworkManager.IsInSession() ) return; int startingIndex = s_slowQueuePlayerIndex; - INetworkPlayer *currentPlayer = NULL; + INetworkPlayer *currentPlayer = nullptr; DWORD currentPlayerCount = 0; do { @@ -2425,7 +2460,7 @@ void MinecraftServer::cycleSlowQueueIndex() } while ( g_NetworkManager.IsInSession() && currentPlayerCount > 0 && s_slowQueuePlayerIndex != startingIndex && - currentPlayer != NULL && + currentPlayer != nullptr && currentPlayer->IsLocal() ); // app.DebugPrintf("Cycled slow queue index to %d\n", s_slowQueuePlayerIndex); diff --git a/Minecraft.Client/MinecraftServer.h b/Minecraft.Client/MinecraftServer.h index 289097912..1ed5db9d7 100644 --- a/Minecraft.Client/MinecraftServer.h +++ b/Minecraft.Client/MinecraftServer.h @@ -44,6 +44,7 @@ typedef struct _NetworkGameInitData LevelGenerationOptions *levelGen; DWORD texturePackId; bool findSeed; + bool dedicatedNoLocalHostPlayer; unsigned int xzSize; unsigned char hellScale; ESavePlatform savePlatform; @@ -52,11 +53,12 @@ typedef struct _NetworkGameInitData _NetworkGameInitData() { seed = 0; - saveData = NULL; + saveData = nullptr; settings = 0; - levelGen = NULL; + levelGen = nullptr; texturePackId = 0; findSeed = false; + dedicatedNoLocalHostPlayer = false; xzSize = LEVEL_LEGACY_WIDTH; hellScale = HELL_LEVEL_LEGACY_SCALE; savePlatform = SAVE_FILE_PLATFORM_LOCAL; @@ -119,6 +121,7 @@ public: int maxBuildHeight; int playerIdleTimeout; bool forceGameType; + int m_spawnProtectionRadius; private: // 4J Added @@ -236,8 +239,7 @@ private: public: void addPostProcessRequest(ChunkSource *chunkSource, int x, int z); -public: - static PlayerList *getPlayerList() { if( server != NULL ) return server->players; else return NULL; } + static PlayerList *getPlayerList() { if( server != nullptr) return server->players; else return nullptr; } static void SetTimeOfDay(int64_t time) { setTimeOfDayAtEndOfTick = true; setTimeOfDay = time; } static void SetTime(int64_t time) { setTimeAtEndOfTick = true; setTime = time; } diff --git a/Minecraft.Client/Minimap.cpp b/Minecraft.Client/Minimap.cpp index 65c6d5f2c..4f6ccd6b6 100644 --- a/Minecraft.Client/Minimap.cpp +++ b/Minecraft.Client/Minimap.cpp @@ -133,10 +133,10 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptrvertexUV((float)(x + 0 + vo), (float)( y + h - vo), (float)( Offset), (float)( 0), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + h - vo), (float)( Offset), (float)( 1), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + 0 + vo), (float)( Offset), (float)( 1), (float)( 0)); - t->vertexUV((float)(x + 0 + vo), (float)( y + 0 + vo), (float)( Offset), (float)( 0), (float)( 0)); + t->vertexUV((float)(x + 0 + vo), (float)( y + h - vo), (float)( Offset), static_cast(0), static_cast(1)); + t->vertexUV((float)(x + w - vo), (float)( y + h - vo), (float)( Offset), static_cast(1), static_cast(1)); + t->vertexUV((float)(x + w - vo), (float)( y + 0 + vo), (float)( Offset), static_cast(1), static_cast(0)); + t->vertexUV((float)(x + 0 + vo), (float)( y + 0 + vo), (float)( Offset), static_cast(0), static_cast(0)); t->end(); glEnable(GL_ALPHA_TEST); glDisable(GL_BLEND); @@ -165,9 +165,9 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptrentityId != entityId) continue; glPushMatrix(); @@ -182,10 +182,10 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptrbegin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV(static_cast(-1), static_cast(+1), static_cast(0), (float)( u0), (float)( v0)); + t->vertexUV(static_cast(+1), static_cast(+1), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV(static_cast(+1), static_cast(-1), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV(static_cast(-1), static_cast(-1), static_cast(0), (float)( u0), (float)( v1)); t->end(); glPopMatrix(); fIconZ-=0.01f; @@ -201,9 +201,9 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptrimg; imgIndex -= 16; - // 4J Stu - For item frame renders, the player is NULL. We do not want to show player icons on the frames. - if(player == NULL && (imgIndex != 12)) continue; - else if (player != NULL && imgIndex == 12) continue; + // 4J Stu - For item frame renders, the player is nullptr. We do not want to show player icons on the frames. + if(player == nullptr && (imgIndex != 12)) continue; + else if (player != nullptr && imgIndex == 12) continue; else if( imgIndex == 12 && dec->entityId != entityId) continue; glPushMatrix(); @@ -218,10 +218,10 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptrbegin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV(static_cast(-1), static_cast(+1), static_cast(0), (float)( u0), (float)( v0)); + t->vertexUV(static_cast(+1), static_cast(+1), static_cast(0), (float)( u1), (float)( v0)); + t->vertexUV(static_cast(+1), static_cast(-1), static_cast(0), (float)( u1), (float)( v1)); + t->vertexUV(static_cast(-1), static_cast(-1), static_cast(0), (float)( u0), (float)( v1)); t->end(); glPopMatrix(); fIconZ-=0.01f; @@ -239,7 +239,7 @@ void Minimap::render(shared_ptr player, Textures *textures, shared_ptr _mob, double x, double y, double z, float rot, float a) { + if (_mob == nullptr) + { + return; + } + shared_ptr mob = dynamic_pointer_cast(_mob); + if (mob == nullptr) + { + return; + } + LivingEntityRenderer::render(mob, x, y, z, rot, a); renderLeash(mob, x, y, z, rot, a); } @@ -30,7 +40,7 @@ void MobRenderer::renderLeash(shared_ptr entity, double x, double y, double { shared_ptr roper = entity->getLeashHolder(); // roper = entityRenderDispatcher.cameraEntity; - if (roper != NULL) + if (roper != nullptr) { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); @@ -61,9 +71,9 @@ void MobRenderer::renderLeash(shared_ptr entity, double x, double y, double x += rotOffCos; z += rotOffSin; - double dx = (float) (endX - startX); - double dy = (float) (endY - startY); - double dz = (float) (endZ - startZ); + double dx = static_cast(endX - startX); + double dy = static_cast(endY - startY); + double dz = static_cast(endZ - startZ); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); @@ -92,9 +102,9 @@ void MobRenderer::renderLeash(shared_ptr entity, double x, double y, double { tessellator->color(rDarkCol, gDarkCol, bDarkCol, 1.0F); } - float aa = (float) k / (float) steps; - tessellator->vertex(x + (dx * aa) + 0, y + (dy * ((aa * aa) + aa) * 0.5) + ((((float) steps - (float) k) / (steps * 0.75F)) + 0.125F), z + (dz * aa)); - tessellator->vertex(x + (dx * aa) + width, y + (dy * ((aa * aa) + aa) * 0.5) + ((((float) steps - (float) k) / (steps * 0.75F)) + 0.125F) + width, z + (dz * aa)); + float aa = static_cast(k) / static_cast(steps); + tessellator->vertex(x + (dx * aa) + 0, y + (dy * ((aa * aa) + aa) * 0.5) + (((static_cast(steps) - static_cast(k)) / (steps * 0.75F)) + 0.125F), z + (dz * aa)); + tessellator->vertex(x + (dx * aa) + width, y + (dy * ((aa * aa) + aa) * 0.5) + (((static_cast(steps) - static_cast(k)) / (steps * 0.75F)) + 0.125F) + width, z + (dz * aa)); } tessellator->end(); @@ -109,9 +119,9 @@ void MobRenderer::renderLeash(shared_ptr entity, double x, double y, double { tessellator->color(rDarkCol, gDarkCol, bDarkCol, 1.0F); } - float aa = (float) k / (float) steps; - tessellator->vertex(x + (dx * aa) + 0, y + (dy * ((aa * aa) + aa) * 0.5) + ((((float) steps - (float) k) / (steps * 0.75F)) + 0.125F) + width, z + (dz * aa)); - tessellator->vertex(x + (dx * aa) + width, y + (dy * ((aa * aa) + aa) * 0.5) + ((((float) steps - (float) k) / (steps * 0.75F)) + 0.125F), z + (dz * aa) + width); + float aa = static_cast(k) / static_cast(steps); + tessellator->vertex(x + (dx * aa) + 0, y + (dy * ((aa * aa) + aa) * 0.5) + (((static_cast(steps) - static_cast(k)) / (steps * 0.75F)) + 0.125F) + width, z + (dz * aa)); + tessellator->vertex(x + (dx * aa) + width, y + (dy * ((aa * aa) + aa) * 0.5) + (((static_cast(steps) - static_cast(k)) / (steps * 0.75F)) + 0.125F), z + (dz * aa) + width); } tessellator->end(); diff --git a/Minecraft.Client/MobSkinMemTextureProcessor.cpp b/Minecraft.Client/MobSkinMemTextureProcessor.cpp index a6fdf5270..c841c3f5a 100644 --- a/Minecraft.Client/MobSkinMemTextureProcessor.cpp +++ b/Minecraft.Client/MobSkinMemTextureProcessor.cpp @@ -3,14 +3,14 @@ BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) { - if (in == NULL) return NULL; + if (in == nullptr) return nullptr; width = 64; height = 32; BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); Graphics *g = out->getGraphics(); - g->drawImage(in, 0, 0, NULL); + g->drawImage(in, 0, 0, nullptr); g->dispose(); pixels = out->getData(); diff --git a/Minecraft.Client/MobSkinTextureProcessor.cpp b/Minecraft.Client/MobSkinTextureProcessor.cpp index dffb467a8..37d2ab46c 100644 --- a/Minecraft.Client/MobSkinTextureProcessor.cpp +++ b/Minecraft.Client/MobSkinTextureProcessor.cpp @@ -3,14 +3,14 @@ BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) { - if (in == NULL) return NULL; + if (in == nullptr) return nullptr; width = 64; height = 32; BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); Graphics *g = out->getGraphics(); - g->drawImage(in, 0, 0, NULL); + g->drawImage(in, 0, 0, nullptr); g->dispose(); pixels = out->getData(); diff --git a/Minecraft.Client/MobSpawnerRenderer.cpp b/Minecraft.Client/MobSpawnerRenderer.cpp index 02aac27fd..1a083fabd 100644 --- a/Minecraft.Client/MobSpawnerRenderer.cpp +++ b/Minecraft.Client/MobSpawnerRenderer.cpp @@ -16,15 +16,15 @@ void MobSpawnerRenderer::render(shared_ptr _spawner, double x, doubl void MobSpawnerRenderer::render(BaseMobSpawner *spawner, double x, double y, double z, float a) { glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y, (float) z + 0.5f); + glTranslatef(static_cast(x) + 0.5f, static_cast(y), static_cast(z) + 0.5f); shared_ptr e = spawner->getDisplayEntity(); - if (e != NULL) + if (e != nullptr) { e->setLevel(spawner->getLevel()); float s = 7 / 16.0f; glTranslatef(0, 0.4f, 0); - glRotatef((float) (spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, 0, 1, 0); + glRotatef(static_cast(spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, 0, 1, 0); glRotatef(-30, 1, 0, 0); glTranslatef(0, -0.4f, 0); glScalef(s, s, s); diff --git a/Minecraft.Client/Model.h b/Minecraft.Client/Model.h index 5a4b6f2e8..6a797a258 100644 --- a/Minecraft.Client/Model.h +++ b/Minecraft.Client/Model.h @@ -23,8 +23,8 @@ public: virtual void render(shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) {} virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, shared_ptr entity, unsigned int uiBitmaskOverrideAnim=0) {} virtual void prepareMobModel(shared_ptr mob, float time, float r, float a) {} - virtual ModelPart *getRandomModelPart(Random random) {return cubes.at(random.nextInt((int)cubes.size()));} - virtual ModelPart * AddOrRetrievePart(SKIN_BOX *pBox) { return NULL;} + virtual ModelPart *getRandomModelPart(Random random) {return cubes.at(random.nextInt(static_cast(cubes.size())));} + virtual ModelPart * AddOrRetrievePart(SKIN_BOX *pBox) { return nullptr;} void setMapTex(wstring id, int x, int y); TexOffs *getMapTex(wstring id); diff --git a/Minecraft.Client/ModelHorse.cpp b/Minecraft.Client/ModelHorse.cpp index 7a13d0adc..81ff7ea61 100644 --- a/Minecraft.Client/ModelHorse.cpp +++ b/Minecraft.Client/ModelHorse.cpp @@ -252,7 +252,7 @@ void ModelHorse::render(shared_ptr entity, float time, float r, float bo bool largeEars = type == EntityHorse::TYPE_DONKEY || type == EntityHorse::TYPE_MULE; float sizeFactor = entityhorse->getFoalScale(); - bool rider = (entityhorse->rider.lock() != NULL); + bool rider = (entityhorse->rider.lock() != nullptr); if (saddled) { @@ -401,7 +401,7 @@ void ModelHorse::prepareMobModel(shared_ptr mob, float wp, float w float openMouth = entityhorse->getMouthAnim(a); bool tail = entityhorse->tailCounter != 0; bool saddled = entityhorse->isSaddled(); - bool rider = entityhorse->rider.lock() != NULL; + bool rider = entityhorse->rider.lock() != nullptr; float bob = mob->tickCount + a; float legAnim1 = cos((wp * 0.6662f) + 3.141593f); diff --git a/Minecraft.Client/ModelPart.cpp b/Minecraft.Client/ModelPart.cpp index c59a821c7..e423a4ae2 100644 --- a/Minecraft.Client/ModelPart.cpp +++ b/Minecraft.Client/ModelPart.cpp @@ -65,7 +65,7 @@ void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) void ModelPart::addChild(ModelPart *child) { - //if (children == NULL) children = new ModelPartArray; + //if (children == nullptr) children = new ModelPartArray; children.push_back(child); } @@ -89,7 +89,7 @@ ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) } } - return NULL; + return nullptr; } ModelPart *ModelPart::mirror() @@ -139,7 +139,7 @@ void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, float 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)); + cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, static_cast(tex))); } void ModelPart::setPos(float x, float y, float z) @@ -180,7 +180,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) } } } - //if (children != NULL) + //if (children != nullptr) { for (unsigned int i = 0; i < children.size(); i++) { @@ -208,7 +208,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) } } } - //if (children != NULL) + //if (children != nullptr) { for (unsigned int i = 0; i < children.size(); i++) { @@ -234,7 +234,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) } } } - //if (children != NULL) + //if (children != nullptr) { for (unsigned int i = 0; i < children.size(); i++) { @@ -307,8 +307,8 @@ void ModelPart::compile(float scale) ModelPart *ModelPart::setTexSize(int xs, int ys) { - this->xTexSize = (float)xs; - this->yTexSize = (float)ys; + this->xTexSize = static_cast(xs); + this->yTexSize = static_cast(ys); return this; } diff --git a/Minecraft.Client/MultiPlayerChunkCache.cpp b/Minecraft.Client/MultiPlayerChunkCache.cpp index a4c200bed..62361ce36 100644 --- a/Minecraft.Client/MultiPlayerChunkCache.cpp +++ b/Minecraft.Client/MultiPlayerChunkCache.cpp @@ -65,7 +65,7 @@ MultiPlayerChunkCache::MultiPlayerChunkCache(Level *level) { if( y >= 3 ) { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); + static_cast(waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); } } } @@ -77,18 +77,18 @@ MultiPlayerChunkCache::MultiPlayerChunkCache(Level *level) { if( y >= ( level->getSeaLevel() - 1 ) ) { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); + static_cast(waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); } else { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,2); + static_cast(waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,2); } } } } else { - waterChunk = NULL; + waterChunk = nullptr; } this->level = level; @@ -132,7 +132,7 @@ bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) int idx = ix * XZSIZE + iz; LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) + if( chunk == nullptr ) { return false; } @@ -166,7 +166,7 @@ LevelChunk *MultiPlayerChunkCache::create(int x, int z) LevelChunk *chunk = cache[idx]; LevelChunk *lastChunk = chunk; - if( chunk == NULL ) + if( chunk == nullptr ) { EnterCriticalSection(&m_csLoadCreate); @@ -174,7 +174,7 @@ LevelChunk *MultiPlayerChunkCache::create(int x, int z) if( g_NetworkManager.IsHost() ) // force here to disable sharing of data { // 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 (MinecraftServer::getInstance()->serverHalted()) return nullptr; // If we're the host, then don't create the chunk, share data from the server's copy #ifdef _LARGE_WORLDS @@ -248,7 +248,7 @@ LevelChunk *MultiPlayerChunkCache::getChunk(int x, int z) int idx = ix * XZSIZE + iz; LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) + if( chunk == nullptr ) { return emptyChunk; } @@ -279,12 +279,12 @@ void MultiPlayerChunkCache::postProcess(ChunkSource *parent, int x, int z) vector *MultiPlayerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) { - return NULL; + return nullptr; } TilePos *MultiPlayerChunkCache::findNearestMapFeature(Level *level, const wstring &featureName, int x, int y, int z) { - return NULL; + return nullptr; } void MultiPlayerChunkCache::recreateLogicStructuresForChunk(int chunkX, int chunkZ) @@ -294,7 +294,7 @@ void MultiPlayerChunkCache::recreateLogicStructuresForChunk(int chunkX, int chun wstring MultiPlayerChunkCache::gatherStats() { EnterCriticalSection(&m_csLoadCreate); - int size = (int)loadedChunkList.size(); + int size = static_cast(loadedChunkList.size()); LeaveCriticalSection(&m_csLoadCreate); return L"MultiplayerChunkCache: " + std::to_wstring(size); diff --git a/Minecraft.Client/MultiPlayerGameMode.cpp b/Minecraft.Client/MultiPlayerGameMode.cpp index 5f9fc9de2..66fc22a6b 100644 --- a/Minecraft.Client/MultiPlayerGameMode.cpp +++ b/Minecraft.Client/MultiPlayerGameMode.cpp @@ -75,7 +75,7 @@ bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) if (localPlayerMode->isCreative()) { - if (minecraft->player->getCarriedItem() != NULL && dynamic_cast(minecraft->player->getCarriedItem()->getItem()) != NULL) + if (minecraft->player->getCarriedItem() != nullptr && dynamic_cast(minecraft->player->getCarriedItem()->getItem()) != nullptr) { return false; } @@ -84,7 +84,7 @@ bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) Level *level = minecraft->level; Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; - if (oldTile == NULL) return false; + if (oldTile == nullptr) return false; level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); @@ -99,7 +99,7 @@ bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) if (!localPlayerMode->isCreative()) { shared_ptr item = minecraft->player->getSelectedItem(); - if (item != NULL) + if (item != nullptr) { item->mineBlock(level, oldTile->id, x, y, z, minecraft->player); if (item->count == 0) @@ -129,7 +129,7 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) // Skip if we just broke a block — prevents double-break on single clicks if (destroyDelay > 0) return; - connection->send(shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) )); + connection->send(std::make_shared(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)); creativeDestroyBlock(minecraft, this, x, y, z, face); destroyDelay = 5; } @@ -137,9 +137,9 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) { if (isDestroying) { - connection->send(shared_ptr(new PlayerActionPacket(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, face))); + connection->send(std::make_shared(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, face)); } - connection->send( shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); + connection->send(std::make_shared(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)); int t = minecraft->level->getTile(x, y, z); if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); if (t > 0 && @@ -159,7 +159,7 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) destroyingItem = minecraft->player->getCarriedItem(); destroyProgress = 0; destroyTicks = 0; - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); + minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, static_cast(destroyProgress * 10) - 1); } } @@ -169,7 +169,7 @@ void MultiPlayerGameMode::stopDestroyBlock() { if (isDestroying) { - connection->send(shared_ptr(new PlayerActionPacket(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1))); + connection->send(std::make_shared(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1)); } isDestroying = false; @@ -193,7 +193,7 @@ void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) if (localPlayerMode->isCreative()) { destroyDelay = 5; - connection->send(shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); + connection->send(std::make_shared(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)); creativeDestroyBlock(minecraft, this, x, y, z, face); return; } @@ -212,7 +212,7 @@ void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) if (destroyTicks % 4 == 0) { - if (tile != NULL) + if (tile != nullptr) { int iStepSound=tile->soundType->getStepSound(); @@ -225,14 +225,14 @@ void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) if (destroyProgress >= 1) { isDestroying = false; - connection->send( shared_ptr( new PlayerActionPacket(PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face) ) ); + connection->send(std::make_shared(PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face)); destroyBlock(x, y, z, face); destroyProgress = 0; destroyTicks = 0; destroyDelay = 5; } - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); + minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, static_cast(destroyProgress * 10) - 1); } else { @@ -259,8 +259,8 @@ void MultiPlayerGameMode::tick() bool MultiPlayerGameMode::sameDestroyTarget(int x, int y, int z) { shared_ptr selected = minecraft->player->getCarriedItem(); - bool sameItems = destroyingItem == NULL && selected == NULL; - if (destroyingItem != NULL && selected != NULL) + bool sameItems = destroyingItem == nullptr && selected == nullptr; + if (destroyingItem != nullptr && selected != nullptr) { sameItems = selected->id == destroyingItem->id && @@ -276,7 +276,7 @@ void MultiPlayerGameMode::ensureHasSentCarriedItem() if (newItem != carriedItem) { carriedItem = newItem; - connection->send( shared_ptr( new SetCarriedItemPacket(carriedItem) ) ); + connection->send(std::make_shared(carriedItem)); } } @@ -289,12 +289,12 @@ bool MultiPlayerGameMode::useItemOn(shared_ptr player, Level *level, sha { ensureHasSentCarriedItem(); } - float clickX = (float) hit->x - x; - float clickY = (float) hit->y - y; - float clickZ = (float) hit->z - z; + float clickX = static_cast(hit->x) - x; + float clickY = static_cast(hit->y) - y; + float clickZ = static_cast(hit->z) - z; bool didSomething = false; - if (!player->isSneaking() || player->getCarriedItem() == NULL) + if (!player->isSneaking() || player->getCarriedItem() == nullptr) { int t = level->getTile(x, y, z); if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) @@ -327,15 +327,15 @@ bool MultiPlayerGameMode::useItemOn(shared_ptr player, Level *level, sha } } - if (!didSomething && item != NULL && dynamic_cast(item->getItem())) + if (!didSomething && item != nullptr && dynamic_cast(item->getItem())) { TileItem *tile = dynamic_cast(item->getItem()); if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; } - // 4J Stu - In Java we send the use packet before the above check for item being NULL + // 4J Stu - In Java we send the use packet before the above check for item being nullptr // so the following never gets executed but the packet still gets sent (for opening chests etc) - if(item != NULL) + if(item != nullptr) { if(!didSomething && player->isAllowedToUse(item)) { @@ -379,7 +379,7 @@ bool MultiPlayerGameMode::useItemOn(shared_ptr player, Level *level, sha // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. if(!bTestUseOnly) { - connection->send( shared_ptr( new UseItemPacket(x, y, z, face, player->inventory->getSelected(), clickX, clickY, clickZ) ) ); + connection->send(std::make_shared(x, y, z, face, player->inventory->getSelected(), clickX, clickY, clickZ)); } return didSomething; } @@ -408,7 +408,7 @@ bool MultiPlayerGameMode::useItem(shared_ptr player, Level *level, share { int oldCount = item->count; shared_ptr itemInstance = item->use(level, player); - if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount)) + if ((itemInstance != nullptr && itemInstance != item) || (itemInstance != nullptr && itemInstance->count != oldCount)) { player->inventory->items[player->inventory->selected] = itemInstance; if (itemInstance->count == 0) @@ -421,27 +421,27 @@ bool MultiPlayerGameMode::useItem(shared_ptr player, Level *level, share if(!bTestUseOnly) { - connection->send( shared_ptr( new UseItemPacket(-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0) ) ); + connection->send(std::make_shared(-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0)); } return result; } shared_ptr MultiPlayerGameMode::createPlayer(Level *level) { - return shared_ptr( new MultiplayerLocalPlayer(minecraft, level, minecraft->user, connection) ); + return std::make_shared(minecraft, level, minecraft->user, connection); } void MultiPlayerGameMode::attack(shared_ptr player, shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send( shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::ATTACK) ) ); + connection->send(std::make_shared(player->entityId, entity->entityId, InteractPacket::ATTACK)); player->attack(entity); } bool MultiPlayerGameMode::interact(shared_ptr player, shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send(shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::INTERACT) ) ); + connection->send(std::make_shared(player->entityId, entity->entityId, InteractPacket::INTERACT)); return player->interact(entity); } @@ -450,36 +450,36 @@ shared_ptr MultiPlayerGameMode::handleInventoryMouseClick(int cont short changeUid = player->containerMenu->backup(player->inventory); shared_ptr clicked = player->containerMenu->clicked(slotNum, buttonNum, quickKeyHeld?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); - connection->send( shared_ptr( new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, clicked, changeUid) ) ); + connection->send(std::make_shared(containerId, slotNum, buttonNum, quickKeyHeld, clicked, changeUid)); return clicked; } void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, int buttonId) { - connection->send(shared_ptr( new ContainerButtonClickPacket(containerId, buttonId) )); + connection->send(std::make_shared(containerId, buttonId)); } void MultiPlayerGameMode::handleCreativeModeItemAdd(shared_ptr clicked, int slot) { if (localPlayerMode->isCreative()) { - connection->send(shared_ptr( new SetCreativeModeSlotPacket(slot, clicked) ) ); + connection->send(std::make_shared(slot, clicked)); } } void MultiPlayerGameMode::handleCreativeModeItemDrop(shared_ptr clicked) { - if (localPlayerMode->isCreative() && clicked != NULL) + if (localPlayerMode->isCreative() && clicked != nullptr) { - connection->send(shared_ptr( new SetCreativeModeSlotPacket(-1, clicked) ) ); + connection->send(std::make_shared(-1, clicked)); } } void MultiPlayerGameMode::releaseUsingItem(shared_ptr player) { ensureHasSentCarriedItem(); - connection->send(shared_ptr( new PlayerActionPacket(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255) ) ); + connection->send(std::make_shared(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255)); player->releaseUsingItem(); } @@ -514,7 +514,7 @@ bool MultiPlayerGameMode::handleCraftItem(int recipe, shared_ptr player) { short changeUid = player->containerMenu->backup(player->inventory); - connection->send( shared_ptr( new CraftItemPacket(recipe, changeUid) ) ); + connection->send(std::make_shared(recipe, changeUid)); return true; } @@ -522,5 +522,5 @@ bool MultiPlayerGameMode::handleCraftItem(int recipe, shared_ptr player) void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, shared_ptr player) { player->SetDebugOptions(uiVal); - connection->send( shared_ptr( new DebugOptionsPacket(uiVal) ) ); + connection->send(std::make_shared(uiVal)); } diff --git a/Minecraft.Client/MultiPlayerGameMode.h b/Minecraft.Client/MultiPlayerGameMode.h index 76aa8fc84..fb21bb67c 100644 --- a/Minecraft.Client/MultiPlayerGameMode.h +++ b/Minecraft.Client/MultiPlayerGameMode.h @@ -42,7 +42,7 @@ private: bool sameDestroyTarget(int x, int y, int z); void ensureHasSentCarriedItem(); public: - virtual bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=NULL); + virtual bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=nullptr); virtual bool useItem(shared_ptr player, Level *level, shared_ptr item, bool bTestUseOnly=false); virtual shared_ptr createPlayer(Level *level); virtual void attack(shared_ptr player, shared_ptr entity); @@ -65,5 +65,5 @@ public: // 4J Stu - Added for tutorial checks virtual bool isInputAllowed(int mapping) { return true; } virtual bool isTutorial() { return false; } - virtual Tutorial *getTutorial() { return NULL; } + virtual Tutorial *getTutorial() { return nullptr; } }; \ No newline at end of file diff --git a/Minecraft.Client/MultiPlayerLevel.cpp b/Minecraft.Client/MultiPlayerLevel.cpp index 29d88b8d7..4aede4458 100644 --- a/Minecraft.Client/MultiPlayerLevel.cpp +++ b/Minecraft.Client/MultiPlayerLevel.cpp @@ -26,7 +26,7 @@ MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, int data) } MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty) - : Level(shared_ptr(new MockedLevelStorage()), L"MpServer", Dimension::getNew(dimension), levelSettings, false) + : Level(std::make_shared(), L"MpServer", Dimension::getNew(dimension), levelSettings, false) { minecraft = Minecraft::GetInstance(); @@ -43,7 +43,7 @@ MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings * levelData->setInitialized(true); } - if(connection !=NULL) + if(connection !=nullptr) { this->connections.push_back( connection ); } @@ -54,7 +54,7 @@ MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings * //setSpawnPos(new Pos(8, 64, 8)); // The base ctor already has made some storage, so need to delete that if( this->savedDataStorage ) delete savedDataStorage; - if(connection !=NULL) + if(connection !=nullptr) { savedDataStorage = connection->savedDataStorage; } @@ -70,7 +70,7 @@ MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings * MultiPlayerLevel::~MultiPlayerLevel() { // Don't let the base class delete this, it comes from the connection for multiplayerlevels, and we'll delete there - this->savedDataStorage = NULL; + this->savedDataStorage = nullptr; } void MultiPlayerLevel::unshareChunkAt(int x, int z) @@ -465,7 +465,7 @@ void MultiPlayerLevel::entityRemoved(shared_ptr e) void MultiPlayerLevel::putEntity(int id, shared_ptr e) { shared_ptr old = getEntity(id); - if (old != NULL) + if (old != nullptr) { removeEntity(old); } @@ -618,7 +618,7 @@ void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) for (auto& it : connections ) { if ( it ) - it->sendAndDisconnect( shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); + it->sendAndDisconnect(std::make_shared(DisconnectPacket::eDisconnect_Quitting)); } } else @@ -633,7 +633,7 @@ void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) Tickable *MultiPlayerLevel::makeSoundUpdater(shared_ptr minecart) { - return NULL; //new MinecartSoundUpdater(minecraft->soundEngine, minecart, minecraft->player); + return nullptr; //new MinecartSoundUpdater(minecraft->soundEngine, minecart, minecraft->player); } void MultiPlayerLevel::tickWeather() @@ -732,7 +732,7 @@ void MultiPlayerLevel::animateTickDoWork() } } - Minecraft::GetInstance()->animateTickLevel = NULL; + Minecraft::GetInstance()->animateTickLevel = nullptr; delete animateRandom; chunksToAnimate.clear(); @@ -770,18 +770,18 @@ void MultiPlayerLevel::playLocalSound(double x, double y, double z, int iSound, // exhaggerate sound speed effect by making speed of sound ~= // 40 m/s instead of 300 m/s double delayInSeconds = sqrt(minDistSq) / 40.0; - minecraft->soundEngine->schedule(iSound, (float) x, (float) y, (float) z, volume, pitch, (int) Math::round(delayInSeconds * SharedConstants::TICKS_PER_SECOND)); + minecraft->soundEngine->schedule(iSound, static_cast(x), static_cast(y), static_cast(z), volume, pitch, static_cast(Math::round(delayInSeconds * SharedConstants::TICKS_PER_SECOND))); } else { - minecraft->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, pitch); + minecraft->soundEngine->play(iSound, static_cast(x), static_cast(y), static_cast(z), volume, pitch); } } } void MultiPlayerLevel::createFireworks(double x, double y, double z, double xd, double yd, double zd, CompoundTag *infoTag) { - minecraft->particleEngine->add(shared_ptr(new FireworksParticles::FireworksStarter(this, x, y, z, xd, yd, zd, minecraft->particleEngine, infoTag))); + minecraft->particleEngine->add(std::make_shared(this, x, y, z, xd, yd, zd, minecraft->particleEngine, infoTag)); } void MultiPlayerLevel::setScoreboard(Scoreboard *scoreboard) @@ -860,7 +860,7 @@ void MultiPlayerLevel::removeAllPendingEntityRemovals() { shared_ptr e = *it;//entities.at(i); - if (e->riding != NULL) + if (e->riding != nullptr) { if (e->riding->removed || e->riding->rider.lock() != e) { @@ -899,7 +899,7 @@ void MultiPlayerLevel::removeClientConnection(ClientConnection *c, bool sendDisc { if( sendDisconnect ) { - c->sendAndDisconnect( shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); + c->sendAndDisconnect(std::make_shared(DisconnectPacket::eDisconnect_Quitting)); } auto it = find(connections.begin(), connections.end(), c); @@ -937,11 +937,11 @@ void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) { LevelChunk *lc = getChunk(te->x >> 4, te->z >> 4); - if (lc != NULL) + if (lc != nullptr) { // Only remove tile entities where this is no longer a tile entity int tileId = lc->getTile(te->x & 15, te->y, te->z & 15 ); - if( Tile::tiles[tileId] == NULL || !Tile::tiles[tileId]->isEntityTile()) + if( Tile::tiles[tileId] == nullptr || !Tile::tiles[tileId]->isEntityTile()) { tileEntityList[i] = tileEntityList.back(); tileEntityList.pop_back(); diff --git a/Minecraft.Client/MultiPlayerLevel.h b/Minecraft.Client/MultiPlayerLevel.h index a552fc2b1..b7f1640a3 100644 --- a/Minecraft.Client/MultiPlayerLevel.h +++ b/Minecraft.Client/MultiPlayerLevel.h @@ -12,6 +12,7 @@ using namespace std; class MultiPlayerLevel : public Level { + friend class ClientConnection; private: static const int TICKS_BEFORE_RESET = 20 * 4; diff --git a/Minecraft.Client/MultiPlayerLocalPlayer.cpp b/Minecraft.Client/MultiPlayerLocalPlayer.cpp index 25bf06bf1..aef7898f2 100644 --- a/Minecraft.Client/MultiPlayerLocalPlayer.cpp +++ b/Minecraft.Client/MultiPlayerLocalPlayer.cpp @@ -76,8 +76,8 @@ void MultiplayerLocalPlayer::tick() { if (isRiding()) { - connection->send(shared_ptr(new MovePlayerPacket::Rot(yRot, xRot, onGround, abilities.flying))); - connection->send(shared_ptr(new PlayerInputPacket(xxa, yya, input->jumping, input->sneaking))); + connection->send(std::make_shared(yRot, xRot, onGround, abilities.flying)); + connection->send(std::make_shared(xxa, yya, input->jumping, input->sneaking)); } else { @@ -96,8 +96,8 @@ void MultiplayerLocalPlayer::sendPosition() bool sprinting = isSprinting(); if (sprinting != lastSprinting) { - if (sprinting) connection->send(shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SPRINTING))); - else connection->send(shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); + if (sprinting) connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::START_SPRINTING)); + else connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::STOP_SPRINTING)); lastSprinting = sprinting; } @@ -105,8 +105,8 @@ void MultiplayerLocalPlayer::sendPosition() bool sneaking = isSneaking(); if (sneaking != lastSneaked) { - if (sneaking) connection->send( shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SNEAKING) ) ); - else connection->send( shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SNEAKING) ) ); + if (sneaking) connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::START_SNEAKING)); + else connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::STOP_SNEAKING)); lastSneaked = sneaking; } @@ -114,8 +114,8 @@ void MultiplayerLocalPlayer::sendPosition() bool idle = isIdle(); if (idle != lastIdle) { - if (idle) connection->send( shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_IDLEANIM) ) ); - else connection->send( shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM) ) ); + if (idle) connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::START_IDLEANIM)); + else connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM)); lastIdle = idle; } @@ -129,28 +129,28 @@ void MultiplayerLocalPlayer::sendPosition() bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || positionReminder >= POSITION_REMINDER_INTERVAL; bool rot = rydd != 0 || rxdd != 0; - if (riding != NULL) + if (riding != nullptr) { - connection->send( shared_ptr( new MovePlayerPacket::PosRot(xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying) ) ); + connection->send(std::make_shared(xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying)); move = false; } else { if (move && rot) { - connection->send( shared_ptr( new MovePlayerPacket::PosRot(x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying) ) ); + connection->send(std::make_shared(x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying)); } else if (move) { - connection->send( shared_ptr( new MovePlayerPacket::Pos(x, bb->y0, y, z, onGround, abilities.flying) ) ); + connection->send(std::make_shared(x, bb->y0, y, z, onGround, abilities.flying)); } else if (rot) { - connection->send( shared_ptr( new MovePlayerPacket::Rot(yRot, xRot, onGround, abilities.flying) ) ); + connection->send(std::make_shared(yRot, xRot, onGround, abilities.flying)); } else { - connection->send( shared_ptr( new MovePlayerPacket(onGround, abilities.flying) ) ); + connection->send(std::make_shared(onGround, abilities.flying)); } } @@ -175,7 +175,7 @@ void MultiplayerLocalPlayer::sendPosition() shared_ptr MultiplayerLocalPlayer::drop() { - connection->send( shared_ptr( new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0) ) ); + connection->send(std::make_shared(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0)); return nullptr; } @@ -185,19 +185,19 @@ void MultiplayerLocalPlayer::reallyDrop(shared_ptr itemEntity) void MultiplayerLocalPlayer::chat(const wstring& message) { - connection->send( shared_ptr( new ChatPacket(message) ) ); + connection->send(std::make_shared(message)); } void MultiplayerLocalPlayer::swing() { LocalPlayer::swing(); - connection->send( shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) ); + connection->send(std::make_shared(shared_from_this(), AnimatePacket::SWING)); } void MultiplayerLocalPlayer::respawn() { - connection->send( shared_ptr( new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN))); + connection->send(std::make_shared(ClientCommandPacket::PERFORM_RESPAWN)); } @@ -211,9 +211,9 @@ void MultiplayerLocalPlayer::actuallyHurt(DamageSource *source, float dmg) void MultiplayerLocalPlayer::completeUsingItem() { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) + if(useItem != nullptr && pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); Tutorial *tutorial = gameMode->getTutorial(); tutorial->completeUsingItem(useItem); } @@ -223,9 +223,9 @@ void MultiplayerLocalPlayer::completeUsingItem() void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance *effect) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); Tutorial *tutorial = gameMode->getTutorial(); tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); } @@ -236,9 +236,9 @@ void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance *effect) void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance *effect, bool doRefreshAttributes) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); Tutorial *tutorial = gameMode->getTutorial(); tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); } @@ -249,9 +249,9 @@ void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance *effect, bool doR void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance *effect) { Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) + if(pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); Tutorial *tutorial = gameMode->getTutorial(); tutorial->onEffectChanged(MobEffect::effects[effect->getId()],true); } @@ -260,7 +260,7 @@ void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance *effect) void MultiplayerLocalPlayer::closeContainer() { - connection->send( shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); + connection->send(std::make_shared(containerMenu->containerId)); clientSideCloseContainer(); } @@ -286,7 +286,7 @@ void MultiplayerLocalPlayer::hurtTo(float newHealth, ETelemetryChallenges damage void MultiplayerLocalPlayer::awardStat(Stat *stat, byteArray param) { - if (stat == NULL) + if (stat == nullptr) { delete [] param.data; return; @@ -305,7 +305,7 @@ void MultiplayerLocalPlayer::awardStat(Stat *stat, byteArray param) void MultiplayerLocalPlayer::awardStatFromServer(Stat *stat, byteArray param) { - if ( stat != NULL && !stat->awardLocallyOnly ) + if ( stat != nullptr && !stat->awardLocallyOnly ) { LocalPlayer::awardStat(stat, param); } @@ -314,7 +314,7 @@ void MultiplayerLocalPlayer::awardStatFromServer(Stat *stat, byteArray param) void MultiplayerLocalPlayer::onUpdateAbilities() { - connection->send(shared_ptr(new PlayerAbilitiesPacket(&abilities))); + connection->send(std::make_shared(&abilities)); } bool MultiplayerLocalPlayer::isLocalPlayer() @@ -324,19 +324,19 @@ bool MultiplayerLocalPlayer::isLocalPlayer() void MultiplayerLocalPlayer::sendRidingJump() { - connection->send(shared_ptr(new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::RIDING_JUMP, (int) (getJumpRidingScale() * 100.0f)))); + connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::RIDING_JUMP, static_cast(getJumpRidingScale() * 100.0f))); } void MultiplayerLocalPlayer::sendOpenInventory() { - connection->send(shared_ptr(new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::OPEN_INVENTORY))); + connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::OPEN_INVENTORY)); } void MultiplayerLocalPlayer::ride(shared_ptr e) { - bool wasRiding = riding != NULL; + bool wasRiding = riding != nullptr; LocalPlayer::ride(e); - bool isRiding = riding != NULL; + bool isRiding = riding != nullptr; // 4J Added if(wasRiding && !isRiding) @@ -348,7 +348,7 @@ void MultiplayerLocalPlayer::ride(shared_ptr e) if( isRiding ) { ETelemetryChallenges eventType = eTelemetryChallenges_Unknown; - if( this->riding != NULL ) + if( this->riding != nullptr ) { switch(riding->GetType()) { @@ -370,9 +370,9 @@ void MultiplayerLocalPlayer::ride(shared_ptr e) Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localgameModes[m_iPad] != NULL ) + if( pMinecraft->localgameModes[m_iPad] != nullptr ) { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; + TutorialMode *gameMode = static_cast(pMinecraft->localgameModes[m_iPad]); if(wasRiding && !isRiding) { gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Gameplay); @@ -386,7 +386,7 @@ void MultiplayerLocalPlayer::ride(shared_ptr e) void MultiplayerLocalPlayer::StopSleeping() { - connection->send( shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SLEEPING) ) ); + connection->send(std::make_shared(shared_from_this(), PlayerCommandPacket::STOP_SLEEPING)); } // 4J Added @@ -397,7 +397,7 @@ void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(DWORD skinId) #ifndef _CONTENT_PACKAGE wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin() ); #endif - if(getCustomSkin() != oldSkinIndex) connection->send( shared_ptr( new TextureAndGeometryChangePacket( shared_from_this(), app.GetPlayerSkinName(GetXboxPad()) ) ) ); + if(getCustomSkin() != oldSkinIndex) connection->send(std::make_shared(shared_from_this(), app.GetPlayerSkinName(GetXboxPad()))); } void MultiplayerLocalPlayer::setAndBroadcastCustomCape(DWORD capeId) @@ -407,7 +407,7 @@ void MultiplayerLocalPlayer::setAndBroadcastCustomCape(DWORD capeId) #ifndef _CONTENT_PACKAGE wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), customTextureUrl2.c_str()); #endif - if(getCustomCape() != oldCapeIndex) connection->send( shared_ptr( new TextureChangePacket( shared_from_this(), TextureChangePacket::e_TextureChange_Cape, app.GetPlayerCapeName(GetXboxPad()) ) ) ); + if(getCustomCape() != oldCapeIndex) connection->send(std::make_shared(shared_from_this(), TextureChangePacket::e_TextureChange_Cape, app.GetPlayerCapeName(GetXboxPad()))); } // 4J added for testing. This moves the player in a repeated sequence of 2 modes: diff --git a/Minecraft.Client/MushroomCowRenderer.cpp b/Minecraft.Client/MushroomCowRenderer.cpp index b5f9ba9f8..277e05d8a 100644 --- a/Minecraft.Client/MushroomCowRenderer.cpp +++ b/Minecraft.Client/MushroomCowRenderer.cpp @@ -42,7 +42,7 @@ void MushroomCowRenderer::additionalRendering(shared_ptr _mob, flo glPopMatrix(); glPushMatrix(); - ((QuadrupedModel *) model)->head->translateTo(1 / 16.0f); + static_cast(model)->head->translateTo(1 / 16.0f); glScalef(1, -1, 1); glTranslatef(0, 0.75f, -0.2f); glRotatef(12, 0, 1, 0); diff --git a/Minecraft.Client/NameEntryScreen.cpp b/Minecraft.Client/NameEntryScreen.cpp index c9df70245..f498d4ea3 100644 --- a/Minecraft.Client/NameEntryScreen.cpp +++ b/Minecraft.Client/NameEntryScreen.cpp @@ -41,7 +41,7 @@ void NameEntryScreen::buttonClicked(Button button) if (button.id == 0 && trimString(name).length() > 1) { minecraft->saveSlot(slot, trimString(name)); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft->grabMouse(); // 4J - removed } if (button.id == 1) diff --git a/Minecraft.Client/NetherPortalParticle.cpp b/Minecraft.Client/NetherPortalParticle.cpp index 4b70d38f5..9dcdd4ce5 100644 --- a/Minecraft.Client/NetherPortalParticle.cpp +++ b/Minecraft.Client/NetherPortalParticle.cpp @@ -33,14 +33,14 @@ NetherPortalParticle::NetherPortalParticle(Level *level, double x, double y, dou gCol = (g/255.0f)*br; bCol = (b/255.0f)*br; - lifetime = (int) (Math::random()*10) + 40; + lifetime = static_cast(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex(static_cast(Math::random() * 8)); } void NetherPortalParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; + float s = (age + a) / static_cast(lifetime); s = 1-s; s = s*s; s = 1-s; @@ -53,13 +53,13 @@ int NetherPortalParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); pos = pos*pos; pos = pos*pos; int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += static_cast(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } @@ -67,7 +67,7 @@ int NetherPortalParticle::getLightColor(float a) float NetherPortalParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); pos = pos*pos; pos = pos*pos; return br*(1-pos)+pos; @@ -79,7 +79,7 @@ void NetherPortalParticle::tick() yo = y; zo = z; - float pos = age/(float)lifetime; + float pos = age/static_cast(lifetime); float a = pos; pos = -pos+pos*pos*2; // pos = pos*pos; diff --git a/Minecraft.Client/NoteParticle.cpp b/Minecraft.Client/NoteParticle.cpp index 2e2320c8a..6d2a31cdb 100644 --- a/Minecraft.Client/NoteParticle.cpp +++ b/Minecraft.Client/NoteParticle.cpp @@ -22,8 +22,8 @@ void NoteParticle::init(Level *level, double x, double y, double z, double xa, d // 4J-JEV: Added, // There are 24 valid colours for this particle input through the 'xa' field (0.0-1.0). - int note = (int) floor(0.5 + (xa*24.0)) + (int) eMinecraftColour_Particle_Note_00; - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( (eMinecraftColour) note ); + int note = static_cast(floor(0.5 + (xa * 24.0))) + static_cast(eMinecraftColour_Particle_Note_00); + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( static_cast(note) ); rCol = ( (col>>16)&0xFF )/255.0; gCol = ( (col>>8)&0xFF )/255.0; diff --git a/Minecraft.Client/OffsettedRenderList.cpp b/Minecraft.Client/OffsettedRenderList.cpp index 729d26f92..0a93fa921 100644 --- a/Minecraft.Client/OffsettedRenderList.cpp +++ b/Minecraft.Client/OffsettedRenderList.cpp @@ -20,9 +20,9 @@ void OffsettedRenderList::init(int x, int y, int z, double xOff, double yOff, do this->y = y; this->z = z; - this->xOff = (float) xOff; - this->yOff = (float) yOff; - this->zOff = (float) zOff; + this->xOff = static_cast(xOff); + this->yOff = static_cast(yOff); + this->zOff = static_cast(zOff); } bool OffsettedRenderList::isAt(int x, int y, int z) diff --git a/Minecraft.Client/Options.cpp b/Minecraft.Client/Options.cpp index 35857b896..ebe1295af 100644 --- a/Minecraft.Client/Options.cpp +++ b/Minecraft.Client/Options.cpp @@ -76,7 +76,7 @@ bool Options::Option::isBoolean() const int Options::Option::getId() const { - return (int)(this-options); + return static_cast(this - options); } wstring Options::Option::getCaptionId() const @@ -152,8 +152,8 @@ void Options::init() keyMappings[12] = keyPickItem; keyMappings[13] = keyToggleFog; - minecraft = NULL; - //optionsFile = NULL; + minecraft = nullptr; + //optionsFile = nullptr; difficulty = 2; hideGui = false; @@ -417,12 +417,12 @@ void Options::load() 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? + while ((line = br->readLine()) != L"") // 4J - was check against nullptr - do we need to distinguish between empty lines and a fail here? { // 4J - removed try/catch // try { wstring cmds[2]; - int splitpos = (int)line.find(L":"); + size_t splitpos = line.find(L":"); if( splitpos == wstring::npos ) { cmds[0] = line; diff --git a/Minecraft.Client/OptionsScreen.cpp b/Minecraft.Client/OptionsScreen.cpp index b5c2f5e60..507640066 100644 --- a/Minecraft.Client/OptionsScreen.cpp +++ b/Minecraft.Client/OptionsScreen.cpp @@ -47,9 +47,9 @@ void OptionsScreen::init() void OptionsScreen::buttonClicked(Button *button) { if (!button->active) return; - if (button->id < 100 && (dynamic_cast(button) != NULL)) + if (button->id < 100 && (dynamic_cast(button) != nullptr)) { - options->toggle(((SmallButton *) button)->getOption(), 1); + options->toggle(static_cast(button)->getOption(), 1); button->msg = options->getMessage(Options::Option::getItem(button->id)); } if (button->id == VIDEO_BUTTON_ID) diff --git a/Minecraft.Client/Orbis/4JLibs/inc/4J_Profile.h b/Minecraft.Client/Orbis/4JLibs/inc/4J_Profile.h index 03651b8fe..d988adbfe 100644 --- a/Minecraft.Client/Orbis/4JLibs/inc/4J_Profile.h +++ b/Minecraft.Client/Orbis/4JLibs/inc/4J_Profile.h @@ -120,7 +120,7 @@ public: // ACHIEVEMENTS & AWARDS void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); + CXuiStringTable*pStringTable=nullptr, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=nullptr, unsigned int uiThemeSize=0L); int GetAwardId(int iAwardNumber); eAwardType GetAwardType(int iAwardNumber); bool CanBeAwarded(int iQuadrant, int iAwardNumber); diff --git a/Minecraft.Client/Orbis/4JLibs/inc/4J_Render.h b/Minecraft.Client/Orbis/4JLibs/inc/4J_Render.h index 6083654d2..00210f609 100644 --- a/Minecraft.Client/Orbis/4JLibs/inc/4J_Render.h +++ b/Minecraft.Client/Orbis/4JLibs/inc/4J_Render.h @@ -19,8 +19,8 @@ public: int GetType() { return m_type; } void *GetBufferPointer() { return m_pBuffer; } int GetBufferSize() { return m_bufferSize; } - void Release() { free(m_pBuffer); m_pBuffer = NULL; } - bool Allocated() { return m_pBuffer != NULL; } + void Release() { free(m_pBuffer); m_pBuffer = nullptr; } + bool Allocated() { return m_pBuffer != nullptr; } }; typedef struct @@ -62,7 +62,7 @@ public: void InitialiseContext(); void StartFrame(bool actualFrameStart = true); void Present(); - void Clear(int flags);//, D3D11_RECT *pRect = NULL); + void Clear(int flags);//, D3D11_RECT *pRect = nullptr); void SetClearColour(const float colourRGBA[4]); bool IsWidescreen(); bool IsHiDef(); diff --git a/Minecraft.Client/Orbis/4JLibs/inc/4J_Storage.h b/Minecraft.Client/Orbis/4JLibs/inc/4J_Storage.h index d4d845dfa..467c7a116 100644 --- a/Minecraft.Client/Orbis/4JLibs/inc/4J_Storage.h +++ b/Minecraft.Client/Orbis/4JLibs/inc/4J_Storage.h @@ -28,7 +28,7 @@ typedef struct int newSaveBlocksUsed; int iSaveC; PSAVE_INFO SaveInfoA; - PSAVE_INFO pCurrentSaveInfo; // Pointer to SAVE_INFO for the save that has just been loaded, or NULL if no save has been loaded (ie this is a newly created game) + PSAVE_INFO pCurrentSaveInfo; // Pointer to SAVE_INFO for the save that has just been loaded, or nullptr if no save has been loaded (ie this is a newly created game) } SAVE_DETAILS,*PSAVE_DETAILS; @@ -315,7 +315,7 @@ public: // Get details of existing savedata C4JStorage::ESaveGameState GetSavesInfo(int iPad,int ( *Func)(LPVOID lpParam,SAVE_DETAILS *pSaveDetails,const bool),LPVOID lpParam,char *pszSavePackName); // Start search - PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or NULL if not yet received) + PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or nullptr if not yet received) void ClearSavesInfo(); // Clears results C4JStorage::ESaveGameState LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo,int( *Func)(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes), LPVOID lpParam); // Get the thumbnail for an individual save referenced by pSaveInfo @@ -398,8 +398,8 @@ public: EDLCStatus GetInstalledDLC(int iPad,int( *Func)(LPVOID, int, int),LPVOID lpParam); CONTENT_DATA& GetDLC(DWORD dw); DWORD GetAvailableDLCCount( int iPad ); - DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive = NULL); - DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL); + DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive = nullptr); + DWORD UnmountInstalledDLC(LPCSTR szMountDrive = nullptr); void GetMountedDLCFileList(const char* szMountDrive, std::vector& fileList); std::string GetMountedPath(std::string szMount); void SetDLCProductCode(const char* szProductCode); diff --git a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.cpp b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.cpp index 122333607..33fd6b4a7 100644 --- a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.cpp +++ b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.cpp @@ -353,7 +353,7 @@ static void gdraw_defragment_cache(GDrawHandleCache *c, GDrawStats *stats) // synchronize compute_to_graphics_sync(); - gdraw->gfxc->setCsShader(NULL); + gdraw->gfxc->setCsShader(nullptr); gdraw->gfxc->setShaderType(Gnm::kShaderTypeGraphics); // don't need to wait till GPU is done since we never access GPU memory from the @@ -365,7 +365,7 @@ static void api_free_resource(GDrawHandle *r) if (!r->cache->is_vertex) { for (S32 i=0; i < MAX_SAMPLERS; i++) if (gdraw->active_tex[i] == (GDrawTexture *) r) - gdraw->active_tex[i] = NULL; + gdraw->active_tex[i] = nullptr; } } @@ -410,7 +410,7 @@ static void track_staging_alloc_attempt(U32 size, U32 align) static void track_staging_alloc_failed() { if (gdraw->staging_stats.allocs_attempted == gdraw->staging_stats.allocs_succeeded + 1) { // warn the first time we run out of mem - IggyGDrawSendWarning(NULL, "GDraw out of staging memory"); + IggyGDrawSendWarning(nullptr, "GDraw out of staging memory"); } } @@ -537,7 +537,7 @@ static void gpu_compute_memset(void *ptr, U32 value, U32 size_in_bytes) // through the regular caches. gfxc->flushShaderCachesAndWait(Gnm::kCacheActionWriteBackL2Volatile, 0, Gnm::kStallCommandBufferParserDisable); gfxc->setShaderType(Gnm::kShaderTypeGraphics); - gfxc->setCsShader(NULL); + gfxc->setCsShader(nullptr); } //////////////////////////////////////////////////////////////////////// @@ -549,8 +549,8 @@ GDrawTexture * RADLINK gdraw_orbis_WrappedTextureCreate(Gnm::Texture *tex) { GDrawStats stats = {}; GDrawHandle *p = gdraw_res_alloc_begin(gdraw->texturecache, 0, &stats); - p->handle.tex.gnm_ptr = NULL; - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + p->handle.tex.gnm_ptr = nullptr; + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); gdraw_orbis_WrappedTextureChange((GDrawTexture *) p, tex); return (GDrawTexture *) p; } @@ -583,13 +583,13 @@ static void RADLINK gdraw_SetTextureUniqueID(GDrawTexture *tex, void *old_id, vo static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format gformat, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { S32 bytes_pixel = 4; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; Gnm::Texture gt; Gnm::SizeAlign sa; Gnm::DataFormat format = Gnm::kDataFormatR8G8B8A8Unorm; if (width > MAX_TEXTURE2D_DIM || height > MAX_TEXTURE2D_DIM) { - IggyGDrawSendWarning(NULL, "GDraw %d x %d texture not supported by hardware (dimension limit %d)", width, height, MAX_TEXTURE2D_DIM); + IggyGDrawSendWarning(nullptr, "GDraw %d x %d texture not supported by hardware (dimension limit %d)", width, height, MAX_TEXTURE2D_DIM); return false; } @@ -742,8 +742,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *t, void *unique_id, GDr static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *stats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); + if (t->owner == unique_id || unique_id == nullptr) { if (t->cache == &gdraw->rendertargets) { gdraw_HandleCacheUnlock(t); // cache it by simply not freeing it @@ -863,7 +863,7 @@ static rrbool RADLINK gdraw_TryLockVertexBuffer(GDrawVertexBuffer *vb, void *uni static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); // @GDRAW_ASSERT + assert(h != nullptr); // @GDRAW_ASSERT if (h->owner == unique_id) gdraw_res_kill(h, stats); } @@ -891,19 +891,19 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) t = gdraw_HandleCacheAllocateBegin(&gdraw->rendertargets); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit handle limit"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit handle limit"); return t; } U8 *ptr = (U8 *)gdraw_arena_alloc(&gdraw->rt_arena, gdraw->rt_colorbuffer_sa.m_size, gdraw->rt_colorbuffer_sa.m_align); if (!ptr) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: out of rendertarget texture memory"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: out of rendertarget texture memory"); gdraw_HandleCacheAllocateFail(t); - return NULL; + return nullptr; } t->fence = get_next_fence(); - t->raw_ptr = NULL; + t->raw_ptr = nullptr; t->handle.tex.gnm_ptr = ptr; t->handle.tex.gnm->initFromRenderTarget(&gdraw->rt_colorbuffer, false); @@ -1065,7 +1065,7 @@ static void set_common_renderstate() // clear our state caching memset(gdraw->active_tex, 0, sizeof(gdraw->active_tex)); - gdraw->cur_ps = NULL; + gdraw->cur_ps = nullptr; gdraw->scissor_state = ~0u; gdraw->blend_mode = -1; @@ -1230,7 +1230,7 @@ static void eliminate_fast_clear() } gfxc->setCbControl(Gnm::kCbModeEliminateFastClear, Gnm::kRasterOpSrcCopy); - gfxc->setPsShader(NULL); + gfxc->setPsShader(nullptr); set_viewport_raw(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0); set_projection_raw(r.x0, r.x1, r.y1, r.y0); GDrawStats stats = {}; // we already counted these clears once, so don't add to main stats @@ -1245,7 +1245,7 @@ static void eliminate_fast_clear() set_viewport(); set_projection(); - gdraw->cur_ps = NULL; + gdraw->cur_ps = nullptr; gdraw->cur->needs_clear_eliminate = false; } @@ -1276,7 +1276,7 @@ static inline U32 pack_color_8888(F32 x, F32 y, F32 z, F32 w) void gdraw_orbis_ClearWholeRenderTarget(const F32 clear_color_rgba[4]) { - assert(gdraw->gfxc != NULL); // call after gdraw_orbis_Begin + assert(gdraw->gfxc != nullptr); // call after gdraw_orbis_Begin gdraw->cur = gdraw->frame; set_common_renderstate(); @@ -1336,16 +1336,16 @@ static void RADLINK gdraw_SetViewSizeAndWorldScale(S32 w, S32 h, F32 scalex, F32 // must include anything necessary for texture creation/update static void RADLINK gdraw_RenderingBegin(void) { - assert(gdraw->gfxc != NULL); // call after gdraw_orbis_Begin + assert(gdraw->gfxc != nullptr); // call after gdraw_orbis_Begin // unbind all shaders Gnmx::GfxContext *gfxc = gdraw->gfxc; - gfxc->setVsShader(NULL, 0, (void*)0); - gfxc->setPsShader(NULL); - gfxc->setCsShader(NULL); - gfxc->setLsHsShaders(NULL, 0, (void*)0, NULL, 0); - gfxc->setEsShader(NULL, 0, (void *) 0); - gfxc->setGsVsShaders(NULL); + gfxc->setVsShader(nullptr, 0, (void*)0); + gfxc->setPsShader(nullptr); + gfxc->setCsShader(nullptr); + gfxc->setLsHsShaders(nullptr, 0, (void*)0, nullptr, 0); + gfxc->setEsShader(nullptr, 0, (void *) 0); + gfxc->setGsVsShaders(nullptr); set_common_renderstate(); } @@ -1406,7 +1406,7 @@ GDRAW_MAYBE_UNUSED static bool mem_is_direct_and_write_combined_or_cached(const void gdraw_orbis_Begin(sce::Gnmx::GfxContext *context, void *staging_buffer, U32 staging_buf_bytes) { - assert(gdraw->gfxc == NULL); // may not nest Begin calls + assert(gdraw->gfxc == nullptr); // may not nest Begin calls // make sure that the memory setup is sensible. // if any of these asserts fire, please relocate your command buffers @@ -1426,13 +1426,13 @@ void gdraw_orbis_Begin(sce::Gnmx::GfxContext *context, void *staging_buffer, U32 void gdraw_orbis_End(gdraw_orbis_staging_stats *stats) { - assert(gdraw->gfxc != NULL); // please keep Begin / End pairs properly matched + assert(gdraw->gfxc != nullptr); // please keep Begin / End pairs properly matched gdraw_HandleCacheTick(gdraw->texturecache, gdraw->tile_end_fence); gdraw_HandleCacheTick(gdraw->vbufcache, gdraw->tile_end_fence); - gdraw_arena_init(&gdraw->staging, NULL, 0); - gdraw->gfxc = NULL; + gdraw_arena_init(&gdraw->staging, nullptr, 0); + gdraw->gfxc = nullptr; if (stats) *stats = gdraw->staging_stats; @@ -1440,7 +1440,7 @@ void gdraw_orbis_End(gdraw_orbis_staging_stats *stats) void gdraw_orbis_EliminateFastClears(void) { - assert(gdraw->gfxc != NULL); // call between gdraw_orbis_Begin and gdraw_orbis_End + assert(gdraw->gfxc != nullptr); // call between gdraw_orbis_Begin and gdraw_orbis_End eliminate_fast_clear(); } @@ -1469,18 +1469,18 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex GDrawFramebufferState *n = gdraw->cur+1; GDrawHandle *t; if (gdraw->tw == 0 || gdraw->th == 0) { - IggyGDrawSendWarning(NULL, "GDraw warning: w=0,h=0 rendertarget"); + IggyGDrawSendWarning(nullptr, "GDraw warning: w=0,h=0 rendertarget"); return false; } if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); return false; } if (owner) { // @TODO implement - t = NULL; + t = nullptr; assert(0); // nyi } else { t = get_color_rendertarget(stats); @@ -1489,9 +1489,9 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex } n->color_buffer = t; - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT - n->cached = owner != NULL; + n->cached = owner != nullptr; if (owner) { n->base_x = region->x0; n->base_y = region->y0; @@ -1571,9 +1571,9 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) assert(m >= gdraw->frame); // bug in Iggy -- unbalanced if (m != gdraw->frame) { - assert(m->color_buffer != NULL); // @GDRAW_ASSERT + assert(m->color_buffer != nullptr); // @GDRAW_ASSERT } - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT // sync on draw completion for this render target rtt_sync(n->color_buffer->handle.tex.gnm_ptr, gdraw->rt_colorbuffer_sa.m_size >> 8); @@ -1615,7 +1615,7 @@ static void RADLINK gdraw_ClearID(void) static RADINLINE void set_texture(U32 texunit, GDrawTexture *tex) { assert(texunit < MAX_SAMPLERS); - assert(tex != NULL); + assert(tex != nullptr); if (gdraw->active_tex[texunit] != tex) { gdraw->active_tex[texunit] = tex; @@ -1791,7 +1791,7 @@ static void set_vertex_buffer(const GDraw::VFormatDesc *fmtdesc, void *ptr, U32 gdraw->gfxc->setBuffers(Gnm::kShaderStageVs, 0, fmtdesc->num_attribs, bufs); } -static RADINLINE void fence_resources(void *r1, void *r2=NULL, void *r3=NULL, void *r4=NULL) +static RADINLINE void fence_resources(void *r1, void *r2=nullptr, void *r3=nullptr, void *r4=nullptr) { GDrawFence fence = get_next_fence(); if (r1) ((GDrawHandle *) r1)->fence = fence; @@ -1937,7 +1937,7 @@ static void set_clamp_constant(F32 *constant, GDrawTexture *tex) static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbevel, GDrawStats *stats) { - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, stats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, stats)) return; set_texture(0, r->tex[0]); @@ -2236,7 +2236,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_orbis_resourcetype type, U32 al cache->alloc = gfxalloc_create(gdraw_limits[type].ptr, num_bytes, align, num_handles); if (!cache->alloc) { IggyGDrawFree(cache); - cache = NULL; + cache = nullptr; } } @@ -2302,12 +2302,12 @@ int gdraw_orbis_SetResourceMemory(gdraw_orbis_resourcetype type, S32 num_handles case GDRAW_ORBIS_RESOURCE_texture: free_handle_cache(gdraw->texturecache); gdraw->texturecache = make_handle_cache(GDRAW_ORBIS_RESOURCE_texture, GDRAW_ORBIS_TEXTURE_ALIGNMENT); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_ORBIS_RESOURCE_vertexbuffer: free_handle_cache(gdraw->vbufcache); gdraw->vbufcache = make_handle_cache(GDRAW_ORBIS_RESOURCE_vertexbuffer, GDRAW_ORBIS_VERTEXBUFFER_ALIGNMENT); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; default: return 0; @@ -2316,9 +2316,9 @@ int gdraw_orbis_SetResourceMemory(gdraw_orbis_resourcetype type, S32 num_handles void gdraw_orbis_ResetAllResourceMemory() { - gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_rendertarget, 0, NULL, 0); - gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_texture, 0, NULL, 0); - gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_vertexbuffer, 0, NULL, 0); + gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_rendertarget, 0, nullptr, 0); + gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_texture, 0, nullptr, 0); + gdraw_orbis_SetResourceMemory(GDRAW_ORBIS_RESOURCE_vertexbuffer, 0, nullptr, 0); } GDrawFunctions *gdraw_orbis_CreateContext(S32 w, S32 h, void *context_shared_mem) @@ -2326,7 +2326,7 @@ GDrawFunctions *gdraw_orbis_CreateContext(S32 w, S32 h, void *context_shared_mem U32 cpram_shadow_size = Gnmx::ConstantUpdateEngine::computeCpRamShadowSize(); gdraw = (GDraw *) IggyGDrawMalloc(sizeof(*gdraw) + cpram_shadow_size); - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -2349,7 +2349,7 @@ GDrawFunctions *gdraw_orbis_CreateContext(S32 w, S32 h, void *context_shared_mem Gnm::DataFormat rtFormat = Gnm::kDataFormatR8G8B8A8Unorm; Gnm::TileMode tileMode; GpuAddress::computeSurfaceTileMode(&tileMode, GpuAddress::kSurfaceTypeRwTextureFlat, rtFormat, 1); - gdraw->rt_colorbuffer_sa = gdraw->rt_colorbuffer.init(gdraw->frametex_width, gdraw->frametex_height, 1, rtFormat, tileMode, Gnm::kNumSamples1, Gnm::kNumFragments1, NULL, NULL); + gdraw->rt_colorbuffer_sa = gdraw->rt_colorbuffer.init(gdraw->frametex_width, gdraw->frametex_height, 1, rtFormat, tileMode, Gnm::kNumSamples1, Gnm::kNumFragments1, nullptr, nullptr); gdraw->rt_colorbuffer.setCmaskFastClearEnable(false); // shaders and state @@ -2418,7 +2418,7 @@ void gdraw_orbis_DestroyContext(void) free_handle_cache(gdraw->texturecache); free_handle_cache(gdraw->vbufcache); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } } diff --git a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.h b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.h index 9fecfb085..13964e078 100644 --- a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.h +++ b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis.h @@ -50,7 +50,7 @@ IDOC extern int gdraw_orbis_SetResourceMemory(gdraw_orbis_resourcetype type, S32 currently hold. SetResourceMemory takes a void* argument for the address of the resource pool. - Pass in NULL and zero bytes to reset a specific pool. + Pass in nullptr and zero bytes to reset a specific pool. Resource pool memory has certain alignment requirements - see the #defines above. If you pass in an unaligned pointer, GDraw will automatically clip off @@ -86,7 +86,7 @@ IDOC extern GDrawFunctions * gdraw_orbis_CreateContext(S32 w, S32 h, void *conte There can only be one GDraw context active at any one time. If initialization fails for some reason (the main reason would be an out of memory condition), - NULL is returned. Otherwise, you can pass the return value to IggySetGDraw. */ + nullptr is returned. Otherwise, you can pass the return value to IggySetGDraw. */ IDOC extern void gdraw_orbis_DestroyContext(void); /* Destroys the current GDraw context, if any. @@ -126,7 +126,7 @@ IDOC extern void gdraw_orbis_End(gdraw_orbis_staging_stats *staging_stats); staging_stats will be filled with stats for the staging buffer, denoting how much memory was actually used and which allocations were attempted. If you're not interested, just - pass NULL. */ + pass nullptr. */ IDOC extern void gdraw_orbis_SetTileOrigin(sce::Gnm::RenderTarget *color, sce::Gnm::DepthRenderTarget *depth, S32 x, S32 y); /* This sets the main color and depth buffers that GDraw should render to and the diff --git a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis_shaders.inl b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis_shaders.inl index fc3e31a38..00010f809 100644 --- a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis_shaders.inl +++ b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_orbis_shaders.inl @@ -517,24 +517,24 @@ static unsigned char pshader_basic_17[412] = { }; static ShaderCode pshader_basic_arr[18] = { - { pshader_basic_0, { NULL } }, - { pshader_basic_1, { NULL } }, - { pshader_basic_2, { NULL } }, - { pshader_basic_3, { NULL } }, - { pshader_basic_4, { NULL } }, - { pshader_basic_5, { NULL } }, - { pshader_basic_6, { NULL } }, - { pshader_basic_7, { NULL } }, - { pshader_basic_8, { NULL } }, - { pshader_basic_9, { NULL } }, - { pshader_basic_10, { NULL } }, - { pshader_basic_11, { NULL } }, - { pshader_basic_12, { NULL } }, - { pshader_basic_13, { NULL } }, - { pshader_basic_14, { NULL } }, - { pshader_basic_15, { NULL } }, - { pshader_basic_16, { NULL } }, - { pshader_basic_17, { NULL } }, + { pshader_basic_0, { nullptr } }, + { pshader_basic_1, { nullptr } }, + { pshader_basic_2, { nullptr } }, + { pshader_basic_3, { nullptr } }, + { pshader_basic_4, { nullptr } }, + { pshader_basic_5, { nullptr } }, + { pshader_basic_6, { nullptr } }, + { pshader_basic_7, { nullptr } }, + { pshader_basic_8, { nullptr } }, + { pshader_basic_9, { nullptr } }, + { pshader_basic_10, { nullptr } }, + { pshader_basic_11, { nullptr } }, + { pshader_basic_12, { nullptr } }, + { pshader_basic_13, { nullptr } }, + { pshader_basic_14, { nullptr } }, + { pshader_basic_15, { nullptr } }, + { pshader_basic_16, { nullptr } }, + { pshader_basic_17, { nullptr } }, }; static unsigned char pshader_exceptional_blend_1[440] = { @@ -917,19 +917,19 @@ static unsigned char pshader_exceptional_blend_12[336] = { }; static ShaderCode pshader_exceptional_blend_arr[13] = { - { NULL, { NULL } }, - { pshader_exceptional_blend_1, { NULL } }, - { pshader_exceptional_blend_2, { NULL } }, - { pshader_exceptional_blend_3, { NULL } }, - { pshader_exceptional_blend_4, { NULL } }, - { pshader_exceptional_blend_5, { NULL } }, - { pshader_exceptional_blend_6, { NULL } }, - { pshader_exceptional_blend_7, { NULL } }, - { pshader_exceptional_blend_8, { NULL } }, - { pshader_exceptional_blend_9, { NULL } }, - { pshader_exceptional_blend_10, { NULL } }, - { pshader_exceptional_blend_11, { NULL } }, - { pshader_exceptional_blend_12, { NULL } }, + { nullptr, { nullptr } }, + { pshader_exceptional_blend_1, { nullptr } }, + { pshader_exceptional_blend_2, { nullptr } }, + { pshader_exceptional_blend_3, { nullptr } }, + { pshader_exceptional_blend_4, { nullptr } }, + { pshader_exceptional_blend_5, { nullptr } }, + { pshader_exceptional_blend_6, { nullptr } }, + { pshader_exceptional_blend_7, { nullptr } }, + { pshader_exceptional_blend_8, { nullptr } }, + { pshader_exceptional_blend_9, { nullptr } }, + { pshader_exceptional_blend_10, { nullptr } }, + { pshader_exceptional_blend_11, { nullptr } }, + { pshader_exceptional_blend_12, { nullptr } }, }; static unsigned char pshader_filter_0[420] = { @@ -1685,38 +1685,38 @@ static unsigned char pshader_filter_27[412] = { }; static ShaderCode pshader_filter_arr[32] = { - { pshader_filter_0, { NULL } }, - { pshader_filter_1, { NULL } }, - { pshader_filter_2, { NULL } }, - { pshader_filter_3, { NULL } }, - { pshader_filter_4, { NULL } }, - { pshader_filter_5, { NULL } }, - { pshader_filter_6, { NULL } }, - { pshader_filter_7, { NULL } }, - { pshader_filter_8, { NULL } }, - { pshader_filter_9, { NULL } }, - { pshader_filter_10, { NULL } }, - { pshader_filter_11, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, - { pshader_filter_16, { NULL } }, - { pshader_filter_17, { NULL } }, - { pshader_filter_18, { NULL } }, - { pshader_filter_19, { NULL } }, - { pshader_filter_20, { NULL } }, - { pshader_filter_21, { NULL } }, - { pshader_filter_22, { NULL } }, - { pshader_filter_23, { NULL } }, - { pshader_filter_24, { NULL } }, - { pshader_filter_25, { NULL } }, - { pshader_filter_26, { NULL } }, - { pshader_filter_27, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, - { NULL, { NULL } }, + { pshader_filter_0, { nullptr } }, + { pshader_filter_1, { nullptr } }, + { pshader_filter_2, { nullptr } }, + { pshader_filter_3, { nullptr } }, + { pshader_filter_4, { nullptr } }, + { pshader_filter_5, { nullptr } }, + { pshader_filter_6, { nullptr } }, + { pshader_filter_7, { nullptr } }, + { pshader_filter_8, { nullptr } }, + { pshader_filter_9, { nullptr } }, + { pshader_filter_10, { nullptr } }, + { pshader_filter_11, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { pshader_filter_16, { nullptr } }, + { pshader_filter_17, { nullptr } }, + { pshader_filter_18, { nullptr } }, + { pshader_filter_19, { nullptr } }, + { pshader_filter_20, { nullptr } }, + { pshader_filter_21, { nullptr } }, + { pshader_filter_22, { nullptr } }, + { pshader_filter_23, { nullptr } }, + { pshader_filter_24, { nullptr } }, + { pshader_filter_25, { nullptr } }, + { pshader_filter_26, { nullptr } }, + { pshader_filter_27, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, }; static unsigned char pshader_blur_2[356] = { @@ -2024,16 +2024,16 @@ static unsigned char pshader_blur_9[748] = { }; static ShaderCode pshader_blur_arr[10] = { - { NULL, { NULL } }, - { NULL, { NULL } }, - { pshader_blur_2, { NULL } }, - { pshader_blur_3, { NULL } }, - { pshader_blur_4, { NULL } }, - { pshader_blur_5, { NULL } }, - { pshader_blur_6, { NULL } }, - { pshader_blur_7, { NULL } }, - { pshader_blur_8, { NULL } }, - { pshader_blur_9, { NULL } }, + { nullptr, { nullptr } }, + { nullptr, { nullptr } }, + { pshader_blur_2, { nullptr } }, + { pshader_blur_3, { nullptr } }, + { pshader_blur_4, { nullptr } }, + { pshader_blur_5, { nullptr } }, + { pshader_blur_6, { nullptr } }, + { pshader_blur_7, { nullptr } }, + { pshader_blur_8, { nullptr } }, + { pshader_blur_9, { nullptr } }, }; static unsigned char pshader_color_matrix_0[348] = { @@ -2062,7 +2062,7 @@ static unsigned char pshader_color_matrix_0[348] = { }; static ShaderCode pshader_color_matrix_arr[1] = { - { pshader_color_matrix_0, { NULL } }, + { pshader_color_matrix_0, { nullptr } }, }; static unsigned char pshader_manual_clear_0[164] = { @@ -2080,7 +2080,7 @@ static unsigned char pshader_manual_clear_0[164] = { }; static ShaderCode pshader_manual_clear_arr[1] = { - { pshader_manual_clear_0, { NULL } }, + { pshader_manual_clear_0, { nullptr } }, }; static unsigned char vshader_vsps4_0[580] = { @@ -2124,7 +2124,7 @@ static unsigned char vshader_vsps4_0[580] = { }; static ShaderCode vshader_vsps4_arr[1] = { - { vshader_vsps4_0, { NULL } }, + { vshader_vsps4_0, { nullptr } }, }; static unsigned char cshader_tex_upload_0[212] = { @@ -2145,7 +2145,7 @@ static unsigned char cshader_tex_upload_0[212] = { }; static ShaderCode cshader_tex_upload_arr[1] = { - { cshader_tex_upload_0, { NULL } }, + { cshader_tex_upload_0, { nullptr } }, }; static unsigned char cshader_memset_0[196] = { @@ -2165,7 +2165,7 @@ static unsigned char cshader_memset_0[196] = { }; static ShaderCode cshader_memset_arr[1] = { - { cshader_memset_0, { NULL } }, + { cshader_memset_0, { nullptr } }, }; static unsigned char cshader_defragment_0[204] = { @@ -2185,7 +2185,7 @@ static unsigned char cshader_defragment_0[204] = { }; static ShaderCode cshader_defragment_arr[1] = { - { cshader_defragment_0, { NULL } }, + { cshader_defragment_0, { nullptr } }, }; static unsigned char cshader_mipgen_0[340] = { @@ -2214,6 +2214,6 @@ static unsigned char cshader_mipgen_0[340] = { }; static ShaderCode cshader_mipgen_arr[1] = { - { cshader_mipgen_0, { NULL } }, + { cshader_mipgen_0, { nullptr } }, }; diff --git a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_shared.inl b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_shared.inl index a6b7dda24..1b7c1cc1e 100644 --- a/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_shared.inl +++ b/Minecraft.Client/Orbis/Iggy/gdraw/gdraw_shared.inl @@ -226,7 +226,7 @@ static void debug_check_raw_values(GDrawHandleCache *c) s = s->next; } s = c->active; - while (s != NULL) { + while (s != nullptr) { assert(s->raw_ptr != t->raw_ptr); s = s->next; } @@ -368,7 +368,7 @@ static void gdraw_HandleTransitionInsertBefore(GDrawHandle *t, GDrawHandleState { check_lists(t->cache); assert(t->state != GDRAW_HANDLE_STATE_sentinel); // sentinels should never get here! - assert(t->state != (U32) new_state); // code should never call "transition" if it's not transitioning! + assert(t->state != static_cast(new_state)); // code should never call "transition" if it's not transitioning! // unlink from prev state t->prev->next = t->next; t->next->prev = t->prev; @@ -433,7 +433,7 @@ static rrbool gdraw_HandleCacheLockStats(GDrawHandle *t, void *owner, GDrawStats static rrbool gdraw_HandleCacheLock(GDrawHandle *t, void *owner) { - return gdraw_HandleCacheLockStats(t, owner, NULL); + return gdraw_HandleCacheLockStats(t, owner, nullptr); } static void gdraw_HandleCacheUnlock(GDrawHandle *t) @@ -461,11 +461,11 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->is_thrashing = false; c->did_defragment = false; for (i=0; i < GDRAW_HANDLE_STATE__count; i++) { - c->state[i].owner = NULL; - c->state[i].cache = NULL; // should never follow cache link from sentinels! + c->state[i].owner = nullptr; + c->state[i].cache = nullptr; // should never follow cache link from sentinels! c->state[i].next = c->state[i].prev = &c->state[i]; #ifdef GDRAW_MANAGE_MEM - c->state[i].raw_ptr = NULL; + c->state[i].raw_ptr = nullptr; #endif c->state[i].fence.value = 0; c->state[i].bytes = 0; @@ -478,7 +478,7 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->handle[i].bytes = 0; c->handle[i].state = GDRAW_HANDLE_STATE_free; #ifdef GDRAW_MANAGE_MEM - c->handle[i].raw_ptr = NULL; + c->handle[i].raw_ptr = nullptr; #endif } c->state[GDRAW_HANDLE_STATE_free].next = &c->handle[0]; @@ -486,10 +486,10 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->prev_frame_start.value = 0; c->prev_frame_end.value = 0; #ifdef GDRAW_MANAGE_MEM - c->alloc = NULL; + c->alloc = nullptr; #endif #ifdef GDRAW_MANAGE_MEM_TWOPOOL - c->alloc_other = NULL; + c->alloc_other = nullptr; #endif check_lists(c); } @@ -497,14 +497,14 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte static GDrawHandle *gdraw_HandleCacheAllocateBegin(GDrawHandleCache *c) { GDrawHandle *free_list = &c->state[GDRAW_HANDLE_STATE_free]; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (free_list->next != free_list) { t = free_list->next; gdraw_HandleTransitionTo(t, GDRAW_HANDLE_STATE_alloc); t->bytes = 0; t->owner = 0; #ifdef GDRAW_MANAGE_MEM - t->raw_ptr = NULL; + t->raw_ptr = nullptr; #endif #ifdef GDRAW_CORRUPTION_CHECK t->has_check_value = false; @@ -563,7 +563,7 @@ static GDrawHandle *gdraw_HandleCacheGetLRU(GDrawHandleCache *c) // at the front of the LRU list are the oldest ones, since in-use resources // will get appended on every transition from "locked" to "live". GDrawHandle *sentinel = &c->state[GDRAW_HANDLE_STATE_live]; - return (sentinel->next != sentinel) ? sentinel->next : NULL; + return (sentinel->next != sentinel) ? sentinel->next : nullptr; } static void gdraw_HandleCacheTick(GDrawHandleCache *c, GDrawFence now) @@ -778,7 +778,7 @@ static GDrawTexture *gdraw_BlurPass(GDrawFunctions *g, GDrawBlurInfo *c, GDrawRe if (!g->TextureDrawBufferBegin(draw_bounds, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, gstats)) return r->tex[0]; - c->BlurPass(r, taps, data, draw_bounds, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, draw_bounds, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -830,7 +830,7 @@ static GDrawTexture *gdraw_BlurPassDownsample(GDrawFunctions *g, GDrawBlurInfo * assert(clamp[0] <= clamp[2]); assert(clamp[1] <= clamp[3]); - c->BlurPass(r, taps, data, &z, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, &z, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -842,7 +842,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR GDrawTexture *t; F32 data[MAX_TAPS][4]; S32 off_axis = 1-axis; - S32 w = ((S32) ceil((blur_width-1)/2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 + S32 w = static_cast(ceil((blur_width - 1) / 2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 F32 edge_weight = 1 - (w - blur_width)/2; // 3 => 0 => 1; 1.2 => 1.8 => 0.9 => 0.1 F32 inverse_weight = 1.0f / blur_width; @@ -949,7 +949,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR // max coverage is 25 samples, or a filter width of 13. with 7 taps, we sample // 13 samples in one pass, max coverage is 13*13 samples or (13*13-1)/2 width, // which is ((2T-1)*(2T-1)-1)/2 or (4T^2 - 4T + 1 -1)/2 or 2T^2 - 2T or 2T*(T-1) - S32 w_mip = (S32) ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS)); + S32 w_mip = static_cast(ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS))); S32 downsample = w_mip; F32 sample_spacing = texel; if (downsample < 2) downsample = 2; @@ -1095,7 +1095,7 @@ static void make_pool_aligned(void **start, S32 *num_bytes, U32 alignment) if (addr_aligned != addr_orig) { S32 diff = (S32) (addr_aligned - addr_orig); if (*num_bytes < diff) { - *start = NULL; + *start = nullptr; *num_bytes = 0; return; } else { @@ -1132,7 +1132,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) UINTa remaining = arena->end - arena->current; UINTa total_size = (ptr - arena->current) + size; if (remaining < total_size) // doesn't fit - return NULL; + return nullptr; arena->current = ptr + size; return ptr; @@ -1157,7 +1157,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // (i.e. block->next->prev == block->prev->next == block) // - All allocated blocks are also kept in a hash table, indexed by their // pointer (to allow free to locate the corresponding block_info quickly). -// There's a single-linked, NULL-terminated list of elements in each hash +// There's a single-linked, nullptr-terminated list of elements in each hash // bucket. // - The physical block list is ordered. It always contains all currently // active blocks and spans the whole managed memory range. There are no @@ -1166,7 +1166,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // they are coalesced immediately. // - The maximum number of blocks that could ever be necessary is allocated // on initialization. All block_infos not currently in use are kept in a -// single-linked, NULL-terminated list of unused blocks. Every block is either +// single-linked, nullptr-terminated list of unused blocks. Every block is either // in the physical block list or the unused list, and the total number of // blocks is constant. // These invariants always hold before and after an allocation/free. @@ -1384,7 +1384,7 @@ static void gfxalloc_check2(gfx_allocator *alloc) static gfx_block_info *gfxalloc_pop_unused(gfx_allocator *alloc) { - GFXALLOC_ASSERT(alloc->unused_list != NULL); + GFXALLOC_ASSERT(alloc->unused_list != nullptr); GFXALLOC_ASSERT(alloc->unused_list->is_unused); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_unused);) @@ -1457,7 +1457,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma U32 i, max_blocks, size; if (!align || (align & (align - 1)) != 0) // align must be >0 and a power of 2 - return NULL; + return nullptr; // for <= max_allocs live allocs, there's <= 2*max_allocs+1 blocks. worst case: // [free][used][free] .... [free][used][free] @@ -1465,7 +1465,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma size = sizeof(gfx_allocator) + max_blocks * sizeof(gfx_block_info); a = (gfx_allocator *) IggyGDrawMalloc(size); if (!a) - return NULL; + return nullptr; memset(a, 0, size); @@ -1506,16 +1506,16 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma a->blocks[i].is_unused = 1; gfxalloc_check(a); - debug_complete_check(a, NULL, 0,0); + debug_complete_check(a, nullptr, 0,0); return a; } static void *gfxalloc_alloc(gfx_allocator *alloc, U32 size_in_bytes) { - gfx_block_info *cur, *best = NULL; + gfx_block_info *cur, *best = nullptr; U32 i, best_wasted = ~0u; U32 size = size_in_bytes; -debug_complete_check(alloc, NULL, 0,0); +debug_complete_check(alloc, nullptr, 0,0); gfxalloc_check(alloc); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_blocks == alloc->num_alloc + alloc->num_free + alloc->num_unused);) GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_free <= alloc->num_blocks+1);) @@ -1565,7 +1565,7 @@ gfxalloc_check(alloc); debug_check_overlap(alloc->cache, best->ptr, best->size); return best->ptr; } else - return NULL; // not enough space! + return nullptr; // not enough space! } static void gfxalloc_free(gfx_allocator *alloc, void *ptr) @@ -1735,7 +1735,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta // (unused for allocated blocks, we'll use it to store a back-pointer to the corresponding handle) for (b = alloc->blocks[0].next_phys; b != alloc->blocks; b=b->next_phys) if (!b->is_free) - b->prev = NULL; + b->prev = nullptr; // go through all handles and store a pointer to the handle in the corresponding memory block for (i=0; i < c->max_handles; i++) @@ -1748,7 +1748,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta break; } - GFXALLOC_ASSERT(b != NULL); // didn't find this block anywhere! + GFXALLOC_ASSERT(b != nullptr); // didn't find this block anywhere! } // clear alloc hash table (we rebuild it during defrag) @@ -1910,7 +1910,7 @@ static rrbool gdraw_CanDefragment(GDrawHandleCache *c) static rrbool gdraw_MigrateResource(GDrawHandle *t, GDrawStats *stats) { GDrawHandleCache *c = t->cache; - void *ptr = NULL; + void *ptr = nullptr; assert(t->state == GDRAW_HANDLE_STATE_live || t->state == GDRAW_HANDLE_STATE_locked || t->state == GDRAW_HANDLE_STATE_pinned); // anything we migrate should be in the "other" (old) pool @@ -2300,7 +2300,7 @@ static void gdraw_bufring_init(gdraw_bufring * RADRESTRICT ring, void *ptr, U32 static void gdraw_bufring_shutdown(gdraw_bufring * RADRESTRICT ring) { - ring->cur = NULL; + ring->cur = nullptr; ring->seg_size = 0; } @@ -2310,7 +2310,7 @@ static void *gdraw_bufring_alloc(gdraw_bufring * RADRESTRICT ring, U32 size, U32 gdraw_bufring_seg *seg; if (size > ring->seg_size) - return NULL; // nope, won't fit + return nullptr; // nope, won't fit assert(align <= ring->align); @@ -2415,7 +2415,7 @@ static rrbool gdraw_res_free_lru(GDrawHandleCache *c, GDrawStats *stats) // was it referenced since end of previous frame (=in this frame)? // if some, we're thrashing; report it to the user, but only once per frame. if (c->prev_frame_end.value < r->fence.value && !c->is_thrashing) { - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); c->is_thrashing = true; } @@ -2435,8 +2435,8 @@ static GDrawHandle *gdraw_res_alloc_outofmem(GDrawHandleCache *c, GDrawHandle *t { if (t) gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); - return NULL; + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); + return nullptr; } #ifndef GDRAW_MANAGE_MEM @@ -2445,7 +2445,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt { GDrawHandle *t; if (size > c->total_bytes) - gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); else { // given how much data we're going to allocate, throw out // data until there's "room" (this basically lets us use @@ -2453,7 +2453,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // packing it and being exact) while (c->bytes_free < size) { if (!gdraw_res_free_lru(c, stats)) { - gdraw_res_alloc_outofmem(c, NULL, "memory"); + gdraw_res_alloc_outofmem(c, nullptr, "memory"); break; } } @@ -2468,8 +2468,8 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // we'd trade off cost of regenerating) if (gdraw_res_free_lru(c, stats)) { t = gdraw_HandleCacheAllocateBegin(c); - if (t == NULL) { - gdraw_res_alloc_outofmem(c, NULL, "handles"); + if (t == nullptr) { + gdraw_res_alloc_outofmem(c, nullptr, "handles"); } } } @@ -2513,7 +2513,7 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) { GDRAW_FENCE_FLUSH(); // dead list is sorted by fence index - make sure all fence values are current. - r->owner = NULL; + r->owner = nullptr; gdraw_HandleCacheInsertDead(r); gdraw_res_reap(r->cache, stats); } @@ -2521,11 +2521,11 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawStats *stats) { GDrawHandle *t; - void *ptr = NULL; + void *ptr = nullptr; gdraw_res_reap(c, stats); // NB this also does GDRAW_FENCE_FLUSH(); if (size > c->total_bytes) - return gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + return gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); // now try to allocate a handle t = gdraw_HandleCacheAllocateBegin(c); @@ -2537,7 +2537,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt gdraw_res_free_lru(c, stats); t = gdraw_HandleCacheAllocateBegin(c); if (!t) - return gdraw_res_alloc_outofmem(c, NULL, "handles"); + return gdraw_res_alloc_outofmem(c, nullptr, "handles"); } // try to allocate first diff --git a/Minecraft.Client/Orbis/Iggy/include/gdraw.h b/Minecraft.Client/Orbis/Iggy/include/gdraw.h index 404a2642b..7cc4ddd0e 100644 --- a/Minecraft.Client/Orbis/Iggy/include/gdraw.h +++ b/Minecraft.Client/Orbis/Iggy/include/gdraw.h @@ -356,13 +356,13 @@ IDOC typedef struct GDrawPrimitive IDOC typedef void RADLINK gdraw_draw_indexed_triangles(GDrawRenderState *r, GDrawPrimitive *prim, GDrawVertexBuffer *buf, GDrawStats *stats); /* Draws a collection of indexed triangles, ignoring special filters or blend modes. - If buf is NULL, then the pointers in 'prim' are machine pointers, and + If buf is nullptr, then the pointers in 'prim' are machine pointers, and you need to make a copy of the data (note currently all triangles implementing strokes (wide lines) go this path). - If buf is non-NULL, then use the appropriate vertex buffer, and the + If buf is non-nullptr, then use the appropriate vertex buffer, and the pointers in prim are actually offsets from the beginning of the - vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) NULL; + vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) nullptr; (note there are separate spaces for vertices and indices; e.g. the first mesh in a given vertex buffer will normally have a 0 offset for the vertices and a 0 offset for the indices) @@ -455,7 +455,7 @@ IDOC typedef GDrawTexture * RADLINK gdraw_make_texture_end(GDraw_MakeTexture_Pro /* Ends specification of a new texture. $:info The same handle initially passed to $gdraw_make_texture_begin - $:return Handle for the newly created texture, or NULL if an error occured + $:return Handle for the newly created texture, or nullptr if an error occured */ IDOC typedef rrbool RADLINK gdraw_update_texture_begin(GDrawTexture *tex, void *unique_id, GDrawStats *stats); diff --git a/Minecraft.Client/Orbis/Iggy/include/iggyexpruntime.h b/Minecraft.Client/Orbis/Iggy/include/iggyexpruntime.h index 1f1a90a1c..a42ccbfff 100644 --- a/Minecraft.Client/Orbis/Iggy/include/iggyexpruntime.h +++ b/Minecraft.Client/Orbis/Iggy/include/iggyexpruntime.h @@ -25,8 +25,8 @@ IDOC RADEXPFUNC HIGGYEXP RADEXPLINK IggyExpCreate(char *ip_address, S32 port, vo $:storage A small block of storage that needed to store the $HIGGYEXP, must be at least $IGGYEXP_MIN_STORAGE $:storage_size_in_bytes The size of the block pointer to by storage -Returns a NULL HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer -can be contacted at the specified address/port. Otherwise returns a non-NULL $HIGGYEXP +Returns a nullptr HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer +can be contacted at the specified address/port. Otherwise returns a non-nullptr $HIGGYEXP which you can pass to $IggyUseExplorer. */ IDOC RADEXPFUNC void RADEXPLINK IggyExpDestroy(HIGGYEXP p); diff --git a/Minecraft.Client/Orbis/Leaderboards/OrbisLeaderboardManager.cpp b/Minecraft.Client/Orbis/Leaderboards/OrbisLeaderboardManager.cpp index b76621970..b2492381b 100644 --- a/Minecraft.Client/Orbis/Leaderboards/OrbisLeaderboardManager.cpp +++ b/Minecraft.Client/Orbis/Leaderboards/OrbisLeaderboardManager.cpp @@ -29,7 +29,7 @@ OrbisLeaderboardManager::OrbisLeaderboardManager() m_myXUID = INVALID_XUID; - m_scores = NULL; //m_stats = NULL; + m_scores = nullptr; //m_stats = nullptr; m_statsType = eStatsType_Kills; m_difficulty = 0; @@ -41,7 +41,7 @@ OrbisLeaderboardManager::OrbisLeaderboardManager() InitializeCriticalSection(&m_csViewsLock); m_running = false; - m_threadScoreboard = NULL; + m_threadScoreboard = nullptr; } OrbisLeaderboardManager::~OrbisLeaderboardManager() @@ -181,7 +181,7 @@ bool OrbisLeaderboardManager::getScoreByIds() SceRtcTick last_sort_date; SceNpScoreRankNumber mTotalRecord; - SceNpId *npIds = NULL; + SceNpId *npIds = nullptr; int ret; @@ -267,7 +267,7 @@ bool OrbisLeaderboardManager::getScoreByIds() ZeroMemory(comments, sizeof(SceNpScoreComment) * num); /* app.DebugPrintf("sceNpScoreGetRankingByNpId(\n\t transaction=%i,\n\t boardID=0,\n\t npId=%i,\n\t friendCount*sizeof(SceNpId)=%i*%i=%i,\ - rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t NULL, 0, NULL, 0,\n\t friendCount=%i,\n...\n", + rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t nullptr, 0, nullptr, 0,\n\t friendCount=%i,\n...\n", transaction, npId, friendCount, sizeof(SceNpId), friendCount*sizeof(SceNpId), rankData, friendCount*sizeof(SceNpScorePlayerRankData), friendCount ); */ @@ -284,9 +284,9 @@ bool OrbisLeaderboardManager::getScoreByIds() sceNpScoreDestroyTransactionCtx(ret); - if (npIds != NULL) delete [] npIds; - if (ptr != NULL) delete [] ptr; - if (comments != NULL) delete [] comments; + if (npIds != nullptr) delete [] npIds; + if (ptr != nullptr) delete [] ptr; + if (comments != nullptr) delete [] comments; return false; } @@ -297,9 +297,9 @@ bool OrbisLeaderboardManager::getScoreByIds() m_eStatsState = eStatsState_Failed; - if (npIds != NULL) delete [] npIds; - if (ptr != NULL) delete [] ptr; - if (comments != NULL) delete [] comments; + if (npIds != nullptr) delete [] npIds; + if (ptr != nullptr) delete [] ptr; + if (comments != nullptr) delete [] comments; return false; } @@ -322,14 +322,14 @@ bool OrbisLeaderboardManager::getScoreByIds() batch + comments, sizeof(SceNpScoreComment) * tmpNum, //OUT: Comments - NULL, 0, // GameData. (unused) + nullptr, 0, // GameData. (unused) tmpNum, &last_sort_date, &mTotalRecord, - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -357,7 +357,7 @@ bool OrbisLeaderboardManager::getScoreByIds() m_readCount = num; // Filter scorers and construct output structure. - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_scores = new ReadScore[m_readCount]; convertToOutput(m_readCount, m_scores, ptr, comments); m_maxRank = m_readCount; @@ -390,7 +390,7 @@ error3: delete [] ptr; delete [] comments; error2: - if (npIds != NULL) delete [] npIds; + if (npIds != nullptr) delete [] npIds; error1: if (m_eStatsState != eStatsState_Canceled) m_eStatsState = eStatsState_Failed; app.DebugPrintf("[LeaderboardManger] getScoreByIds() FAILED, ret=0x%X\n", ret); @@ -443,14 +443,14 @@ bool OrbisLeaderboardManager::getScoreByRange() comments, sizeof(SceNpScoreComment) * num, //OUT: Comment Data - NULL, 0, // GameData. + nullptr, 0, // GameData. num, &last_sort_date, &m_maxRank, // 'Total number of players registered in the target scoreboard.' - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -471,7 +471,7 @@ bool OrbisLeaderboardManager::getScoreByRange() delete [] ptr; delete [] comments; - m_scores = NULL; + m_scores = nullptr; m_readCount = 0; m_eStatsState = eStatsState_Ready; @@ -489,7 +489,7 @@ bool OrbisLeaderboardManager::getScoreByRange() //m_stats = ptr; //Maybe: addPadding(num,ptr); - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_readCount = ret; m_scores = new ReadScore[m_readCount]; for (int i=0; i 0) ret = eStatsReturn_Success; - if (m_readListener != NULL) + if (m_readListener != nullptr) { app.DebugPrintf("[LeaderboardManager] OnStatsReadComplete(%i, %i, _), m_readCount=%i.\n", ret, m_maxRank, m_readCount); m_readListener->OnStatsReadComplete(ret, m_maxRank, view); @@ -636,16 +636,16 @@ void OrbisLeaderboardManager::Tick() m_eStatsState = eStatsState_Idle; delete [] m_scores; - m_scores = NULL; + m_scores = nullptr; } break; case eStatsState_Failed: { view.m_numQueries = 0; - view.m_queries = NULL; + view.m_queries = nullptr; - if ( m_readListener != NULL ) + if ( m_readListener != nullptr ) m_readListener->OnStatsReadComplete(eStatsReturn_NetworkError, 0, view); m_eStatsState = eStatsState_Idle; @@ -667,7 +667,7 @@ bool OrbisLeaderboardManager::OpenSession() { if (m_openSessions == 0) { - if (m_threadScoreboard == NULL) + if (m_threadScoreboard == nullptr) { m_threadScoreboard = new C4JThread(&scoreboardThreadEntry, this, "4JScoreboard"); m_threadScoreboard->SetProcessor(CPU_CORE_LEADERBOARDS); @@ -762,7 +762,7 @@ void OrbisLeaderboardManager::FlushStats() {} void OrbisLeaderboardManager::CancelOperation() { - m_readListener = NULL; + m_readListener = nullptr; m_eStatsState = eStatsState_Canceled; if (m_requestId != 0) @@ -912,7 +912,7 @@ void OrbisLeaderboardManager::fromBase32(void *out, SceNpScoreComment *in) for (int i = 0; i < SCE_NP_SCORE_COMMENT_MAXLEN; i++) { ch[0] = in->utf8Comment[i]; - unsigned char fivebits = strtol(ch, NULL, 32) << 3; + unsigned char fivebits = strtol(ch, nullptr, 32) << 3; int sByte = (i*5) / 8; int eByte = (5+(i*5)) / 8; @@ -973,7 +973,7 @@ bool OrbisLeaderboardManager::test_string(string testing) int ctx = sceNpScoreCreateTransactionCtx(m_titleContext); if (ctx<0) return false; - int ret = sceNpScoreCensorComment(ctx, (const char *) &comment, NULL); + int ret = sceNpScoreCensorComment(ctx, (const char *) &comment, nullptr); if (ret == SCE_NP_COMMUNITY_SERVER_ERROR_CENSORED) { diff --git a/Minecraft.Client/Orbis/Network/Orbis_NPToolkit.cpp b/Minecraft.Client/Orbis/Network/Orbis_NPToolkit.cpp index d1c9cf15f..5db367d4c 100644 --- a/Minecraft.Client/Orbis/Network/Orbis_NPToolkit.cpp +++ b/Minecraft.Client/Orbis/Network/Orbis_NPToolkit.cpp @@ -309,7 +309,7 @@ void hexStrToBin( val <<= 4; } else { - if (pBinBuf != NULL && binOffset < binBufSize) { + if (pBinBuf != nullptr && binOffset < binBufSize) { memcpy(pBinBuf + binOffset, &val, 1); val = 0; } @@ -317,7 +317,7 @@ void hexStrToBin( } } - if (val != 0 && pBinBuf != NULL && binOffset < binBufSize) { + if (val != 0 && pBinBuf != nullptr && binOffset < binBufSize) { memcpy(pBinBuf + binOffset, &val, 1); } diff --git a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp index 1b32bce2a..7c3e1a663 100644 --- a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp @@ -17,8 +17,8 @@ // #include "..\PS3Extras\PS3Strings.h" -int (* SQRNetworkManager_Orbis::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = NULL; -void * SQRNetworkManager_Orbis::s_SignInCompleteParam = NULL; +int (* SQRNetworkManager_Orbis::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = nullptr; +void * SQRNetworkManager_Orbis::s_SignInCompleteParam = nullptr; sce::Toolkit::NP::PresenceDetails SQRNetworkManager_Orbis::s_lastPresenceInfo; int64_t SQRNetworkManager_Orbis::s_lastPresenceTime = 0; @@ -109,8 +109,8 @@ SQRNetworkManager_Orbis::SQRNetworkManager_Orbis(ISQRNetworkManagerListener *lis m_isInSession = false; m_offlineGame = false; m_offlineSQR = false; - m_aServerId = NULL; - m_gameBootInvite = NULL; + m_aServerId = nullptr; + m_gameBootInvite = nullptr; m_onlineStatus = false; m_bLinkDisconnected = false; m_bRefreshingRestrictionsForInvite = false; @@ -137,7 +137,7 @@ void SQRNetworkManager_Orbis::Initialise() int32_t ret = 0; int32_t libCtxId = 0; - ret = sceNpInGameMessageInitialize(NP_IN_GAME_MESSAGE_POOL_SIZE, NULL); + ret = sceNpInGameMessageInitialize(NP_IN_GAME_MESSAGE_POOL_SIZE, nullptr); assert (ret >= 0); libCtxId = ret; @@ -251,7 +251,7 @@ void SQRNetworkManager_Orbis::InitialiseAfterOnline() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,s_SignInCompleteCallbackPad); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; s_SignInCompleteCallbackPad = -1; } return; @@ -334,7 +334,7 @@ void SQRNetworkManager_Orbis::RefreshChatAndContentRestrictionsReturned_HandleIn SQRNetworkManager_Orbis *netMan = (SQRNetworkManager_Orbis *)pParam; netMan->m_listener->HandleInviteReceived( ProfileManager.GetPrimaryPad(), netMan->m_gameBootInvite ); - netMan->m_gameBootInvite = NULL; + netMan->m_gameBootInvite = nullptr; netMan->m_bRefreshingRestrictionsForInvite = false; } @@ -357,7 +357,7 @@ void SQRNetworkManager_Orbis::Tick() m_bRefreshingRestrictionsForInvite = true; ProfileManager.RefreshChatAndContentRestrictions(RefreshChatAndContentRestrictionsReturned_HandleInvite, this); //m_listener->HandleInviteReceived( ProfileManager.GetPrimaryPad(), m_gameBootInvite ); - //m_gameBootInvite = NULL; + //m_gameBootInvite = nullptr; } ErrorHandlingTick(); @@ -431,14 +431,14 @@ void SQRNetworkManager_Orbis::Tick() if(s_SignInCompleteCallbackFn) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,s_SignInCompleteCallbackPad); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } s_SignInCompleteCallbackPad = -1; } else if(s_SignInCompleteCallbackFn) { s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, s_SignInCompleteCallbackPad); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; s_SignInCompleteCallbackPad = -1; } } @@ -539,7 +539,7 @@ void SQRNetworkManager_Orbis::ErrorHandlingTick() m_bCallPSNSignInCallback=true; //s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,s_SignInCompleteCallbackPad); } - //s_SignInCompleteCallbackFn = NULL; + //s_SignInCompleteCallbackFn = nullptr; //s_SignInCompleteCallbackPad = -1; } app.DebugPrintf("Network error: SNM_INT_STATE_INITIALISE_FAILED\n"); @@ -655,7 +655,7 @@ void SQRNetworkManager_Orbis::UpdateExternalRoomData() reqParam.roomBinAttrExternalNum = 1; reqParam.roomBinAttrExternal = &roomBinAttr; - int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SetRoomDataExternal returns 0x%x, number of players %d\n",ret,((char *)m_joinExtData)[174]); if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA ) ) { @@ -685,11 +685,11 @@ bool SQRNetworkManager_Orbis::FriendRoomManagerSearch() } // Free up any external data that we received from the previous search - for( int i = 0; i < m_aFriendSearchResults.size(); i++ ) + for( size_t i = 0; i < m_aFriendSearchResults.size(); i++ ) { if(m_aFriendSearchResults[i].m_RoomExtDataReceived) free(m_aFriendSearchResults[i].m_RoomExtDataReceived); - m_aFriendSearchResults[i].m_RoomExtDataReceived = NULL; + m_aFriendSearchResults[i].m_RoomExtDataReceived = nullptr; } m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT; @@ -755,7 +755,7 @@ void SQRNetworkManager_Orbis::FriendSearchTick() { m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO; delete m_getFriendCountThread; - m_getFriendCountThread = NULL; + m_getFriendCountThread = nullptr; FriendRoomManagerSearch2(); } } @@ -773,7 +773,7 @@ int SQRNetworkManager_Orbis::BasicEventThreadProc( void *lpParameter ) do { - ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); + ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, nullptr); // 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 ) @@ -979,7 +979,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerByIndex(int idx) } else { - return NULL; + return nullptr; } } @@ -996,7 +996,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerBySmallId(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerByXuid(PlayerUID xuid) @@ -1012,7 +1012,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerByXuid(PlayerUID xuid) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_Orbis::GetLocalPlayerByUserIndex(int idx) @@ -1028,7 +1028,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetLocalPlayerByUserIndex(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_Orbis::GetHostPlayer() @@ -1041,11 +1041,11 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetHostPlayer() SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerIfReady(SQRNetworkPlayer *player) { - if( player == NULL ) return NULL; + if( player == nullptr ) return nullptr; if( player->IsReady() ) return player; - return NULL; + return nullptr; } // Update state internally @@ -1099,7 +1099,7 @@ bool SQRNetworkManager_Orbis::JoinRoom(SQRNetworkManager_Orbis::SessionSearchRes { // Set up the presence info we would like to synchronise out when we have fully joined the game CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData(&s_lastPresenceSyncInfo, searchResult->m_extData, searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId); - return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, NULL); + return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, nullptr); } // Join room with a specified roomId. This is used when joining from an invite, as well as by the previous method @@ -1165,7 +1165,7 @@ void SQRNetworkManager_Orbis::LeaveRoom(bool bActuallyLeaveRoom) reqParam.roomId = m_room; SetState(SNM_INT_STATE_LEAVING); - int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, NULL, &m_leaveRoomRequestId ); + int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, nullptr, &m_leaveRoomRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_LEAVE_ROOM) ) { SetState(SNM_INT_STATE_LEAVING_FAILED); @@ -1274,7 +1274,7 @@ bool SQRNetworkManager_Orbis::AddLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL) ) { @@ -1326,7 +1326,7 @@ bool SQRNetworkManager_Orbis::RemoveLocalPlayerByUserIndex(int idx) // And do any adjusting necessary to the mappings from this room data, to the SQRNetworkPlayers. // This will also delete the SQRNetworkPlayer and do all the callbacks that requires etc. MapRoomSlotPlayers(roomSlotPlayerCount); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; // Sync this back out to our networked clients... SyncRoomData(); @@ -1367,7 +1367,7 @@ bool SQRNetworkManager_Orbis::RemoveLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2) ) { @@ -1388,7 +1388,7 @@ void SQRNetworkManager_Orbis::UpdateRemotePlay() int localPlayerCount = 0; for(int i = 0; i < XUSER_MAX_COUNT; i++) { - if(GetLocalPlayerByUserIndex(i) != NULL) localPlayerCount++; + if(GetLocalPlayerByUserIndex(i) != nullptr) localPlayerCount++; } InputManager.SetLocalMultiplayer(localPlayerCount > 1); } @@ -1427,7 +1427,7 @@ void SQRNetworkManager_Orbis::SendInviteGUI() messData.body.assign(body); 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.npIds = nullptr; messData.userInfo.userId = userId; // Set expire to maximum @@ -1602,7 +1602,7 @@ void SQRNetworkManager_Orbis::FindOrCreateNonNetworkPlayer(int slot, int playerT } } // Create the player - non-network players can be considered complete as soon as we create them as we aren't waiting on their network connections becoming complete, so can flag them as such and notify via callback - PlayerUID *pUID = NULL; + PlayerUID *pUID = nullptr; PlayerUID localUID; if( ( playerType == SQRNetworkPlayer::SNP_TYPE_LOCAL ) || (m_isHosting && ( playerType == SQRNetworkPlayer::SNP_TYPE_HOST )) ) @@ -1669,7 +1669,7 @@ void SQRNetworkManager_Orbis::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_REMOTE ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1725,7 +1725,7 @@ void SQRNetworkManager_Orbis::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_LOCAL ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1817,7 +1817,7 @@ void SQRNetworkManager_Orbis::UpdatePlayersFromRoomSyncUIDs() } // Host only - add remote players to our internal storage of player slots, and synchronise this with other room members. -bool SQRNetworkManager_Orbis::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==NULL*/ ) +bool SQRNetworkManager_Orbis::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==nullptr*/ ) { assert( m_isHosting ); @@ -1939,7 +1939,7 @@ void SQRNetworkManager_Orbis::RemoveRemotePlayersAndSync( SceNpMatching2RoomMemb } // Zero last element, that isn't part of the currently sized array anymore memset(&m_roomSyncData.players[m_roomSyncData.getPlayerCount()],0,sizeof(PlayerSyncData)); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; } else { @@ -1984,7 +1984,7 @@ void SQRNetworkManager_Orbis::RemoveNetworkPlayers( int mask ) { if( m_aRoomSlotPlayers[i] == player ) { - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } // And delete the reference from the ctx->player map @@ -2037,7 +2037,7 @@ void SQRNetworkManager_Orbis::SyncRoomData() roomBinAttr.size = sizeof( m_roomSyncData ); reqParam.roomBinAttrInternalNum = 1; reqParam.roomBinAttrInternal = &roomBinAttr; - sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); } // Check if the matching context is valid, and if not attempt to create one. If to do this requires starting an asynchronous process, then sets the internal state to the state passed in @@ -2159,7 +2159,7 @@ bool SQRNetworkManager_Orbis::GetServerContext(SceNpMatching2ServerId serverId) // { // // Get list of server IDs of servers allocated to the application. We don't actually need to do this, but it is as good a way as any to try a matching2 service and check that // // the context *really* is valid. -// int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, NULL, 0 ); +// int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, nullptr, 0 ); // // If an error is returned here, we need to destroy and recerate our server - if this goes ok we should come back through this path again // if( ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_UNAVAILABLE ) || // This error has been seen (occasionally) in a normal working environment // ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error @@ -2253,7 +2253,7 @@ void SQRNetworkManager_Orbis::RoomCreateTick() SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_CREATING_ROOM); app.DebugPrintf(CMinecraftApp::USER_RR,">> Creating room start\n"); s_roomStartTime = System::currentTimeMillis(); - int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, NULL, &m_createRoomRequestId ); + int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, nullptr, &m_createRoomRequestId ); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_JOIN_ROOM) ) { SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED); @@ -2493,7 +2493,7 @@ bool SQRNetworkManager_Orbis::CreateVoiceRudpConnections(SceNpMatching2RoomId ro // create this connection if we don't have it already SQRVoiceConnection* pConnection = SonyVoiceChat_Orbis::getVoiceConnectionFromRoomMemberID(peerMemberId); - if(pConnection == NULL) + if(pConnection == nullptr) { // Create an Rudp context for the voice connection, this will happen regardless of whether the peer is client or host @@ -2573,7 +2573,7 @@ bool SQRNetworkManager_Orbis::CreateRudpConnections(SceNpMatching2RoomId roomId, if( m_isHosting ) { - m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, NULL ); + m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, nullptr ); } else { @@ -2611,7 +2611,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerFromRudpCtx(int rudpCtx) { return it->second; } - return NULL; + return nullptr; } @@ -2625,7 +2625,7 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerFromRoomMemberAndLocalIdx(in return it->second; } } - return NULL; + return nullptr; } @@ -2720,7 +2720,7 @@ void SQRNetworkManager_Orbis::ContextCallback(SceNpMatching2ContextId id, SceNp if( manager->m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { manager->SetState( SNM_INT_STATE_IDLE ); - manager->GetExtDataForRoom(0, NULL, NULL, NULL); + manager->GetExtDataForRoom(0, nullptr, nullptr, nullptr); break; } @@ -2759,7 +2759,7 @@ void SQRNetworkManager_Orbis::ContextCallback(SceNpMatching2ContextId id, SceNp // if(s_SignInCompleteCallbackFn) // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } @@ -2966,12 +2966,12 @@ void SQRNetworkManager_Orbis::DefaultRequestCallback(SceNpMatching2ContextId id, // Set flag to indicate whether we were kicked for being out of room or not reqParam.optData.data[0] = isFull ? 1 : 0; reqParam.optData.len = 1; - int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, NULL, &manager->m_kickRequestId); + int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, nullptr, &manager->m_kickRequestId); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2KickoutRoomMember returns error 0x%x\n",ret); } else { - if(pRoomMemberData->roomMemberDataInternal->roomMemberBinAttrInternal->data.ptr == NULL) + if(pRoomMemberData->roomMemberDataInternal->roomMemberBinAttrInternal->data.ptr == nullptr) { // the host doesn't send out data, so this must be the host we're connecting to @@ -3213,7 +3213,7 @@ void SQRNetworkManager_Orbis::RoomEventCallback(SceNpMatching2ContextId id, SceN reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, NULL, &manager->m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, nullptr, &manager->m_setRoomMemberInternalDataRequestId ); } else { @@ -3349,7 +3349,7 @@ void SQRNetworkManager_Orbis::ProcessSignallingEvent(SceNpMatching2ContextId ctx reqParam.attrId = attrs; reqParam.attrIdNum = 1; - sceNpMatching2GetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_roomMemberDataRequestId); + sceNpMatching2GetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_roomMemberDataRequestId); } break; } @@ -3358,7 +3358,7 @@ void SQRNetworkManager_Orbis::ProcessSignallingEvent(SceNpMatching2ContextId ctx void SQRNetworkManager_Orbis::SignallingEventsTick() { EnterCriticalSection(&m_signallingEventListCS); - for(int i=0;i= sizeof(SQRNetworkPlayer::InitSendData) ) { SQRNetworkPlayer::InitSendData ISD; - int bytesRead = sceRudpRead( ctx_id, &ISD, sizeof(SQRNetworkPlayer::InitSendData), 0, NULL ); + int bytesRead = sceRudpRead( ctx_id, &ISD, sizeof(SQRNetworkPlayer::InitSendData), 0, nullptr ); if( bytesRead == sizeof(SQRNetworkPlayer::InitSendData) ) { manager->NetworkPlayerInitialDataReceived(playerFrom, &ISD); @@ -3555,7 +3555,7 @@ void SQRNetworkManager_Orbis::RudpContextCallback(int ctx_id, int event_id, int if( dataSize > 0 ) { unsigned char *data = new unsigned char [ dataSize ]; - int bytesRead = sceRudpRead( ctx_id, data, dataSize, 0, NULL ); + int bytesRead = sceRudpRead( ctx_id, data, dataSize, 0, nullptr ); if( bytesRead > 0 ) { SQRNetworkPlayer *playerFrom, *playerTo; @@ -3571,7 +3571,7 @@ void SQRNetworkManager_Orbis::RudpContextCallback(int ctx_id, int event_id, int playerFrom = manager->m_aRoomSlotPlayers[0]; playerTo = manager->GetPlayerFromRudpCtx( ctx_id ); } - if( ( playerFrom != NULL ) && ( playerTo != NULL ) ) + if( ( playerFrom != nullptr ) && ( playerTo != nullptr ) ) { manager->m_listener->HandleDataReceived( playerFrom, playerTo, data, bytesRead ); } @@ -3632,7 +3632,7 @@ void SQRNetworkManager_Orbis::ServerContextValid_CreateRoom() int ret = -1; if( !ForceErrorPoint(SNM_FORCE_ERROR_GET_WORLD_INFO_LIST) ) { - ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, NULL, &m_getWorldRequestId); + ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, nullptr, &m_getWorldRequestId); } if (ret < 0) { @@ -3661,7 +3661,7 @@ void SQRNetworkManager_Orbis::ServerContextValid_JoinRoom() reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, NULL, &m_joinRoomRequestId ); + int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, nullptr, &m_joinRoomRequestId ); if ( (ret < 0) || ForceErrorPoint(SNM_FORCE_ERROR_JOIN_ROOM) ) { if( ret == SCE_NP_MATCHING2_SERVER_ERROR_NAT_TYPE_MISMATCH) @@ -3722,9 +3722,9 @@ void SQRNetworkManager_Orbis::GetExtDataForRoom( SceNpMatching2RoomId roomId, vo static SceNpMatching2RoomId aRoomId[1]; static SceNpMatching2AttributeId attr[1]; - // All parameters will be NULL if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). - // NULL parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList - if( extData != NULL ) + // All parameters will be nullptr if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). + // nullptr parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList + if( extData != nullptr ) { aRoomId[0] = roomId; attr[0] = SCE_NP_MATCHING2_ROOM_BIN_ATTR_EXTERNAL_1_ID; @@ -3748,14 +3748,14 @@ void SQRNetworkManager_Orbis::GetExtDataForRoom( SceNpMatching2RoomId roomId, vo return; } - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { app.DebugPrintf("Having to recreate matching context, setting state to SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT\n"); return; } - int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, NULL, &m_roomDataExternalListRequestId ); + int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, nullptr, &m_roomDataExternalListRequestId ); // If we hadn't properly detected that a matching context was unvailable, we might still get an error indicating that it is from the previous call. Handle similarly, but we need // to destroy the context first. @@ -3769,7 +3769,7 @@ void SQRNetworkManager_Orbis::GetExtDataForRoom( SceNpMatching2RoomId roomId, vo m_FriendSessionUpdatedFn(false, m_pParamFriendSessionUpdated); return; }; - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { return; @@ -3907,7 +3907,7 @@ void SQRNetworkManager_Orbis::AttemptPSNSignIn(int (*SignInCompleteCallbackFn)(v //s_signInCompleteCallbackIfFailed=false; //s_SignInCompleteCallbackFn(s_SignInCompleteParam, false, iPad); } - //s_SignInCompleteCallbackFn = NULL; + //s_SignInCompleteCallbackFn = nullptr; } } } @@ -4145,11 +4145,11 @@ void SQRNetworkManager_Orbis::NotifyRealtimePlusFeature(int iQuadrant) // bool isSignedIn = ProfileManager.IsSignedInLive(s_SignInCompleteCallbackPad); // // s_SignInCompleteCallbackFn(s_SignInCompleteParam, isSignedIn, s_SignInCompleteCallbackPad); -// s_SignInCompleteCallbackFn = NULL; +// s_SignInCompleteCallbackFn = nullptr; // s_SignInCompleteCallbackPad = -1; // } // else // { -// app.DebugPrintf("============ Calling CallSignInCompleteCallback but s_SignInCompleteCallbackFn is NULL\n"); +// app.DebugPrintf("============ Calling CallSignInCompleteCallback but s_SignInCompleteCallbackFn is nullptr\n"); // } //} \ No newline at end of file diff --git a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.h b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.h index cb7cafa94..0217e4c55 100644 --- a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.h +++ b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.h @@ -139,7 +139,7 @@ private: void LocalDataSend(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, const void *data, unsigned int dataSize); int GetSessionIndex(SQRNetworkPlayer *player); - bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = NULL ); + bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = nullptr ); void RemoveRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int mask ); void RemoveNetworkPlayers( int mask ); void SetLocalPlayersAndSync(); diff --git a/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.cpp b/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.cpp index 34ab67e40..67ae639bc 100644 --- a/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.cpp @@ -9,22 +9,22 @@ bool SonyCommerce_Orbis::m_bCommerceInitialised = false; // SceNpCommerce2SessionInfo SonyCommerce_Orbis::m_sessionInfo; SonyCommerce_Orbis::State SonyCommerce_Orbis::m_state = e_state_noSession; int SonyCommerce_Orbis::m_errorCode = 0; -LPVOID SonyCommerce_Orbis::m_callbackParam = NULL; +LPVOID SonyCommerce_Orbis::m_callbackParam = nullptr; -void* SonyCommerce_Orbis::m_receiveBuffer = NULL; +void* SonyCommerce_Orbis::m_receiveBuffer = nullptr; SonyCommerce_Orbis::Event SonyCommerce_Orbis::m_event; std::queue SonyCommerce_Orbis::m_messageQueue; -std::vector* SonyCommerce_Orbis::m_pProductInfoList = NULL; -SonyCommerce_Orbis::ProductInfoDetailed* SonyCommerce_Orbis::m_pProductInfoDetailed = NULL; -SonyCommerce_Orbis::ProductInfo* SonyCommerce_Orbis::m_pProductInfo = NULL; +std::vector* SonyCommerce_Orbis::m_pProductInfoList = nullptr; +SonyCommerce_Orbis::ProductInfoDetailed* SonyCommerce_Orbis::m_pProductInfoDetailed = nullptr; +SonyCommerce_Orbis::ProductInfo* SonyCommerce_Orbis::m_pProductInfo = nullptr; -SonyCommerce_Orbis::CategoryInfo* SonyCommerce_Orbis::m_pCategoryInfo = NULL; -const char* SonyCommerce_Orbis::m_pProductID = NULL; -char* SonyCommerce_Orbis::m_pCategoryID = NULL; +SonyCommerce_Orbis::CategoryInfo* SonyCommerce_Orbis::m_pCategoryInfo = nullptr; +const char* SonyCommerce_Orbis::m_pProductID = nullptr; +char* SonyCommerce_Orbis::m_pCategoryID = nullptr; SonyCommerce_Orbis::CheckoutInputParams SonyCommerce_Orbis::m_checkoutInputParams; SonyCommerce_Orbis::DownloadListInputParams SonyCommerce_Orbis::m_downloadInputParams; -SonyCommerce_Orbis::CallbackFunc SonyCommerce_Orbis::m_callbackFunc = NULL; +SonyCommerce_Orbis::CallbackFunc SonyCommerce_Orbis::m_callbackFunc = nullptr; // sys_memory_container_t SonyCommerce_Orbis::m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; bool SonyCommerce_Orbis::m_bUpgradingTrial = false; @@ -38,7 +38,7 @@ bool SonyCommerce_Orbis::m_contextCreated=false; ///< npcommerce2 cont SonyCommerce_Orbis::Phase SonyCommerce_Orbis::m_currentPhase = e_phase_stopped; ///< Current commerce2 util // char SonyCommerce_Orbis::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; -C4JThread* SonyCommerce_Orbis::m_tickThread = NULL; +C4JThread* SonyCommerce_Orbis::m_tickThread = nullptr; bool SonyCommerce_Orbis::m_bLicenseChecked=false; // Check the trial/full license for the game @@ -52,12 +52,12 @@ sce::Toolkit::NP::Utilities::Future g_d SonyCommerce_Orbis::ProductInfoDetailed s_trialUpgradeProductInfoDetailed; void SonyCommerce_Orbis::Delete() { - m_pProductInfoList=NULL; - m_pProductInfoDetailed=NULL; - m_pProductInfo=NULL; - m_pCategoryInfo = NULL; - m_pProductID = NULL; - m_pCategoryID = NULL; + m_pProductInfoList=nullptr; + m_pProductInfoDetailed=nullptr; + m_pProductInfo=nullptr; + m_pCategoryInfo = nullptr; + m_pProductID = nullptr; + m_pCategoryID = nullptr; } void SonyCommerce_Orbis::Init() @@ -95,7 +95,7 @@ bool SonyCommerce_Orbis::LicenseChecked() void SonyCommerce_Orbis::CheckForTrialUpgradeKey() { - StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, NULL); + StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, nullptr); } int SonyCommerce_Orbis::Shutdown() @@ -112,7 +112,7 @@ int SonyCommerce_Orbis::Shutdown() DeleteCriticalSection(&m_queueLock); // clear any possible callback function - m_callbackFunc = NULL; + m_callbackFunc = nullptr; return ret; } @@ -582,7 +582,7 @@ int SonyCommerce_Orbis::createContext() // } // // // Create commerce2 context -// ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, NULL, &m_contextId); +// ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, nullptr, &m_contextId); // if (ret < 0) // { // app.DebugPrintf(4,"createContext sceNpCommerce2CreateCtx problem\n"); @@ -657,7 +657,7 @@ void SonyCommerce_Orbis::commerce2Handler( const sce::Toolkit::NP::Event& event) case sce::Toolkit::NP::Event::UserEvent::commerceGotCategoryInfo: { copyCategoryInfo(m_pCategoryInfo, g_categoryInfo.get()); - m_pCategoryInfo = NULL; + m_pCategoryInfo = nullptr; m_event = e_event_commerceGotCategoryInfo; break; } @@ -665,7 +665,7 @@ void SonyCommerce_Orbis::commerce2Handler( const sce::Toolkit::NP::Event& event) case sce::Toolkit::NP::Event::UserEvent::commerceGotProductList: { copyProductList(m_pProductInfoList, g_productList.get()); - m_pProductInfoDetailed = NULL; + m_pProductInfoDetailed = nullptr; m_event = e_event_commerceGotProductList; break; } @@ -675,12 +675,12 @@ void SonyCommerce_Orbis::commerce2Handler( const sce::Toolkit::NP::Event& event) if(m_pProductInfoDetailed) { copyDetailedProductInfo(m_pProductInfoDetailed, g_detailedProductInfo.get()); - m_pProductInfoDetailed = NULL; + m_pProductInfoDetailed = nullptr; } else { copyAddDetailedProductInfo(m_pProductInfo, g_detailedProductInfo.get()); - m_pProductInfo = NULL; + m_pProductInfo = nullptr; } m_event = e_event_commerceGotDetailedProductInfo; break; @@ -1027,7 +1027,7 @@ void SonyCommerce_Orbis::processEvent() case e_event_commerceProductBrowseFinished: app.DebugPrintf(4,"e_event_commerceProductBrowseFinished succeeded: 0x%x\n", m_errorCode); - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1076,7 +1076,7 @@ void SonyCommerce_Orbis::processEvent() } // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1094,7 +1094,7 @@ void SonyCommerce_Orbis::processEvent() } // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1154,8 +1154,8 @@ void SonyCommerce_Orbis::CreateSession( CallbackFunc cb, LPVOID lpParam ) m_messageQueue.push(e_message_commerceEnd); m_event = e_event_commerceSessionCreated; - if(m_tickThread == NULL) - m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce_Orbis tick"); + if(m_tickThread == nullptr) + m_tickThread = new C4JThread(TickLoop, nullptr, "SonyCommerce_Orbis tick"); if(m_tickThread->isRunning() == false) { m_currentPhase = e_phase_idle; diff --git a/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.h b/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.h index a2a42d574..dc7671f46 100644 --- a/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.h +++ b/Minecraft.Client/Orbis/Network/SonyCommerce_Orbis.h @@ -107,14 +107,14 @@ class SonyCommerce_Orbis : public SonyCommerce { assert(m_callbackFunc); CallbackFunc func = m_callbackFunc; - m_callbackFunc = NULL; + m_callbackFunc = nullptr; if(func) func(m_callbackParam, m_errorCode); m_errorCode = SCE_OK; } static void setCallback(CallbackFunc cb,LPVOID lpParam) { - assert(m_callbackFunc == NULL); + assert(m_callbackFunc == nullptr); m_callbackFunc = cb; m_callbackParam = lpParam; } diff --git a/Minecraft.Client/Orbis/Network/SonyHttp_Orbis.cpp b/Minecraft.Client/Orbis/Network/SonyHttp_Orbis.cpp index 7f7c62d68..3387839fd 100644 --- a/Minecraft.Client/Orbis/Network/SonyHttp_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SonyHttp_Orbis.cpp @@ -100,16 +100,16 @@ void SonyHttp_Orbis::printSslError(SceInt32 sslErr, SceUInt32 sslErrDetail) void SonyHttp_Orbis::printSslCertInfo(int libsslCtxId,SceSslCert *sslCert) { SceInt32 ret; - SceUChar8 *sboData = NULL ; + SceUChar8 *sboData = nullptr ; SceSize sboLen, counter; - ret = sceSslGetSerialNumber(libsslCtxId, sslCert, NULL, &sboLen); + ret = sceSslGetSerialNumber(libsslCtxId, sslCert, nullptr, &sboLen); if (ret < 0){ app.DebugPrintf("sceSslGetSerialNumber() returns 0x%x\n", ret); } else { - sboData = (SceUChar8*)malloc(sboLen); - if ( sboData != NULL ) { + sboData = static_cast(malloc(sboLen)); + if ( sboData != nullptr ) { ret = sceSslGetSerialNumber(libsslCtxId, sslCert, sboData, &sboLen); if (ret < 0){ app.DebugPrintf ("sceSslGetSerialNumber() returns 0x%x\n", ret); @@ -141,10 +141,10 @@ SceInt32 SonyHttp_Orbis::sslCallback(int libsslCtxId,unsigned int verifyErr,SceS (void)userArg; app.DebugPrintf("Ssl callback:\n"); - app.DebugPrintf("\tbase tmpl[%x]\n", (*(SceInt32*)(userArg)) ); + app.DebugPrintf("\tbase tmpl[%x]\n", (*static_cast(userArg)) ); if (verifyErr != 0){ - printSslError((SceInt32)SCE_HTTPS_ERROR_CERT, verifyErr); + printSslError(static_cast(SCE_HTTPS_ERROR_CERT), verifyErr); } for (i = 0; i < certNum; i++){ printSslCertInfo(libsslCtxId,sslCert[i]); @@ -202,7 +202,7 @@ bool SonyHttp_Orbis::http_get(const char *targetUrl, void** ppOutData, int* pDat } /* Register SSL callback */ - ret = sceHttpsSetSslCallback(tmplId, sslCallback, (void*)&tmplId); + ret = sceHttpsSetSslCallback(tmplId, sslCallback, static_cast(&tmplId)); if (ret < 0) { app.DebugPrintf("sceHttpsSetSslCallback() error: 0x%08X\n", ret); @@ -225,7 +225,7 @@ bool SonyHttp_Orbis::http_get(const char *targetUrl, void** ppOutData, int* pDat } reqId = ret; - ret = sceHttpSendRequest(reqId, NULL, 0); + ret = sceHttpSendRequest(reqId, nullptr, 0); if (ret < 0) { app.DebugPrintf("sceHttpSendRequest() error: 0x%08X\n", ret); diff --git a/Minecraft.Client/Orbis/Network/SonyRemoteStorage_Orbis.cpp b/Minecraft.Client/Orbis/Network/SonyRemoteStorage_Orbis.cpp index e248f602c..008879cb3 100644 --- a/Minecraft.Client/Orbis/Network/SonyRemoteStorage_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SonyRemoteStorage_Orbis.cpp @@ -26,7 +26,7 @@ static SceRemoteStorageData s_getDataOutput; void SonyRemoteStorage_Orbis::staticInternalCallback(const SceRemoteStorageEvent event, int32_t retCode, void * userData) { - ((SonyRemoteStorage_Orbis*)userData)->internalCallback(event, retCode); + static_cast(userData)->internalCallback(event, retCode); } void SonyRemoteStorage_Orbis::internalCallback(const SceRemoteStorageEvent event, int32_t retCode) { @@ -196,7 +196,7 @@ bool SonyRemoteStorage_Orbis::init(CallbackFunc cb, LPVOID lpParam) // memcpy(clientId.id, CLIENT_ID, strlen(CLIENT_ID)); // authParams.pClientId = &clientId; -// ret = sceNpAuthGetAuthorizationCode(reqId, &authParams, &authCode, NULL); +// ret = sceNpAuthGetAuthorizationCode(reqId, &authParams, &authCode, nullptr); // if (ret < 0) { // app.DebugPrintf("Failed to get auth code 0x%x\n", ret); // } @@ -223,7 +223,7 @@ bool SonyRemoteStorage_Orbis::init(CallbackFunc cb, LPVOID lpParam) params.timeout.sendMs = 120 * 1000; //120 seconds is the default params.pool.memPoolSize = 7 * 1024 * 1024; - if(m_memPoolBuffer == NULL) + if(m_memPoolBuffer == nullptr) m_memPoolBuffer = malloc(params.pool.memPoolSize); params.pool.memPoolBuffer = m_memPoolBuffer; diff --git a/Minecraft.Client/Orbis/Network/SonyVoiceChat_Orbis.cpp b/Minecraft.Client/Orbis/Network/SonyVoiceChat_Orbis.cpp index d869d38bf..c075badb6 100644 --- a/Minecraft.Client/Orbis/Network/SonyVoiceChat_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SonyVoiceChat_Orbis.cpp @@ -67,7 +67,7 @@ void LoadPCMVoiceData() { char filename[64]; sprintf(filename, "voice%d.pcm", i+1); - HANDLE file = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(filename, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); DWORD dwHigh=0; g_loadedPCMVoiceDataSizes[i] = GetFileSize(file,&dwHigh); @@ -75,7 +75,7 @@ void LoadPCMVoiceData() { g_loadedPCMVoiceData[i] = new char[g_loadedPCMVoiceDataSizes[i]]; DWORD bytesRead; - BOOL bSuccess = ReadFile(file, g_loadedPCMVoiceData[i], g_loadedPCMVoiceDataSizes[i], &bytesRead, NULL); + BOOL bSuccess = ReadFile(file, g_loadedPCMVoiceData[i], g_loadedPCMVoiceDataSizes[i], &bytesRead, nullptr); assert(bSuccess); } g_loadedPCMVoiceDataPos[i] = 0; @@ -274,7 +274,7 @@ void SQRVoiceConnection::readRemoteData() if( dataSize > 0 ) { VoicePacket packet; - int bytesRead = sceRudpRead( m_rudpCtx, &packet, dataSize, 0, NULL ); + int bytesRead = sceRudpRead( m_rudpCtx, &packet, dataSize, 0, nullptr ); unsigned int writeSize; if( bytesRead > 0 ) { @@ -468,7 +468,7 @@ void SonyVoiceChat_Orbis::sendAllVoiceData() if(m_localVoiceDevices[i].isValid()) { bool bChatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,true,&bChatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(i,true,&bChatRestricted,nullptr,nullptr); if(bChatRestricted) { @@ -928,7 +928,7 @@ void SonyVoiceChat_Orbis::initLocalPlayer(int playerIndex) if(m_localVoiceDevices[playerIndex].isValid() == false) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); // create all device ports required m_localVoiceDevices[playerIndex].init(ProfileManager.getUserID(playerIndex), chatRestricted); @@ -965,7 +965,7 @@ SQRVoiceConnection* SonyVoiceChat_Orbis::GetVoiceConnectionFromRudpCtx( int Rudp if(m_remoteConnections[i]->m_rudpCtx == RudpCtx) return m_remoteConnections[i]; } - return NULL; + return nullptr; } void SonyVoiceChat_Orbis::connectPlayerToAll( int playerIndex ) @@ -990,7 +990,7 @@ SQRVoiceConnection* SonyVoiceChat_Orbis::getVoiceConnectionFromRoomMemberID( Sce } } - return NULL; + return nullptr; } void SonyVoiceChat_Orbis::disconnectLocalPlayer( int localIdx ) diff --git a/Minecraft.Client/Orbis/OrbisExtras/OrbisStubs.cpp b/Minecraft.Client/Orbis/OrbisExtras/OrbisStubs.cpp index 661a15284..21e73a80c 100644 --- a/Minecraft.Client/Orbis/OrbisExtras/OrbisStubs.cpp +++ b/Minecraft.Client/Orbis/OrbisExtras/OrbisStubs.cpp @@ -34,7 +34,7 @@ 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); @@ -51,7 +51,7 @@ size_t wcsnlen(const wchar_t *wcs, size_t maxsize) { size_t n; -// Note that we do not check if s == NULL, because we do not +// Note that we do not check if s == nullptr, because we do not // return errno_t... for (n = 0; n < maxsize && *wcs; n++, wcs++) @@ -95,8 +95,8 @@ VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) } HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { ORBIS_STUBBED; return NULL; } -VOID Sleep(DWORD dwMilliseconds) -{ +VOID Sleep(DWORD dwMilliseconds) +{ C4JThread::Sleep(dwMilliseconds); } @@ -203,7 +203,7 @@ VOID InitializeCriticalSection(PCRITICAL_SECTION CriticalSection) CriticalSection->m_cLock = 0; assert(err == SCE_OK); #ifdef _DEBUG - CriticalSection->m_pOwnerThread = NULL; + CriticalSection->m_pOwnerThread = nullptr; #endif } @@ -247,7 +247,7 @@ VOID LeaveCriticalSection(PCRITICAL_SECTION CriticalSection) int err = scePthreadMutexUnlock(&CriticalSection->mutex); assert(err == SCE_OK ); #ifdef _DEBUG - CriticalSection->m_pOwnerThread = NULL; + CriticalSection->m_pOwnerThread = nullptr; #endif } @@ -266,8 +266,8 @@ ULONG TryEnterCriticalSection(PCRITICAL_SECTION CriticalSection) DWORD WaitForMultipleObjects(DWORD nCount, CONST HANDLE *lpHandles,BOOL bWaitAll,DWORD dwMilliseconds) { ORBIS_STUBBED; return 0; } -BOOL CloseHandle(HANDLE hObject) -{ +BOOL CloseHandle(HANDLE hObject) +{ sceFiosFHCloseSync(NULL,(SceFiosFH)((int64_t)hObject)); return true; // ORBIS_STUBBED; @@ -342,7 +342,7 @@ public: if(err != SCE_OK) { assert(0); - return NULL; + return nullptr; } // work out where the next page should be in virtual addr space, and pass that to the mapping function void* pageVirtualAddr = ((char*)m_virtualAddr) + m_allocatedSize; @@ -359,12 +359,12 @@ public: if(inAddr != pageVirtualAddr) // make sure we actually get the virtual address that we requested { assert(0); - return NULL; + return nullptr; } if(err != SCE_OK) { assert(0); - return NULL; + return nullptr; } m_pagesAllocated.push_back(PageInfo(physAddr, pageVirtualAddr, sizeToAdd)); m_allocatedSize += sizeToAdd; @@ -393,8 +393,8 @@ public: static std::vector s_orbisVAllocs; -LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) -{ +LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) +{ if(lpAddress == NULL) { void *pAddr = (void*)SCE_KERNEL_APP_MAP_AREA_START_ADDR; @@ -402,7 +402,7 @@ LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWO if( err != SCE_OK ) { app.DebugPrintf("sceKernelReserveVirtualRange failed: 0x%08X\n", err); - return NULL; + return nullptr; } s_orbisVAllocs.push_back(new OrbisVAlloc(pAddr, dwSize)); return (LPVOID)pAddr; @@ -419,10 +419,10 @@ LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWO } } assert(0); // failed to find the virtual alloc in our table - return NULL; + return nullptr; } } - return NULL; + return nullptr; } BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) @@ -483,7 +483,7 @@ BOOL WriteFile( { SceFiosFH fh = (SceFiosFH)((int64_t)hFile); // sceFiosFHReadSync - Non-negative values are the number of bytes read, 0 <= result <= length. Negative values are error codes. - SceFiosSize bytesRead = sceFiosFHWriteSync(NULL, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToWrite); + SceFiosSize bytesRead = sceFiosFHWriteSync(nullptr, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToWrite); if(bytesRead < 0) { // error @@ -500,7 +500,7 @@ BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD { SceFiosFH fh = (SceFiosFH)((int64_t)hFile); // sceFiosFHReadSync - Non-negative values are the number of bytes read, 0 <= result <= length. Negative values are error codes. - SceFiosSize bytesRead = sceFiosFHReadSync(NULL, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToRead); + SceFiosSize bytesRead = sceFiosFHReadSync(nullptr, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToRead); *lpNumberOfBytesRead = (DWORD)bytesRead; if(bytesRead < 0) { @@ -520,7 +520,7 @@ BOOL SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHi uint64_t bitsToMove = (int64_t) lDistanceToMove; SceFiosOffset pos = 0; - if (lpDistanceToMoveHigh != NULL) + if (lpDistanceToMoveHigh != nullptr) bitsToMove |= ((uint64_t) (*lpDistanceToMoveHigh)) << 32; SceFiosWhence whence = SCE_FIOS_SEEK_SET; @@ -581,7 +581,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, case TRUNCATE_EXISTING: break; } - int err = sceFiosFHOpenSync(NULL, &fh, filePath, &openParams); + int err = sceFiosFHOpenSync(nullptr, &fh, filePath, &openParams); if(err != SCE_FIOS_OK) { @@ -597,7 +597,7 @@ BOOL DeleteFileA(LPCSTR lpFileName) { ORBIS_STUBBED; return false; } // BOOL XCloseHandle(HANDLE a) // { -// sceFiosFHCloseSync(NULL,(SceFiosFH)((int64_t)a)); +// sceFiosFHCloseSync(nullptr,(SceFiosFH)((int64_t)a)); // return true; // } @@ -617,7 +617,7 @@ DWORD GetFileAttributesA(LPCSTR lpFileName) // check if the file exists first SceFiosStat statData; - if(sceFiosStatSync(NULL, filePath, &statData) != SCE_FIOS_OK) + if(sceFiosStatSync(nullptr, filePath, &statData) != SCE_FIOS_OK) { app.DebugPrintf("*** sceFiosStatSync Failed\n"); return -1; diff --git a/Minecraft.Client/Orbis/OrbisExtras/TLSStorage.cpp b/Minecraft.Client/Orbis/OrbisExtras/TLSStorage.cpp index 9f17e999d..4229b61d1 100644 --- a/Minecraft.Client/Orbis/OrbisExtras/TLSStorage.cpp +++ b/Minecraft.Client/Orbis/OrbisExtras/TLSStorage.cpp @@ -4,7 +4,7 @@ -TLSStorageOrbis* TLSStorageOrbis::m_pInstance = NULL; +TLSStorageOrbis* TLSStorageOrbis::m_pInstance = nullptr; BOOL TLSStorageOrbis::m_activeList[sc_maxSlots]; __thread LPVOID TLSStorageOrbis::m_values[sc_maxSlots]; @@ -16,7 +16,7 @@ TLSStorageOrbis::TLSStorageOrbis() for(int i=0;isecond; } @@ -124,7 +124,7 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfoFromKeyname(char *pchKeyName) } } - return NULL; + return nullptr; } #define WRAPPED_READFILE(hFile,lpBuffer,nNumberOfBytesToRead,lpNumberOfBytesRead,lpOverlapped) {if(ReadFile(hFile,lpBuffer,nNumberOfBytesToRead,lpNumberOfBytesRead,lpOverlapped)==FALSE) { return FALSE;}} @@ -133,8 +133,8 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() char chDLCTitle[64]; // 4J-PB - Read the file containing the product codes. This will be different for the SCEE/SCEA/SCEJ builds - //HANDLE file = CreateFile("orbis/DLCImages/TP01_360x360.png", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - HANDLE file = CreateFile("orbis/PS4ProductCodes.bin", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + //HANDLE file = CreateFile("orbis/DLCImages/TP01_360x360.png", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE file = CreateFile("orbis/PS4ProductCodes.bin", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { DWORD error = GetLastError(); @@ -149,12 +149,12 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() { DWORD bytesRead; - WRAPPED_READFILE(file,ProductCodes.chProductCode,PRODUCT_CODE_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chCommerceCategory,COMMERCE_CATEGORY_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chTexturePackID,SCE_NP_COMMERCE2_CATEGORY_ID_LEN,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chUpgradeKey,UPGRADE_KEY_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chSkuPostfix,SKU_POSTFIX_SIZE,&bytesRead,NULL); + WRAPPED_READFILE(file,ProductCodes.chProductCode,PRODUCT_CODE_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chCommerceCategory,COMMERCE_CATEGORY_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chTexturePackID,SCE_NP_COMMERCE2_CATEGORY_ID_LEN,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chUpgradeKey,UPGRADE_KEY_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chSkuPostfix,SKU_POSTFIX_SIZE,&bytesRead,nullptr); app.DebugPrintf("ProductCodes.chProductCode %s\n",ProductCodes.chProductCode); app.DebugPrintf("ProductCodes.chSaveFolderPrefix %s\n",ProductCodes.chSaveFolderPrefix); @@ -165,7 +165,7 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() // DLC unsigned int uiDLC; - WRAPPED_READFILE(file,&uiDLC,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&uiDLC,sizeof(int),&bytesRead,nullptr); for(unsigned int i=0;ichDLCKeyname,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,pDLCInfo->chDLCKeyname,sizeof(char)*uiVal,&bytesRead,nullptr); - WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,nullptr); app.DebugPrintf("DLC title %s\n",chDLCTitle); - WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,nullptr); - WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,pDLCInfo->chDLCPicname,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,pDLCInfo->chDLCPicname,sizeof(char)*uiVal,&bytesRead,nullptr); - WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,nullptr); // push this into a vector @@ -310,7 +310,7 @@ void CConsoleMinecraftApp::FreeLocalDLCImages() { free(pDLCInfo->pbImageData); pDLCInfo->dwImageBytes=0; - pDLCInfo->pbImageData=NULL; + pDLCInfo->pbImageData=nullptr; } } } @@ -323,7 +323,7 @@ int CConsoleMinecraftApp::LoadLocalDLCImage(SONYDLC *pDLCInfo) sprintf(pchFilename,"orbis/DLCImages/%s_360x360.png",pDLCInfo->chDLCPicname); // 4J-PB - Read the file containing the product codes. This will be different for the SCEE/SCEA/SCEJ builds - HANDLE hFile = CreateFile(pchFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hFile = CreateFile(pchFilename, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( hFile == INVALID_HANDLE_VALUE ) { @@ -339,7 +339,7 @@ int CConsoleMinecraftApp::LoadLocalDLCImage(SONYDLC *pDLCInfo) DWORD dwBytesRead; pDLCInfo->pbImageData=(PBYTE)malloc(pDLCInfo->dwImageBytes); - if(ReadFile(hFile,pDLCInfo->pbImageData,pDLCInfo->dwImageBytes,&dwBytesRead,NULL)==FALSE) + if(ReadFile(hFile,pDLCInfo->pbImageData,pDLCInfo->dwImageBytes,&dwBytesRead,nullptr)==FALSE) { // failed free(pDLCInfo->pbImageData); @@ -375,7 +375,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() { ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // From CScene_Main::RunPlayGame Minecraft *pMinecraft=Minecraft::GetInstance(); @@ -404,7 +404,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() NetworkGameInitData *param = new NetworkGameInitData(); param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; app.SetGameHostOption(eGameHostOption_Difficulty,0); app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); @@ -620,7 +620,7 @@ SonyCommerce::CategoryInfo *CConsoleMinecraftApp::GetCategoryInfo() { if(m_bCommerceCategoriesRetrieved==false) { - return NULL; + return nullptr; } return &m_CategoryInfo; @@ -636,10 +636,10 @@ void CConsoleMinecraftApp::ClearCommerceDetails() pProductList->clear(); } - if(m_ProductListA!=NULL) + if(m_ProductListA!=nullptr) { delete [] m_ProductListA; - m_ProductListA=NULL; + m_ProductListA=nullptr; } m_ProductListRetrievedC=0; @@ -665,7 +665,7 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch // find the DLC for(int i=0;i* pProductList=&m_ProductListA[i]; for ( SonyCommerce::ProductInfo& : *pProductList ) @@ -727,7 +727,7 @@ std::vector* CConsoleMinecraftApp::GetProductList(int { if((m_bCommerceProductListRetrieved==false) || (m_bProductListAdditionalDetailsRetrieved==false) ) { - return NULL; + return nullptr; } return &m_ProductListA[iIndex]; @@ -1175,7 +1175,7 @@ int CConsoleMinecraftApp::Callback_SaveGameIncompleteMessageBoxReturned(void *pP StorageManager.CancelIncompleteOperation(); break; case C4JStorage::EMessage_ResultThirdOption: - ui.NavigateToScene(iPad, eUIScene_InGameSaveManagementMenu, NULL, eUILayer_Error, eUIGroup_Fullscreen); + ui.NavigateToScene(iPad, eUIScene_InGameSaveManagementMenu, nullptr, eUILayer_Error, eUIGroup_Fullscreen); break; } return 0; @@ -1186,7 +1186,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); bool bEmptyStore=true; - if(pCategories!=NULL) + if(pCategories!=nullptr) { if(pCategories->countOfProducts>0) { @@ -1244,7 +1244,7 @@ void CConsoleMinecraftApp::PatchAvailableDialogTick() UINT uiIDA[1]; uiIDA[0]=IDS_PRO_NOTONLINE_DECLINE; - ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION_PATCH_AVAILABLE, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL, app.GetStringTable()); + ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION_PATCH_AVAILABLE, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr, app.GetStringTable()); m_bPatchAvailableDialogRunning=false; } } diff --git a/Minecraft.Client/Orbis/Orbis_App.h b/Minecraft.Client/Orbis/Orbis_App.h index 1c09579f7..06b6e83a8 100644 --- a/Minecraft.Client/Orbis/Orbis_App.h +++ b/Minecraft.Client/Orbis/Orbis_App.h @@ -86,7 +86,7 @@ public: // BANNED LEVEL LIST virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable *GetStringTable() { return nullptr;} // original code virtual void TemporaryCreateGameStart(); diff --git a/Minecraft.Client/Orbis/Orbis_Minecraft.cpp b/Minecraft.Client/Orbis/Orbis_Minecraft.cpp index 1030ff769..0cb4a0964 100644 --- a/Minecraft.Client/Orbis/Orbis_Minecraft.cpp +++ b/Minecraft.Client/Orbis/Orbis_Minecraft.cpp @@ -367,7 +367,7 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, return pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, - NULL, + nullptr, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, pd3dPP, ppDevice ); @@ -386,16 +386,16 @@ void MemSect(int sect) #endif #ifndef __ORBIS__ -HINSTANCE g_hInst = NULL; -HWND g_hWnd = NULL; +HINSTANCE g_hInst = nullptr; +HWND g_hWnd = nullptr; D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; -ID3D11Device* g_pd3dDevice = NULL; -ID3D11DeviceContext* g_pImmediateContext = NULL; -IDXGISwapChain* g_pSwapChain = NULL; -ID3D11RenderTargetView* g_pRenderTargetView = NULL; -ID3D11DepthStencilView* g_pDepthStencilView = NULL; -ID3D11Texture2D* g_pDepthStencilBuffer = NULL; +ID3D11Device* g_pd3dDevice = nullptr; +ID3D11DeviceContext* g_pImmediateContext = nullptr; +IDXGISwapChain* g_pSwapChain = nullptr; +ID3D11RenderTargetView* g_pRenderTargetView = nullptr; +ID3D11DepthStencilView* g_pDepthStencilView = nullptr; +ID3D11Texture2D* g_pDepthStencilBuffer = nullptr; // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) @@ -460,7 +460,7 @@ ATOM MyRegisterClass(HINSTANCE hInstance) wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, "Minecraft"); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = "Minecraft"; wcex.lpszClassName = "MinecraftClass"; @@ -484,7 +484,7 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) g_hInst = hInstance; // Store instance handle in our global variable g_hWnd = CreateWindow("MinecraftClass", "Minecraft", WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); + CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!g_hWnd) { @@ -548,7 +548,7 @@ HRESULT InitDevice() for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { g_driverType = driverTypes[driverTypeIndex]; - hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, + hr = D3D11CreateDeviceAndSwapChain( nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); if( HRESULT_SUCCEEDED( hr ) ) break; @@ -557,7 +557,7 @@ HRESULT InitDevice() return hr; // Create a render target view - ID3D11Texture2D* pBackBuffer = NULL; + ID3D11Texture2D* pBackBuffer = nullptr; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; @@ -576,7 +576,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, nullptr, &g_pDepthStencilBuffer); D3D11_DEPTH_STENCIL_VIEW_DESC descDSView; descDSView.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; @@ -585,7 +585,7 @@ HRESULT InitDevice() hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); - hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); + hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &g_pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; @@ -778,7 +778,7 @@ int main(int argc, const char *argv[] ) MSG msg = {0}; while( WM_QUIT != msg.message ) { - if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) + if( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); @@ -924,7 +924,7 @@ int main(int argc, const char *argv[] ) StorageManager.Init(0,app.GetString(IDS_DEFAULT_SAVENAME),"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,(LPVOID)&app,""); StorageManager.SetSaveTitleExtraFileSuffix(app.GetString(IDS_SAVE_SUBTITLE_SUFFIX)); StorageManager.SetDLCInfoMap(app.GetSonyDLCMap()); - app.CommerceInit(); // MGH - moved this here so GetCommerce isn't NULL + app.CommerceInit(); // MGH - moved this here so GetCommerce isn't nullptr // 4J-PB - Kick of the check for trial or full version - requires ui to be initialised app.GetCommerce()->CheckForTrialUpgradeKey(); @@ -944,7 +944,7 @@ int main(int argc, const char *argv[] ) } // Create an XAudio2 mastering voice (utilized by XHV2 when voice data is mixed to main speakers) - hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, NULL); + hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, nullptr); if ( FAILED( hr ) ) { app.DebugPrintf( "Creating XAudio2 mastering voice failed (err = 0x%08x)!\n", hr ); @@ -1094,7 +1094,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"); + C4JThread *minecraftThread = new C4JThread(&StartMinecraftThreadProc, nullptr, "Running minecraft start"); minecraftThread->Run(); do { @@ -1199,7 +1199,7 @@ int main(int argc, const char *argv[] ) // We should track down why though... app.DebugPrintf("---init sound engine()\n"); - pMinecraft->soundEngine->init(NULL); + pMinecraft->soundEngine->init(nullptr); while (TRUE) { @@ -1254,7 +1254,7 @@ int main(int argc, const char *argv[] ) else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); @@ -1495,7 +1495,7 @@ uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) uint8_t * AddRichPresenceString(int iID) { uint8_t *strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); - if( strUtf8 != NULL ) + if( strUtf8 != nullptr ) { vRichPresenceStrings.push_back(strUtf8); } @@ -1505,7 +1505,7 @@ uint8_t * AddRichPresenceString(int iID) void FreeRichPresenceStrings() { uint8_t *strUtf8; - for(int i=0;i& fileList); std::string GetMountedPath(std::string szMount); C4JStorage::ETMSStatus ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType, WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int),LPVOID lpParam, int iAction) { return C4JStorage::ETMSStatus_Idle; } @@ -400,7 +400,7 @@ typedef struct bool CheckForTrialUpgradeKey(void( *Func)(LPVOID, bool),LPVOID lpParam); - C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)/*=NULL*/,LPVOID lpParam/*=NULL*/, int iUserData/*=0*/) {return C4JStorage::ETMSStatus_Idle;} + C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)/*=nullptr*/,LPVOID lpParam/*=nullptr*/, int iUserData/*=0*/) {return C4JStorage::ETMSStatus_Idle;} // PROFILE DATA int SetDefaultOptionsCallback(int( *Func)(LPVOID,PROFILESETTINGS *, const int iPad),LPVOID lpParam); diff --git a/Minecraft.Client/PS3/Audio/PS3_SoundEngine.cpp b/Minecraft.Client/PS3/Audio/PS3_SoundEngine.cpp index fcce5f05a..1c7edba30 100644 --- a/Minecraft.Client/PS3/Audio/PS3_SoundEngine.cpp +++ b/Minecraft.Client/PS3/Audio/PS3_SoundEngine.cpp @@ -37,7 +37,7 @@ int SoundEngine::initAudioHardware( int minimum_chans ) a_config.channel = ch_pcm; a_config.encoder = CELL_AUDIO_OUT_CODING_TYPE_LPCM; a_config.downMixer = CELL_AUDIO_OUT_DOWNMIXER_NONE; /* No downmixer is used */ - cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, NULL, 0 ); + cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, nullptr, 0 ); ret = ch_pcm; } @@ -51,7 +51,7 @@ int SoundEngine::initAudioHardware( int minimum_chans ) a_config.channel = 6; a_config.encoder = CELL_AUDIO_OUT_CODING_TYPE_LPCM; a_config.downMixer = CELL_AUDIO_OUT_DOWNMIXER_TYPE_B; - if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, NULL, 0 ) != CELL_OK ) + if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, nullptr, 0 ) != CELL_OK ) { return 0; // error - the downmixer didn't init } @@ -83,7 +83,7 @@ int SoundEngine::initAudioHardware( int minimum_chans ) ret = 8; } - if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, NULL, 0 ) == CELL_OK ) + if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, nullptr, 0 ) == CELL_OK ) { break; } @@ -94,7 +94,7 @@ int SoundEngine::initAudioHardware( int minimum_chans ) a_config.channel = 2; a_config.encoder = CELL_AUDIO_OUT_CODING_TYPE_LPCM; a_config.downMixer = CELL_AUDIO_OUT_DOWNMIXER_TYPE_A; - if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, NULL, 0 ) != CELL_OK ) + if ( cellAudioOutConfigure( CELL_AUDIO_OUT_PRIMARY, &a_config, nullptr, 0 ) != CELL_OK ) { return 0; // error - downmixer didn't work } diff --git a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.cpp b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.cpp index 997e8d837..e8bd03679 100644 --- a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.cpp +++ b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.cpp @@ -751,7 +751,7 @@ static void api_free_resource(GDrawHandle *r) S32 i; for (i=0; i < MAX_SAMPLERS; i++) if (gdraw->active_tex[i] == (GDrawTexture *) r) - gdraw->active_tex[i] = NULL; + gdraw->active_tex[i] = nullptr; } static void RADLINK gdraw_UnlockHandles(GDrawStats *stats) @@ -772,7 +772,7 @@ extern GDrawTexture *gdraw_GCM_WrappedTextureCreate(CellGcmTexture *gcm_tex) memset(&stats, 0, sizeof(stats)); GDrawHandle *p = gdraw_res_alloc_begin(gdraw->texturecache, 0, &stats); // it may need to free one item to give us a handle p->handle.tex.gcm_ptr = 0; - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); gdraw_GCM_WrappedTextureChange((GDrawTexture *) p, gcm_tex); return (GDrawTexture *) p; } @@ -816,11 +816,11 @@ static bool is_texture_swizzled(S32 w, S32 h) static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format gformat, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { S32 bytes_pixel = 4; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; bool swizzled = false; if (width > 4096 || height > 4096) { - IggyGDrawSendWarning(NULL, "GDraw %d x %d texture not supported by hardware (dimension size limit 4096)", width, height); + IggyGDrawSendWarning(nullptr, "GDraw %d x %d texture not supported by hardware (dimension size limit 4096)", width, height); return false; } @@ -893,7 +893,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, if (swizzled || (flags & GDRAW_MAKETEXTURE_FLAGS_mipmap)) { rrbool ok; - assert(p->temp_buffer != NULL); + assert(p->temp_buffer != nullptr); ok = gdraw_MipmapBegin(&gdraw->mipmap, width, height, mipmaps, bytes_pixel, p->temp_buffer, p->temp_buffer_bytes); assert(ok); // this should never hit unless the temp_buffer is way too small @@ -1023,8 +1023,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *t, void *unique_id, GDr static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *stats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); // @GDRAW_ASSERT - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); // @GDRAW_ASSERT + if (t->owner == unique_id || unique_id == nullptr) { if (t->cache == &gdraw->rendertargets) { gdraw_HandleCacheUnlock(t); // cache it by simply not freeing it @@ -1121,7 +1121,7 @@ static rrbool RADLINK gdraw_TryLockVertexBuffer(GDrawVertexBuffer *vb, void *uni static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); // @GDRAW_ASSERT + assert(h != nullptr); // @GDRAW_ASSERT if (h->owner == unique_id) gdraw_res_kill(h, stats); } @@ -1152,19 +1152,19 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) t = gdraw_HandleCacheAllocateBegin(&gdraw->rendertargets); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit handle limit"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit handle limit"); return t; } void *ptr = gdraw_arena_alloc(&gdraw->rt_arena, size, 1); if (!ptr) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: out of rendertarget texture memory"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: out of rendertarget texture memory"); gdraw_HandleCacheAllocateFail(t); - return NULL; + return nullptr; } t->fence = get_next_fence(); // we're about to start using it immediately, so... - t->raw_ptr = NULL; + t->raw_ptr = nullptr; t->handle.tex.gcm_ptr = ptr; @@ -1329,14 +1329,14 @@ static void set_common_renderstate() // reset our state caching for (i=0; i < MAX_SAMPLERS; i++) { - gdraw->active_tex[i] = NULL; + gdraw->active_tex[i] = nullptr; cellGcmSetTextureControl(gcm, i, CELL_GCM_FALSE, 0, 0, 0); } assert(gdraw->aa_tex.offset != 0); // if you hit this, your initialization is screwed up. set_rsx_texture(gdraw->gcm, AATEX_SAMPLER, &gdraw->aa_tex, GDRAW_WRAP_clamp, 0); - gdraw->cur_fprog = NULL; + gdraw->cur_fprog = nullptr; gdraw->vert_format = -1; gdraw->scissor_state = ~0u; gdraw->blend_mode = -1; @@ -1363,7 +1363,7 @@ static void clear_renderstate(void) static void set_render_target() { - GcmTexture *tex = NULL; + GcmTexture *tex = nullptr; S32 i; CellGcmSurface surf = gdraw->main_surface; @@ -1384,7 +1384,7 @@ static void set_render_target() // invalidate current textures (need to reset them to force L1 texture cache flush) for (i=0; i < MAX_SAMPLERS; ++i) - gdraw->active_tex[i] = NULL; + gdraw->active_tex[i] = nullptr; } //////////////////////////////////////////////////////////////////////// @@ -1513,19 +1513,19 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex GDrawFramebufferState *n = gdraw->cur+1; GDrawHandle *t; if (gdraw->tw == 0 || gdraw->th == 0) { - IggyGDrawSendWarning(NULL, "GDraw warning: w=0,h=0 rendertarget"); + IggyGDrawSendWarning(nullptr, "GDraw warning: w=0,h=0 rendertarget"); return false; } if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) { assert(0); - IggyGDrawSendWarning(NULL, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); return false; } if (owner) { // @TODO implement - t = NULL; + t = nullptr; assert(0); // nyi } else { t = get_color_rendertarget(stats); @@ -1534,9 +1534,9 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex } n->color_buffer = t; - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT - n->cached = owner != NULL; + n->cached = owner != nullptr; if (owner) { n->base_x = region->x0; n->base_y = region->y0; @@ -1617,9 +1617,9 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) assert(m >= gdraw->frame); // bug in Iggy -- unbalanced if (m != gdraw->frame) { - assert(m->color_buffer != NULL); // @GDRAW_ASSERT + assert(m->color_buffer != nullptr); // @GDRAW_ASSERT } - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT // wait for render to texture operation to finish // can't put down a backend fence directly, there might still be @@ -1694,7 +1694,7 @@ static void set_fragment_para(GDraw * RADRESTRICT gd, U32 ucode_offs, int para, if (para == -1) return; - gd->cur_fprog = NULL; // need to re-set shader after patching + gd->cur_fprog = nullptr; // need to re-set shader after patching const U64 *inv = (const U64 *) values; const int *patch_offs = (const int *) para; @@ -1728,7 +1728,7 @@ static void set_fragment_para(GDraw * RADRESTRICT gd, U32 ucode_offs, int para, static RADINLINE void set_texture(S32 texunit, GDrawTexture *tex) { assert(texunit < MAX_SAMPLERS); - assert(tex != NULL); + assert(tex != nullptr); if (gdraw->active_tex[texunit] != tex) { gdraw->active_tex[texunit] = tex; @@ -1983,7 +1983,7 @@ static RADINLINE void set_vertex_decl(GDraw * RADRESTRICT gd, CellGcmContextData // Draw triangles with a given renderstate // -static RADINLINE void fence_resources(GDraw * RADRESTRICT gd, void *r1, void *r2=NULL, void *r3=NULL, void *r4=NULL) +static RADINLINE void fence_resources(GDraw * RADRESTRICT gd, void *r1, void *r2=nullptr, void *r3=nullptr, void *r4=nullptr) { GDrawFence fence; fence.value = gd->next_fence_index; @@ -2046,7 +2046,7 @@ static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimiti while (pos < p->num_indices) { S32 vert_count = RR_MIN(p->num_indices - pos, verts_per_chunk); void *ring = gdraw_bufring_alloc(&gd->dyn_vb, vert_count * vsize, CELL_GCM_VERTEX_TEXTURE_CACHE_LINE_SIZE); - assert(ring != NULL); // we specifically chunked so this alloc succeeds! + assert(ring != nullptr); // we specifically chunked so this alloc succeeds! // prepare for painting... cellGcmSetInvalidateVertexCache(gcm); @@ -2083,7 +2083,7 @@ static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimiti S32 vert_count = RR_MIN(p->num_vertices - pos, verts_per_chunk); U32 chunk_bytes = vert_count * vsize; void *ring = gdraw_bufring_alloc(&gd->dyn_vb, chunk_bytes, CELL_GCM_VERTEX_TEXTURE_CACHE_LINE_SIZE); - assert(ring != NULL); // we picked the chunk size so this alloc succeeds! + assert(ring != nullptr); // we picked the chunk size so this alloc succeeds! memcpy(ring, (U8 *)p->vertices + pos * vsize, chunk_bytes); cellGcmSetInvalidateVertexCache(gcm); @@ -2203,7 +2203,7 @@ static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbe { ProgramWithCachedVariableLocations *prg = &gdraw->filter_prog[isbevel][r->filter_mode]; U32 ucode_offs = prg->cfg.offset; - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, stats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, stats)) return; set_texture(0, r->tex[0]); @@ -2287,14 +2287,14 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 assert(0); } } else { - GDrawHandle *blend_tex = NULL; + GDrawHandle *blend_tex = nullptr; GDraw *gd = gdraw; // for crazy blend modes, we need to read back from the framebuffer // and do the blending in the pixel shader. so we need to copy the // relevant pixels from our active render target into a texture. if (r->blend_mode == GDRAW_BLEND_special && - (blend_tex = get_color_rendertarget(stats)) != NULL) { + (blend_tex = get_color_rendertarget(stats)) != nullptr) { // slightly different logic depending on whether we were rendering // to the main color buffer or a render target, because the former // has tile origin-based coordinates while the latter don't. also, @@ -2344,7 +2344,7 @@ static void create_fragment_program(ProgramWithCachedVariableLocations *p, Progr cellGcmCgGetUCode(p->program, &ucode_main, &ucode_size); ucode_local = gdraw_arena_alloc(&gdraw->local_arena, ucode_size + 400, CELL_GCM_FRAGMENT_UCODE_LOCAL_ALIGN_OFFSET); // 400 for overfetch - assert(ucode_local != NULL); // if this triggers, it's a GDraw bug + assert(ucode_local != nullptr); // if this triggers, it's a GDraw bug memcpy(ucode_local, ucode_main, ucode_size); cellGcmCgGetCgbFragmentProgramConfiguration(p->program, &p->cfg, 0, 1, 0); @@ -2408,7 +2408,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_gcm_resourcetype type, U32 alig U32 header_size = is_vertex ? 0 : sizeof(GcmTexture) * num_handles; if (!num_handles) - return NULL; + return nullptr; GDrawHandleCache *cache = (GDrawHandleCache *) IggyGDrawMalloc(cache_size + header_size); if (cache) { @@ -2427,7 +2427,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_gcm_resourcetype type, U32 alig cache->alloc = gfxalloc_create(gdraw_mem[type].ptr, num_bytes, align, num_handles); if (!cache->alloc) { IggyGDrawFree(cache); - cache = NULL; + cache = nullptr; } } @@ -2496,14 +2496,14 @@ int gdraw_GCM_SetResourceMemory(gdraw_gcm_resourcetype type, S32 num_handles, vo free_handle_cache(gdraw->texturecache); gdraw->texturecache = make_handle_cache(GDRAW_GCM_RESOURCE_texture, CELL_GCM_TEXTURE_SWIZZLE_ALIGN_OFFSET); gdraw->tex_loc = get_location(ptr); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_GCM_RESOURCE_vertexbuffer: free_handle_cache(gdraw->vbufcache); gdraw->vbufcache = make_handle_cache(GDRAW_GCM_RESOURCE_vertexbuffer, CELL_GCM_SURFACE_LINEAR_ALIGN_OFFSET); gdraw->vbuf_base = ptr ? (U8 *) ptr - addr2offs(ptr) : 0; gdraw->vbuf_loc = get_location(ptr); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; case GDRAW_GCM_RESOURCE_dyn_vertexbuffer: gdraw_bufring_shutdown(&gdraw->dyn_vb); @@ -2549,10 +2549,10 @@ int gdraw_GCM_SetRendertargetMemory(void *ptr, S32 num_bytes, S32 width, S32 hei void gdraw_GCM_ResetAllResourceMemory() { - gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_texture, 0, NULL, 0); - gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_vertexbuffer, 0, NULL, 0); - gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_dyn_vertexbuffer, 0, NULL, 0); - gdraw_GCM_SetRendertargetMemory(NULL, 0, 0, 0, 0); + gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_texture, 0, nullptr, 0); + gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_vertexbuffer, 0, nullptr, 0); + gdraw_GCM_SetResourceMemory(GDRAW_GCM_RESOURCE_dyn_vertexbuffer, 0, nullptr, 0); + gdraw_GCM_SetRendertargetMemory(nullptr, 0, 0, 0, 0); } GDrawFunctions *gdraw_GCM_CreateContext(CellGcmContextData *gcm, void *local_workmem, U8 rsx_label_index) @@ -2560,7 +2560,7 @@ GDrawFunctions *gdraw_GCM_CreateContext(CellGcmContextData *gcm, void *local_wor S32 i; gdraw = (GDraw *) IggyGDrawMalloc(sizeof(*gdraw)); // make sure gdraw struct is PPU cache line aligned - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -2648,7 +2648,7 @@ void gdraw_GCM_DestroyContext(void) free_handle_cache(gdraw->texturecache); free_handle_cache(gdraw->vbufcache); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } } diff --git a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.h b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.h index f8ec8705e..cf691d067 100644 --- a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.h +++ b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm.h @@ -108,7 +108,7 @@ IDOC extern GDrawFunctions * gdraw_GCM_CreateContext(CellGcmContextData *gcm, vo There can only be one GCM GDraw context active at any one time. If initialization fails for some reason (the main reason would be an out of memory condition), - NULL is returned. Otherwise, you can pass the return value to IggySetGDraw. */ + nullptr is returned. Otherwise, you can pass the return value to IggySetGDraw. */ IDOC extern void gdraw_GCM_DestroyContext(void); /* Destroys the current GDraw context, if any. */ diff --git a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm_shaders.inl b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm_shaders.inl index 811f524a9..4d3c91bb0 100644 --- a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm_shaders.inl +++ b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_ps3gcm_shaders.inl @@ -273,24 +273,24 @@ static int pshader_basic_econst[28] = { }; static ProgramWithCachedVariableLocations pshader_basic_arr[18] = { - { { pshader_basic_0 }, { NULL }, { -1, 7, -1, -1, -1, } }, - { { pshader_basic_1 }, { NULL }, { -1, 7, -1, (int) (intptr_t) (pshader_basic_econst + 0), -1, } }, - { { pshader_basic_2 }, { NULL }, { -1, 7, -1, (int) (intptr_t) (pshader_basic_econst + 0), -1, } }, - { { pshader_basic_3 }, { NULL }, { 0, 7, -1, -1, -1, } }, - { { pshader_basic_4 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 2), -1, } }, - { { pshader_basic_5 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 4), -1, } }, - { { pshader_basic_6 }, { NULL }, { 0, 7, -1, -1, -1, } }, - { { pshader_basic_7 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 6), -1, } }, - { { pshader_basic_8 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 6), -1, } }, - { { pshader_basic_9 }, { NULL }, { 0, 7, -1, -1, -1, } }, - { { pshader_basic_10 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 8), -1, } }, - { { pshader_basic_11 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 10), -1, } }, - { { pshader_basic_12 }, { NULL }, { 0, 7, -1, -1, (int) (intptr_t) (pshader_basic_econst + 12), } }, - { { pshader_basic_13 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 16), (int) (intptr_t) (pshader_basic_econst + 18), } }, - { { pshader_basic_14 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 22), (int) (intptr_t) (pshader_basic_econst + 24), } }, - { { pshader_basic_15 }, { NULL }, { 0, 7, -1, -1, -1, } }, - { { pshader_basic_16 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 2), -1, } }, - { { pshader_basic_17 }, { NULL }, { 0, 7, -1, (int) (intptr_t) (pshader_basic_econst + 6), -1, } }, + { { pshader_basic_0 }, { nullptr }, { -1, 7, -1, -1, -1, } }, + { { pshader_basic_1 }, { nullptr }, { -1, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 0)), -1, } }, + { { pshader_basic_2 }, { nullptr }, { -1, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 0)), -1, } }, + { { pshader_basic_3 }, { nullptr }, { 0, 7, -1, -1, -1, } }, + { { pshader_basic_4 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 2)), -1, } }, + { { pshader_basic_5 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 4)), -1, } }, + { { pshader_basic_6 }, { nullptr }, { 0, 7, -1, -1, -1, } }, + { { pshader_basic_7 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 6)), -1, } }, + { { pshader_basic_8 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 6)), -1, } }, + { { pshader_basic_9 }, { nullptr }, { 0, 7, -1, -1, -1, } }, + { { pshader_basic_10 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 8)), -1, } }, + { { pshader_basic_11 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 10)), -1, } }, + { { pshader_basic_12 }, { nullptr }, { 0, 7, -1, -1, static_cast((intptr_t)(pshader_basic_econst + 12)), } }, + { { pshader_basic_13 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 16)), static_cast((intptr_t)(pshader_basic_econst + 18)), } }, + { { pshader_basic_14 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 22)), static_cast((intptr_t)(pshader_basic_econst + 24)), } }, + { { pshader_basic_15 }, { nullptr }, { 0, 7, -1, -1, -1, } }, + { { pshader_basic_16 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 2)), -1, } }, + { { pshader_basic_17 }, { nullptr }, { 0, 7, -1, static_cast((intptr_t)(pshader_basic_econst + 6)), -1, } }, }; static unsigned char pshader_exceptional_blend_1[368] = { @@ -536,19 +536,19 @@ static int pshader_exceptional_blend_econst[4] = { }; static ProgramWithCachedVariableLocations pshader_exceptional_blend_arr[13] = { - { { NULL }, { NULL }, { -1, -1, -1, -1, } }, - { { pshader_exceptional_blend_1 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_2 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_3 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_4 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_5 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_6 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_7 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_8 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_9 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_10 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 0), } }, - { { pshader_exceptional_blend_11 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 2), } }, - { { pshader_exceptional_blend_12 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_exceptional_blend_econst + 2), } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, } }, + { { pshader_exceptional_blend_1 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_2 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_3 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_4 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_5 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_6 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_7 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_8 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_9 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_10 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 0)), } }, + { { pshader_exceptional_blend_11 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 2)), } }, + { { pshader_exceptional_blend_12 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_exceptional_blend_econst + 2)), } }, }; static unsigned char pshader_filter_0[416] = { @@ -1121,38 +1121,38 @@ static int pshader_filter_econst[90] = { }; static ProgramWithCachedVariableLocations pshader_filter_arr[32] = { - { { pshader_filter_0 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 0), (int) (intptr_t) (pshader_filter_econst + 2), -1, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_1 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 11), (int) (intptr_t) (pshader_filter_econst + 2), -1, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_2 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 13), 2, (int) (intptr_t) (pshader_filter_econst + 16), (int) (intptr_t) (pshader_filter_econst + 5), -1, } }, - { { pshader_filter_3 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 13), 2, (int) (intptr_t) (pshader_filter_econst + 16), (int) (intptr_t) (pshader_filter_econst + 5), -1, } }, - { { pshader_filter_4 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 19), (int) (intptr_t) (pshader_filter_econst + 2), -1, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_5 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 11), (int) (intptr_t) (pshader_filter_econst + 2), -1, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_6 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 2), 2, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_7 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 13), 2, (int) (intptr_t) (pshader_filter_econst + 16), (int) (intptr_t) (pshader_filter_econst + 5), -1, } }, - { { pshader_filter_8 }, { NULL }, { -1, 1, (int) (intptr_t) (pshader_filter_econst + 21), -1, -1, -1, (int) (intptr_t) (pshader_filter_econst + 24), -1, } }, - { { pshader_filter_9 }, { NULL }, { -1, -1, (int) (intptr_t) (pshader_filter_econst + 27), -1, -1, -1, -1, -1, } }, - { { pshader_filter_10 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 2), 2, (int) (intptr_t) (pshader_filter_econst + 5), (int) (intptr_t) (pshader_filter_econst + 8), -1, } }, - { { pshader_filter_11 }, { NULL }, { 0, -1, -1, (int) (intptr_t) (pshader_filter_econst + 29), 2, (int) (intptr_t) (pshader_filter_econst + 32), -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { pshader_filter_16 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 35), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 46), (int) (intptr_t) (pshader_filter_econst + 49), } }, - { { pshader_filter_17 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 47), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 51), (int) (intptr_t) (pshader_filter_econst + 35), } }, - { { pshader_filter_18 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 37), 2, (int) (intptr_t) (pshader_filter_econst + 54), (int) (intptr_t) (pshader_filter_econst + 59), -1, } }, - { { pshader_filter_19 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 62), 2, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 66), -1, } }, - { { pshader_filter_20 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 35), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 46), (int) (intptr_t) (pshader_filter_econst + 49), } }, - { { pshader_filter_21 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 47), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 51), (int) (intptr_t) (pshader_filter_econst + 35), } }, - { { pshader_filter_22 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 69), 2, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 73), -1, } }, - { { pshader_filter_23 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 62), 2, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 66), -1, } }, - { { pshader_filter_24 }, { NULL }, { 0, 1, (int) (intptr_t) (pshader_filter_econst + 35), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), (int) (intptr_t) (pshader_filter_econst + 46), (int) (intptr_t) (pshader_filter_econst + 49), } }, - { { pshader_filter_25 }, { NULL }, { 0, -1, (int) (intptr_t) (pshader_filter_econst + 76), (int) (intptr_t) (pshader_filter_econst + 37), -1, (int) (intptr_t) (pshader_filter_econst + 41), -1, (int) (intptr_t) (pshader_filter_econst + 67), } }, - { { pshader_filter_26 }, { NULL }, { 0, 1, -1, (int) (intptr_t) (pshader_filter_econst + 78), 2, (int) (intptr_t) (pshader_filter_econst + 82), (int) (intptr_t) (pshader_filter_econst + 87), -1, } }, - { { pshader_filter_27 }, { NULL }, { 0, -1, -1, (int) (intptr_t) (pshader_filter_econst + 37), 2, (int) (intptr_t) (pshader_filter_econst + 41), -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { pshader_filter_0 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 0)), static_cast((intptr_t)(pshader_filter_econst + 2)), -1, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_1 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 11)), static_cast((intptr_t)(pshader_filter_econst + 2)), -1, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_2 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 13)), 2, static_cast((intptr_t)(pshader_filter_econst + 16)), static_cast((intptr_t)(pshader_filter_econst + 5)), -1, } }, + { { pshader_filter_3 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 13)), 2, static_cast((intptr_t)(pshader_filter_econst + 16)), static_cast((intptr_t)(pshader_filter_econst + 5)), -1, } }, + { { pshader_filter_4 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 19)), static_cast((intptr_t)(pshader_filter_econst + 2)), -1, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_5 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 11)), static_cast((intptr_t)(pshader_filter_econst + 2)), -1, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_6 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 2)), 2, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_7 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 13)), 2, static_cast((intptr_t)(pshader_filter_econst + 16)), static_cast((intptr_t)(pshader_filter_econst + 5)), -1, } }, + { { pshader_filter_8 }, { nullptr }, { -1, 1, static_cast((intptr_t)(pshader_filter_econst + 21)), -1, -1, -1, static_cast((intptr_t)(pshader_filter_econst + 24)), -1, } }, + { { pshader_filter_9 }, { nullptr }, { -1, -1, static_cast((intptr_t)(pshader_filter_econst + 27)), -1, -1, -1, -1, -1, } }, + { { pshader_filter_10 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 2)), 2, static_cast((intptr_t)(pshader_filter_econst + 5)), static_cast((intptr_t)(pshader_filter_econst + 8)), -1, } }, + { { pshader_filter_11 }, { nullptr }, { 0, -1, -1, static_cast((intptr_t)(pshader_filter_econst + 29)), 2, static_cast((intptr_t)(pshader_filter_econst + 32)), -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { pshader_filter_16 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 35)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 46)), static_cast((intptr_t)(pshader_filter_econst + 49)), } }, + { { pshader_filter_17 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 47)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 51)), static_cast((intptr_t)(pshader_filter_econst + 35)), } }, + { { pshader_filter_18 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 37)), 2, static_cast((intptr_t)(pshader_filter_econst + 54)), static_cast((intptr_t)(pshader_filter_econst + 59)), -1, } }, + { { pshader_filter_19 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 62)), 2, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 66)), -1, } }, + { { pshader_filter_20 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 35)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 46)), static_cast((intptr_t)(pshader_filter_econst + 49)), } }, + { { pshader_filter_21 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 47)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 51)), static_cast((intptr_t)(pshader_filter_econst + 35)), } }, + { { pshader_filter_22 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 69)), 2, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 73)), -1, } }, + { { pshader_filter_23 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 62)), 2, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 66)), -1, } }, + { { pshader_filter_24 }, { nullptr }, { 0, 1, static_cast((intptr_t)(pshader_filter_econst + 35)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), static_cast((intptr_t)(pshader_filter_econst + 46)), static_cast((intptr_t)(pshader_filter_econst + 49)), } }, + { { pshader_filter_25 }, { nullptr }, { 0, -1, static_cast((intptr_t)(pshader_filter_econst + 76)), static_cast((intptr_t)(pshader_filter_econst + 37)), -1, static_cast((intptr_t)(pshader_filter_econst + 41)), -1, static_cast((intptr_t)(pshader_filter_econst + 67)), } }, + { { pshader_filter_26 }, { nullptr }, { 0, 1, -1, static_cast((intptr_t)(pshader_filter_econst + 78)), 2, static_cast((intptr_t)(pshader_filter_econst + 82)), static_cast((intptr_t)(pshader_filter_econst + 87)), -1, } }, + { { pshader_filter_27 }, { nullptr }, { 0, -1, -1, static_cast((intptr_t)(pshader_filter_econst + 37)), 2, static_cast((intptr_t)(pshader_filter_econst + 41)), -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, -1, -1, -1, -1, -1, } }, }; static unsigned char pshader_blur_2[368] = { @@ -1560,16 +1560,16 @@ static int pshader_blur_econst[256] = { }; static ProgramWithCachedVariableLocations pshader_blur_arr[10] = { - { { NULL }, { NULL }, { -1, -1, -1, } }, - { { NULL }, { NULL }, { -1, -1, -1, } }, - { { pshader_blur_2 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 0), (int) (intptr_t) (pshader_blur_econst + 13), } }, - { { pshader_blur_3 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 18), (int) (intptr_t) (pshader_blur_econst + 33), } }, - { { pshader_blur_4 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 40), (int) (intptr_t) (pshader_blur_econst + 57), } }, - { { pshader_blur_5 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 66), (int) (intptr_t) (pshader_blur_econst + 85), } }, - { { pshader_blur_6 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 96), (int) (intptr_t) (pshader_blur_econst + 117), } }, - { { pshader_blur_7 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 130), (int) (intptr_t) (pshader_blur_econst + 153), } }, - { { pshader_blur_8 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 168), (int) (intptr_t) (pshader_blur_econst + 193), } }, - { { pshader_blur_9 }, { NULL }, { 0, (int) (intptr_t) (pshader_blur_econst + 210), (int) (intptr_t) (pshader_blur_econst + 237), } }, + { { nullptr }, { nullptr }, { -1, -1, -1, } }, + { { nullptr }, { nullptr }, { -1, -1, -1, } }, + { { pshader_blur_2 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 0)), static_cast((intptr_t)(pshader_blur_econst + 13)), } }, + { { pshader_blur_3 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 18)), static_cast((intptr_t)(pshader_blur_econst + 33)), } }, + { { pshader_blur_4 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 40)), static_cast((intptr_t)(pshader_blur_econst + 57)), } }, + { { pshader_blur_5 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 66)), static_cast((intptr_t)(pshader_blur_econst + 85)), } }, + { { pshader_blur_6 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 96)), static_cast((intptr_t)(pshader_blur_econst + 117)), } }, + { { pshader_blur_7 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 130)), static_cast((intptr_t)(pshader_blur_econst + 153)), } }, + { { pshader_blur_8 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 168)), static_cast((intptr_t)(pshader_blur_econst + 193)), } }, + { { pshader_blur_9 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_blur_econst + 210)), static_cast((intptr_t)(pshader_blur_econst + 237)), } }, }; static unsigned char pshader_color_matrix_0[336] = { @@ -1598,7 +1598,7 @@ static int pshader_color_matrix_econst[12] = { }; static ProgramWithCachedVariableLocations pshader_color_matrix_arr[1] = { - { { pshader_color_matrix_0 }, { NULL }, { 0, (int) (intptr_t) (pshader_color_matrix_econst + 0), } }, + { { pshader_color_matrix_0 }, { nullptr }, { 0, static_cast((intptr_t)(pshader_color_matrix_econst + 0)), } }, }; static unsigned char vshader_vsps3_0[272] = { @@ -1655,8 +1655,8 @@ static unsigned char vshader_vsps3_2[240] = { }; static ProgramWithCachedVariableLocations vshader_vsps3_arr[3] = { - { { vshader_vsps3_0 }, { NULL }, { } }, - { { vshader_vsps3_1 }, { NULL }, { } }, - { { vshader_vsps3_2 }, { NULL }, { } }, + { { vshader_vsps3_0 }, { nullptr }, { } }, + { { vshader_vsps3_1 }, { nullptr }, { } }, + { { vshader_vsps3_2 }, { nullptr }, { } }, }; diff --git a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_shared.inl b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_shared.inl index 86293ab6d..6f8dd9c02 100644 --- a/Minecraft.Client/PS3/Iggy/gdraw/gdraw_shared.inl +++ b/Minecraft.Client/PS3/Iggy/gdraw/gdraw_shared.inl @@ -226,7 +226,7 @@ static void debug_check_raw_values(GDrawHandleCache *c) s = s->next; } s = c->active; - while (s != NULL) { + while (s != nullptr) { assert(s->raw_ptr != t->raw_ptr); s = s->next; } @@ -368,7 +368,7 @@ static void gdraw_HandleTransitionInsertBefore(GDrawHandle *t, GDrawHandleState { check_lists(t->cache); assert(t->state != GDRAW_HANDLE_STATE_sentinel); // sentinels should never get here! - assert(t->state != (U32) new_state); // code should never call "transition" if it's not transitioning! + assert(t->state != static_cast(new_state)); // code should never call "transition" if it's not transitioning! // unlink from prev state t->prev->next = t->next; t->next->prev = t->prev; @@ -433,7 +433,7 @@ static rrbool gdraw_HandleCacheLockStats(GDrawHandle *t, void *owner, GDrawStats static rrbool gdraw_HandleCacheLock(GDrawHandle *t, void *owner) { - return gdraw_HandleCacheLockStats(t, owner, NULL); + return gdraw_HandleCacheLockStats(t, owner, nullptr); } static void gdraw_HandleCacheUnlock(GDrawHandle *t) @@ -461,11 +461,11 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->is_thrashing = false; c->did_defragment = false; for (i=0; i < GDRAW_HANDLE_STATE__count; i++) { - c->state[i].owner = NULL; - c->state[i].cache = NULL; // should never follow cache link from sentinels! + c->state[i].owner = nullptr; + c->state[i].cache = nullptr; // should never follow cache link from sentinels! c->state[i].next = c->state[i].prev = &c->state[i]; #ifdef GDRAW_MANAGE_MEM - c->state[i].raw_ptr = NULL; + c->state[i].raw_ptr = nullptr; #endif c->state[i].fence.value = 0; c->state[i].bytes = 0; @@ -478,7 +478,7 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->handle[i].bytes = 0; c->handle[i].state = GDRAW_HANDLE_STATE_free; #ifdef GDRAW_MANAGE_MEM - c->handle[i].raw_ptr = NULL; + c->handle[i].raw_ptr = nullptr; #endif } c->state[GDRAW_HANDLE_STATE_free].next = &c->handle[0]; @@ -486,10 +486,10 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->prev_frame_start.value = 0; c->prev_frame_end.value = 0; #ifdef GDRAW_MANAGE_MEM - c->alloc = NULL; + c->alloc = nullptr; #endif #ifdef GDRAW_MANAGE_MEM_TWOPOOL - c->alloc_other = NULL; + c->alloc_other = nullptr; #endif check_lists(c); } @@ -497,14 +497,14 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte static GDrawHandle *gdraw_HandleCacheAllocateBegin(GDrawHandleCache *c) { GDrawHandle *free_list = &c->state[GDRAW_HANDLE_STATE_free]; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (free_list->next != free_list) { t = free_list->next; gdraw_HandleTransitionTo(t, GDRAW_HANDLE_STATE_alloc); t->bytes = 0; t->owner = 0; #ifdef GDRAW_MANAGE_MEM - t->raw_ptr = NULL; + t->raw_ptr = nullptr; #endif #ifdef GDRAW_CORRUPTION_CHECK t->has_check_value = false; @@ -563,7 +563,7 @@ static GDrawHandle *gdraw_HandleCacheGetLRU(GDrawHandleCache *c) // at the front of the LRU list are the oldest ones, since in-use resources // will get appended on every transition from "locked" to "live". GDrawHandle *sentinel = &c->state[GDRAW_HANDLE_STATE_live]; - return (sentinel->next != sentinel) ? sentinel->next : NULL; + return (sentinel->next != sentinel) ? sentinel->next : nullptr; } static void gdraw_HandleCacheTick(GDrawHandleCache *c, GDrawFence now) @@ -778,7 +778,7 @@ static GDrawTexture *gdraw_BlurPass(GDrawFunctions *g, GDrawBlurInfo *c, GDrawRe if (!g->TextureDrawBufferBegin(draw_bounds, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, gstats)) return r->tex[0]; - c->BlurPass(r, taps, data, draw_bounds, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, draw_bounds, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -830,7 +830,7 @@ static GDrawTexture *gdraw_BlurPassDownsample(GDrawFunctions *g, GDrawBlurInfo * assert(clamp[0] <= clamp[2]); assert(clamp[1] <= clamp[3]); - c->BlurPass(r, taps, data, &z, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, &z, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -842,7 +842,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR GDrawTexture *t; F32 data[MAX_TAPS][4]; S32 off_axis = 1-axis; - S32 w = ((S32) ceil((blur_width-1)/2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 + S32 w = static_cast(ceil((blur_width - 1) / 2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 F32 edge_weight = 1 - (w - blur_width)/2; // 3 => 0 => 1; 1.2 => 1.8 => 0.9 => 0.1 F32 inverse_weight = 1.0f / blur_width; @@ -949,7 +949,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR // max coverage is 25 samples, or a filter width of 13. with 7 taps, we sample // 13 samples in one pass, max coverage is 13*13 samples or (13*13-1)/2 width, // which is ((2T-1)*(2T-1)-1)/2 or (4T^2 - 4T + 1 -1)/2 or 2T^2 - 2T or 2T*(T-1) - S32 w_mip = (S32) ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS)); + S32 w_mip = static_cast(ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS))); S32 downsample = w_mip; F32 sample_spacing = texel; if (downsample < 2) downsample = 2; @@ -1095,7 +1095,7 @@ static void make_pool_aligned(void **start, S32 *num_bytes, U32 alignment) if (addr_aligned != addr_orig) { S32 diff = (S32) (addr_aligned - addr_orig); if (*num_bytes < diff) { - *start = NULL; + *start = nullptr; *num_bytes = 0; return; } else { @@ -1132,7 +1132,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) UINTa remaining = arena->end - arena->current; UINTa total_size = (ptr - arena->current) + size; if (remaining < total_size) // doesn't fit - return NULL; + return nullptr; arena->current = ptr + size; return ptr; @@ -1157,7 +1157,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // (i.e. block->next->prev == block->prev->next == block) // - All allocated blocks are also kept in a hash table, indexed by their // pointer (to allow free to locate the corresponding block_info quickly). -// There's a single-linked, NULL-terminated list of elements in each hash +// There's a single-linked, nullptr-terminated list of elements in each hash // bucket. // - The physical block list is ordered. It always contains all currently // active blocks and spans the whole managed memory range. There are no @@ -1166,7 +1166,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // they are coalesced immediately. // - The maximum number of blocks that could ever be necessary is allocated // on initialization. All block_infos not currently in use are kept in a -// single-linked, NULL-terminated list of unused blocks. Every block is either +// single-linked, nullptr-terminated list of unused blocks. Every block is either // in the physical block list or the unused list, and the total number of // blocks is constant. // These invariants always hold before and after an allocation/free. @@ -1384,7 +1384,7 @@ static void gfxalloc_check2(gfx_allocator *alloc) static gfx_block_info *gfxalloc_pop_unused(gfx_allocator *alloc) { - GFXALLOC_ASSERT(alloc->unused_list != NULL); + GFXALLOC_ASSERT(alloc->unused_list != nullptr); GFXALLOC_ASSERT(alloc->unused_list->is_unused); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_unused);) @@ -1457,7 +1457,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma U32 i, max_blocks, size; if (!align || (align & (align - 1)) != 0) // align must be >0 and a power of 2 - return NULL; + return nullptr; // for <= max_allocs live allocs, there's <= 2*max_allocs+1 blocks. worst case: // [free][used][free] .... [free][used][free] @@ -1465,7 +1465,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma size = sizeof(gfx_allocator) + max_blocks * sizeof(gfx_block_info); a = (gfx_allocator *) IggyGDrawMalloc(size); if (!a) - return NULL; + return nullptr; memset(a, 0, size); @@ -1506,16 +1506,16 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma a->blocks[i].is_unused = 1; gfxalloc_check(a); - debug_complete_check(a, NULL, 0,0); + debug_complete_check(a, nullptr, 0,0); return a; } static void *gfxalloc_alloc(gfx_allocator *alloc, U32 size_in_bytes) { - gfx_block_info *cur, *best = NULL; + gfx_block_info *cur, *best = nullptr; U32 i, best_wasted = ~0u; U32 size = size_in_bytes; -debug_complete_check(alloc, NULL, 0,0); +debug_complete_check(alloc, nullptr, 0,0); gfxalloc_check(alloc); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_blocks == alloc->num_alloc + alloc->num_free + alloc->num_unused);) GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_free <= alloc->num_blocks+1);) @@ -1565,7 +1565,7 @@ gfxalloc_check(alloc); debug_check_overlap(alloc->cache, best->ptr, best->size); return best->ptr; } else - return NULL; // not enough space! + return nullptr; // not enough space! } static void gfxalloc_free(gfx_allocator *alloc, void *ptr) @@ -1735,7 +1735,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta // (unused for allocated blocks, we'll use it to store a back-pointer to the corresponding handle) for (b = alloc->blocks[0].next_phys; b != alloc->blocks; b=b->next_phys) if (!b->is_free) - b->prev = NULL; + b->prev = nullptr; // go through all handles and store a pointer to the handle in the corresponding memory block for (i=0; i < c->max_handles; i++) @@ -1748,7 +1748,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta break; } - GFXALLOC_ASSERT(b != NULL); // didn't find this block anywhere! + GFXALLOC_ASSERT(b != nullptr); // didn't find this block anywhere! } // clear alloc hash table (we rebuild it during defrag) @@ -1910,7 +1910,7 @@ static rrbool gdraw_CanDefragment(GDrawHandleCache *c) static rrbool gdraw_MigrateResource(GDrawHandle *t, GDrawStats *stats) { GDrawHandleCache *c = t->cache; - void *ptr = NULL; + void *ptr = nullptr; assert(t->state == GDRAW_HANDLE_STATE_live || t->state == GDRAW_HANDLE_STATE_locked || t->state == GDRAW_HANDLE_STATE_pinned); // anything we migrate should be in the "other" (old) pool @@ -2300,7 +2300,7 @@ static void gdraw_bufring_init(gdraw_bufring * RADRESTRICT ring, void *ptr, U32 static void gdraw_bufring_shutdown(gdraw_bufring * RADRESTRICT ring) { - ring->cur = NULL; + ring->cur = nullptr; ring->seg_size = 0; } @@ -2310,7 +2310,7 @@ static void *gdraw_bufring_alloc(gdraw_bufring * RADRESTRICT ring, U32 size, U32 gdraw_bufring_seg *seg; if (size > ring->seg_size) - return NULL; // nope, won't fit + return nullptr; // nope, won't fit assert(align <= ring->align); @@ -2415,7 +2415,7 @@ static rrbool gdraw_res_free_lru(GDrawHandleCache *c, GDrawStats *stats) // was it referenced since end of previous frame (=in this frame)? // if some, we're thrashing; report it to the user, but only once per frame. if (c->prev_frame_end.value < r->fence.value && !c->is_thrashing) { - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); c->is_thrashing = true; } @@ -2435,8 +2435,8 @@ static GDrawHandle *gdraw_res_alloc_outofmem(GDrawHandleCache *c, GDrawHandle *t { if (t) gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); - return NULL; + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); + return nullptr; } #ifndef GDRAW_MANAGE_MEM @@ -2445,7 +2445,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt { GDrawHandle *t; if (size > c->total_bytes) - gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); else { // given how much data we're going to allocate, throw out // data until there's "room" (this basically lets us use @@ -2453,7 +2453,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // packing it and being exact) while (c->bytes_free < size) { if (!gdraw_res_free_lru(c, stats)) { - gdraw_res_alloc_outofmem(c, NULL, "memory"); + gdraw_res_alloc_outofmem(c, nullptr, "memory"); break; } } @@ -2468,8 +2468,8 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // we'd trade off cost of regenerating) if (gdraw_res_free_lru(c, stats)) { t = gdraw_HandleCacheAllocateBegin(c); - if (t == NULL) { - gdraw_res_alloc_outofmem(c, NULL, "handles"); + if (t == nullptr) { + gdraw_res_alloc_outofmem(c, nullptr, "handles"); } } } @@ -2513,7 +2513,7 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) { GDRAW_FENCE_FLUSH(); // dead list is sorted by fence index - make sure all fence values are current. - r->owner = NULL; + r->owner = nullptr; gdraw_HandleCacheInsertDead(r); gdraw_res_reap(r->cache, stats); } @@ -2521,11 +2521,11 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawStats *stats) { GDrawHandle *t; - void *ptr = NULL; + void *ptr = nullptr; gdraw_res_reap(c, stats); // NB this also does GDRAW_FENCE_FLUSH(); if (size > c->total_bytes) - return gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + return gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); // now try to allocate a handle t = gdraw_HandleCacheAllocateBegin(c); @@ -2537,7 +2537,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt gdraw_res_free_lru(c, stats); t = gdraw_HandleCacheAllocateBegin(c); if (!t) - return gdraw_res_alloc_outofmem(c, NULL, "handles"); + return gdraw_res_alloc_outofmem(c, nullptr, "handles"); } // try to allocate first diff --git a/Minecraft.Client/PS3/Iggy/include/gdraw.h b/Minecraft.Client/PS3/Iggy/include/gdraw.h index 404a2642b..7cc4ddd0e 100644 --- a/Minecraft.Client/PS3/Iggy/include/gdraw.h +++ b/Minecraft.Client/PS3/Iggy/include/gdraw.h @@ -356,13 +356,13 @@ IDOC typedef struct GDrawPrimitive IDOC typedef void RADLINK gdraw_draw_indexed_triangles(GDrawRenderState *r, GDrawPrimitive *prim, GDrawVertexBuffer *buf, GDrawStats *stats); /* Draws a collection of indexed triangles, ignoring special filters or blend modes. - If buf is NULL, then the pointers in 'prim' are machine pointers, and + If buf is nullptr, then the pointers in 'prim' are machine pointers, and you need to make a copy of the data (note currently all triangles implementing strokes (wide lines) go this path). - If buf is non-NULL, then use the appropriate vertex buffer, and the + If buf is non-nullptr, then use the appropriate vertex buffer, and the pointers in prim are actually offsets from the beginning of the - vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) NULL; + vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) nullptr; (note there are separate spaces for vertices and indices; e.g. the first mesh in a given vertex buffer will normally have a 0 offset for the vertices and a 0 offset for the indices) @@ -455,7 +455,7 @@ IDOC typedef GDrawTexture * RADLINK gdraw_make_texture_end(GDraw_MakeTexture_Pro /* Ends specification of a new texture. $:info The same handle initially passed to $gdraw_make_texture_begin - $:return Handle for the newly created texture, or NULL if an error occured + $:return Handle for the newly created texture, or nullptr if an error occured */ IDOC typedef rrbool RADLINK gdraw_update_texture_begin(GDrawTexture *tex, void *unique_id, GDrawStats *stats); diff --git a/Minecraft.Client/PS3/Iggy/include/iggyexpruntime.h b/Minecraft.Client/PS3/Iggy/include/iggyexpruntime.h index 1f1a90a1c..a42ccbfff 100644 --- a/Minecraft.Client/PS3/Iggy/include/iggyexpruntime.h +++ b/Minecraft.Client/PS3/Iggy/include/iggyexpruntime.h @@ -25,8 +25,8 @@ IDOC RADEXPFUNC HIGGYEXP RADEXPLINK IggyExpCreate(char *ip_address, S32 port, vo $:storage A small block of storage that needed to store the $HIGGYEXP, must be at least $IGGYEXP_MIN_STORAGE $:storage_size_in_bytes The size of the block pointer to by storage -Returns a NULL HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer -can be contacted at the specified address/port. Otherwise returns a non-NULL $HIGGYEXP +Returns a nullptr HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer +can be contacted at the specified address/port. Otherwise returns a non-nullptr $HIGGYEXP which you can pass to $IggyUseExplorer. */ IDOC RADEXPFUNC void RADEXPLINK IggyExpDestroy(HIGGYEXP p); diff --git a/Minecraft.Client/PS3/Leaderboards/PS3LeaderboardManager.cpp b/Minecraft.Client/PS3/Leaderboards/PS3LeaderboardManager.cpp index 38380bfb4..274061866 100644 --- a/Minecraft.Client/PS3/Leaderboards/PS3LeaderboardManager.cpp +++ b/Minecraft.Client/PS3/Leaderboards/PS3LeaderboardManager.cpp @@ -30,7 +30,7 @@ PS3LeaderboardManager::PS3LeaderboardManager() m_myXUID = INVALID_XUID; - m_scores = NULL; //m_stats = NULL; + m_scores = nullptr; //m_stats = nullptr; m_statsType = eStatsType_Kills; m_difficulty = 0; @@ -42,7 +42,7 @@ PS3LeaderboardManager::PS3LeaderboardManager() InitializeCriticalSection(&m_csViewsLock); m_running = false; - m_threadScoreboard = NULL; + m_threadScoreboard = nullptr; } PS3LeaderboardManager::~PS3LeaderboardManager() @@ -196,7 +196,7 @@ bool PS3LeaderboardManager::getScoreByIds() CellRtcTick last_sort_date; SceNpScoreRankNumber mTotalRecord; - SceNpId *npIds = NULL; + SceNpId *npIds = nullptr; int ret; @@ -246,7 +246,7 @@ bool PS3LeaderboardManager::getScoreByIds() sceNpScoreDestroyTransactionCtx(ret); - if (npIds != NULL) delete [] npIds; + if (npIds != nullptr) delete [] npIds; return false; } else if (ret < 0) @@ -256,7 +256,7 @@ bool PS3LeaderboardManager::getScoreByIds() m_eStatsState = eStatsState_Failed; - if (npIds != NULL) delete [] npIds; + if (npIds != nullptr) delete [] npIds; return false; } else @@ -270,7 +270,7 @@ bool PS3LeaderboardManager::getScoreByIds() comments = new SceNpScoreComment[num]; /* app.DebugPrintf("sceNpScoreGetRankingByNpId(\n\t transaction=%i,\n\t boardID=0,\n\t npId=%i,\n\t friendCount*sizeof(SceNpId)=%i*%i=%i,\ - rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t NULL, 0, NULL, 0,\n\t friendCount=%i,\n...\n", + rankData=%i,\n\t friendCount*sizeof(SceNpScorePlayerRankData)=%i,\n\t nullptr, 0, nullptr, 0,\n\t friendCount=%i,\n...\n", transaction, npId, friendCount, sizeof(SceNpId), friendCount*sizeof(SceNpId), rankData, friendCount*sizeof(SceNpScorePlayerRankData), friendCount ); */ @@ -285,14 +285,14 @@ bool PS3LeaderboardManager::getScoreByIds() comments, sizeof(SceNpScoreComment) * num, //OUT: Comments - NULL, 0, // GameData. (unused) + nullptr, 0, // GameData. (unused) num, &last_sort_date, &mTotalRecord, - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -319,7 +319,7 @@ bool PS3LeaderboardManager::getScoreByIds() delete [] comments; delete [] npIds; - m_scores = NULL; + m_scores = nullptr; m_readCount = 0; m_maxRank = num; @@ -335,7 +335,7 @@ bool PS3LeaderboardManager::getScoreByIds() m_readCount = num; // Filter scorers and construct output structure. - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_scores = new ReadScore[m_readCount]; convertToOutput(m_readCount, m_scores, ptr, comments); m_maxRank = m_readCount; @@ -368,7 +368,7 @@ error3: delete [] ptr; delete [] comments; error2: - if (npIds != NULL) delete [] npIds; + if (npIds != nullptr) delete [] npIds; error1: if (m_eStatsState != eStatsState_Canceled) m_eStatsState = eStatsState_Failed; app.DebugPrintf("[LeaderboardManger] getScoreByIds() FAILED, ret=0x%X\n", ret); @@ -422,14 +422,14 @@ bool PS3LeaderboardManager::getScoreByRange() comments, sizeof(SceNpScoreComment) * num, //OUT: Comment Data - NULL, 0, // GameData. + nullptr, 0, // GameData. num, &last_sort_date, &m_maxRank, // 'Total number of players registered in the target scoreboard.' - NULL // Reserved, specify null. + nullptr // Reserved, specify null. ); if (ret == SCE_NP_COMMUNITY_ERROR_ABORTED) @@ -454,7 +454,7 @@ bool PS3LeaderboardManager::getScoreByRange() delete [] ptr; delete [] comments; - m_scores = NULL; + m_scores = nullptr; m_readCount = 0; m_eStatsState = eStatsState_Ready; @@ -472,7 +472,7 @@ bool PS3LeaderboardManager::getScoreByRange() //m_stats = ptr; //Maybe: addPadding(num,ptr); - if (m_scores != NULL) delete [] m_scores; + if (m_scores != nullptr) delete [] m_scores; m_readCount = ret; m_scores = new ReadScore[m_readCount]; for (int i=0; i 0) ret = eStatsReturn_Success; - if (m_readListener != NULL) + if (m_readListener != nullptr) { app.DebugPrintf("[LeaderboardManager] OnStatsReadComplete(%i, %i, _), m_readCount=%i.\n", ret, m_maxRank, m_readCount); m_readListener->OnStatsReadComplete(ret, m_maxRank, view); @@ -621,16 +621,16 @@ void PS3LeaderboardManager::Tick() m_eStatsState = eStatsState_Idle; delete [] m_scores; - m_scores = NULL; + m_scores = nullptr; } break; case eStatsState_Failed: { view.m_numQueries = 0; - view.m_queries = NULL; + view.m_queries = nullptr; - if ( m_readListener != NULL ) + if ( m_readListener != nullptr ) m_readListener->OnStatsReadComplete(eStatsReturn_NetworkError, 0, view); m_eStatsState = eStatsState_Idle; @@ -652,7 +652,7 @@ bool PS3LeaderboardManager::OpenSession() { if (m_openSessions == 0) { - if (m_threadScoreboard == NULL) + if (m_threadScoreboard == nullptr) { m_threadScoreboard = new C4JThread(&scoreboardThreadEntry, this, "4JScoreboard"); m_threadScoreboard->SetProcessor(CPU_CORE_LEADERBOARDS); @@ -747,7 +747,7 @@ void PS3LeaderboardManager::FlushStats() {} void PS3LeaderboardManager::CancelOperation() { - m_readListener = NULL; + m_readListener = nullptr; m_eStatsState = eStatsState_Canceled; if (m_transactionCtx != 0) @@ -897,7 +897,7 @@ void PS3LeaderboardManager::fromBase32(void *out, SceNpScoreComment *in) for (int i = 0; i < SCE_NP_SCORE_COMMENT_MAXLEN; i++) { ch[0] = in->data[i]; - unsigned char fivebits = strtol(ch, NULL, 32) << 3; + unsigned char fivebits = strtol(ch, nullptr, 32) << 3; int sByte = (i*5) / 8; int eByte = (5+(i*5)) / 8; @@ -958,7 +958,7 @@ bool PS3LeaderboardManager::test_string(string testing) int ctx = sceNpScoreCreateTransactionCtx(m_titleContext); if (ctx<0) return false; - int ret = sceNpScoreCensorComment(ctx, (const void *) &comment, NULL); + int ret = sceNpScoreCensorComment(ctx, (const void *) &comment, nullptr); if (ret == SCE_NP_COMMUNITY_SERVER_ERROR_CENSORED) { diff --git a/Minecraft.Client/PS3/Media/splashes.txt b/Minecraft.Client/PS3/Media/splashes.txt index 7f7835c6c..df4a4be19 100644 --- a/Minecraft.Client/PS3/Media/splashes.txt +++ b/Minecraft.Client/PS3/Media/splashes.txt @@ -43,7 +43,7 @@ Dungeon! Exclusive! The bee's knees! Down with O.P.P.! -Closed source! +Closed source xD! Classy! Wow! Not on steam! diff --git a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp index 8ab30bebd..a1a57443d 100644 --- a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp +++ b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp @@ -19,8 +19,8 @@ #include "..\PS3Extras\PS3Strings.h" #include "PS3\Network\SonyRemoteStorage_PS3.h" -int (* SQRNetworkManager_PS3::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = NULL; -void * SQRNetworkManager_PS3::s_SignInCompleteParam = NULL; +int (* SQRNetworkManager_PS3::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = nullptr; +void * SQRNetworkManager_PS3::s_SignInCompleteParam = nullptr; SceNpBasicPresenceDetails2 SQRNetworkManager_PS3::s_lastPresenceInfo = { 0 }; int SQRNetworkManager_PS3::s_resendPresenceCountdown = 0; bool SQRNetworkManager_PS3::s_presenceStatusDirty = false; @@ -96,8 +96,8 @@ SQRNetworkManager_PS3::SQRNetworkManager_PS3(ISQRNetworkManagerListener *listene m_isInSession = false; m_offlineGame = false; m_offlineSQR = false; - m_aServerId = NULL; - m_gameBootInvite = NULL; + m_aServerId = nullptr; + m_gameBootInvite = nullptr; m_onlineStatus = false; m_bLinkDisconnected = false; @@ -151,7 +151,7 @@ void SQRNetworkManager_PS3::Initialise() // Initialise RUDP #ifdef __PS3__ - ret = cellRudpInit(NULL); + ret = cellRudpInit(nullptr); #else const int RUDP_POOL_SIZE = (500 * 1024); // TODO - find out what we need, this size is copied from library reference uint8_t *rudp_pool = (uint8_t *)malloc(RUDP_POOL_SIZE); @@ -258,7 +258,7 @@ void SQRNetworkManager_PS3::InitialiseAfterOnline() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } return; } @@ -268,7 +268,7 @@ void SQRNetworkManager_PS3::InitialiseAfterOnline() int ret = 0; if( !m_matching2initialised) { - ret = sceNpMatching2Init2(0, 0, NULL); + ret = sceNpMatching2Init2(0, 0, nullptr); } #else SceNpMatching2InitializeParameter initParam; @@ -339,7 +339,7 @@ void SQRNetworkManager_PS3::Tick() if( ( m_gameBootInvite ) && ( s_safeToRespondToGameBootInvite ) ) { m_listener->HandleInviteReceived( ProfileManager.GetPrimaryPad(), m_gameBootInvite ); - m_gameBootInvite = NULL; + m_gameBootInvite = nullptr; } ErrorHandlingTick(); @@ -399,12 +399,12 @@ void SQRNetworkManager_PS3::Tick() if( s_signInCompleteCallbackIfFailed ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } else if(s_SignInCompleteCallbackFn) { s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } @@ -421,7 +421,7 @@ void SQRNetworkManager_PS3::ErrorHandlingTick() { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } app.DebugPrintf("Network error: SNM_INT_STATE_INITIALISE_FAILED\n"); if( m_isInSession && m_offlineGame) // m_offlineSQR ) // MGH - changed this to m_offlineGame, as m_offlineSQR can be true when running an online game but the init has failed because the servers are down @@ -531,7 +531,7 @@ void SQRNetworkManager_PS3::UpdateExternalRoomData() reqParam.roomBinAttrExternalNum = 1; reqParam.roomBinAttrExternal = &roomBinAttr; - int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SetRoomDataExternal returns 0x%x, number of players %d\n",ret,((char *)m_joinExtData)[174]); if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA ) ) { @@ -564,7 +564,7 @@ bool SQRNetworkManager_PS3::FriendRoomManagerSearch() for( int i = 0; i < m_searchResultCount; i++ ) { free(m_aSearchResultRoomExtDataReceived[i]); - m_aSearchResultRoomExtDataReceived[i] = NULL; + m_aSearchResultRoomExtDataReceived[i] = nullptr; } m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT; @@ -639,7 +639,7 @@ void SQRNetworkManager_PS3::FriendSearchTick() { m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO; delete m_getFriendCountThread; - m_getFriendCountThread = NULL; + m_getFriendCountThread = nullptr; FriendRoomManagerSearch2(); } } @@ -813,7 +813,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerByIndex(int idx) } else { - return NULL; + return nullptr; } } @@ -830,7 +830,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerBySmallId(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerByXuid(PlayerUID xuid) @@ -846,7 +846,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerByXuid(PlayerUID xuid) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_PS3::GetLocalPlayerByUserIndex(int idx) @@ -862,7 +862,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetLocalPlayerByUserIndex(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_PS3::GetHostPlayer() @@ -875,11 +875,11 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetHostPlayer() SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerIfReady(SQRNetworkPlayer *player) { - if( player == NULL ) return NULL; + if( player == nullptr ) return nullptr; if( player->IsReady() ) return player; - return NULL; + return nullptr; } // Update state internally @@ -930,7 +930,7 @@ bool SQRNetworkManager_PS3::JoinRoom(SQRNetworkManager_PS3::SessionSearchResult { // Set up the presence info we would like to synchronise out when we have fully joined the game CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData(&s_lastPresenceSyncInfo, searchResult->m_extData, searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId); - return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, NULL); + return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, nullptr); } // Join room with a specified roomId. This is used when joining from an invite, as well as by the previous method @@ -996,7 +996,7 @@ void SQRNetworkManager_PS3::LeaveRoom(bool bActuallyLeaveRoom) reqParam.roomId = m_room; SetState(SNM_INT_STATE_LEAVING); - int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, NULL, &m_leaveRoomRequestId ); + int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, nullptr, &m_leaveRoomRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_LEAVE_ROOM) ) { SetState(SNM_INT_STATE_LEAVING_FAILED); @@ -1100,7 +1100,7 @@ bool SQRNetworkManager_PS3::AddLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL) ) { @@ -1148,7 +1148,7 @@ bool SQRNetworkManager_PS3::RemoveLocalPlayerByUserIndex(int idx) // And do any adjusting necessary to the mappings from this room data, to the SQRNetworkPlayers. // This will also delete the SQRNetworkPlayer and do all the callbacks that requires etc. MapRoomSlotPlayers(roomSlotPlayerCount); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; // Sync this back out to our networked clients... SyncRoomData(); @@ -1184,7 +1184,7 @@ bool SQRNetworkManager_PS3::RemoveLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2) ) { @@ -1216,7 +1216,7 @@ void SQRNetworkManager_PS3::SendInviteGUI() msg.mainType = SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE; msg.subType = SCE_NP_BASIC_MESSAGE_INVITE_SUBTYPE_ACTION_ACCEPT; msg.msgFeatures = SCE_NP_BASIC_MESSAGE_FEATURES_BOOTABLE; - msg.npids = NULL; + msg.npids = nullptr; msg.count = 0; uint8_t *subject = mallocAndCreateUTF8ArrayFromString(IDS_INVITATION_SUBJECT_MAX_18_CHARS); @@ -1284,7 +1284,7 @@ void SQRNetworkManager_PS3::FindOrCreateNonNetworkPlayer(int slot, int playerTyp } } // Create the player - non-network players can be considered complete as soon as we create them as we aren't waiting on their network connections becoming complete, so can flag them as such and notify via callback - PlayerUID *pUID = NULL; + PlayerUID *pUID = nullptr; PlayerUID localUID; if( ( playerType == SQRNetworkPlayer::SNP_TYPE_LOCAL ) || m_isHosting && ( playerType == SQRNetworkPlayer::SNP_TYPE_HOST ) ) @@ -1351,7 +1351,7 @@ void SQRNetworkManager_PS3::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_REMOTE ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1407,7 +1407,7 @@ void SQRNetworkManager_PS3::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_LOCAL ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1499,7 +1499,7 @@ void SQRNetworkManager_PS3::UpdatePlayersFromRoomSyncUIDs() } // Host only - add remote players to our internal storage of player slots, and synchronise this with other room members. -bool SQRNetworkManager_PS3::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==NULL*/ ) +bool SQRNetworkManager_PS3::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==nullptr*/ ) { assert( m_isHosting ); @@ -1618,7 +1618,7 @@ void SQRNetworkManager_PS3::RemoveRemotePlayersAndSync( SceNpMatching2RoomMember } // Zero last element, that isn't part of the currently sized array anymore memset(&m_roomSyncData.players[m_roomSyncData.getPlayerCount()],0,sizeof(PlayerSyncData)); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; } else { @@ -1660,7 +1660,7 @@ void SQRNetworkManager_PS3::RemoveNetworkPlayers( int mask ) { if( m_aRoomSlotPlayers[i] == player ) { - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } // And delete the reference from the ctx->player map @@ -1711,7 +1711,7 @@ void SQRNetworkManager_PS3::SyncRoomData() roomBinAttr.size = sizeof( m_roomSyncData ); reqParam.roomBinAttrInternalNum = 1; reqParam.roomBinAttrInternal = &roomBinAttr; - sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); } // Check if the matching context is valid, and if not attempt to create one. If to do this requires starting an asynchronous process, then sets the internal state to the state passed in @@ -1724,7 +1724,7 @@ bool SQRNetworkManager_PS3::GetMatchingContext(eSQRNetworkManagerInternalState a int ret = 0; if( !m_matching2initialised) { - ret = sceNpMatching2Init2(0, 0, NULL); + ret = sceNpMatching2Init2(0, 0, nullptr); } if( ret < 0 ) { @@ -1797,7 +1797,7 @@ bool SQRNetworkManager_PS3::GetServerContext() bool SQRNetworkManager_PS3::GetServerContext2() { // Get list of server IDs of servers allocated to the application - int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, NULL, 0 ); + int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, nullptr, 0 ); // If an error is returned here, we need to destroy and recerate our server - if this goes ok we should come back through this path again if( ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_UNAVAILABLE ) || // This error has been seen (occasionally) in a normal working environment ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error @@ -1852,7 +1852,7 @@ bool SQRNetworkManager_PS3::GetServerContext(SceNpMatching2ServerId serverId) { // Get list of server IDs of servers allocated to the application. We don't actually need to do this, but it is as good a way as any to try a matching2 service and check that // the context *really* is valid. - int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, NULL, 0 ); + int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, nullptr, 0 ); // If an error is returned here, we need to destroy and recerate our server - if this goes ok we should come back through this path again if( ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_UNAVAILABLE ) || // This error has been seen (occasionally) in a normal working environment ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error @@ -1906,7 +1906,7 @@ void SQRNetworkManager_PS3::ServerContextTick() reqParam.serverId = m_serverId; SetState((m_state==SNM_INT_STATE_HOSTING_SERVER_FOUND)?SNM_INT_STATE_HOSTING_SERVER_SEARCH_CREATING_CONTEXT:SNM_INT_STATE_JOINING_SERVER_SEARCH_CREATING_CONTEXT); // Found a server - now try and create a context for it - int ret = sceNpMatching2CreateServerContext( m_matchingContext, &reqParam, NULL, &m_serverContextRequestId ); + int ret = sceNpMatching2CreateServerContext( m_matchingContext, &reqParam, nullptr, &m_serverContextRequestId ); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT) ) { SetState((m_state==SNM_INT_STATE_HOSTING_SERVER_FOUND)?SNM_INT_STATE_HOSTING_SERVER_SEARCH_FAILED:SNM_INT_STATE_JOINING_SERVER_SEARCH_FAILED); @@ -1958,7 +1958,7 @@ void SQRNetworkManager_PS3::RoomCreateTick() SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_CREATING_ROOM); app.DebugPrintf(CMinecraftApp::USER_RR,">> Creating room start\n"); s_roomStartTime = System::currentTimeMillis(); - int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, NULL, &m_createRoomRequestId ); + int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, nullptr, &m_createRoomRequestId ); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_JOIN_ROOM) ) { SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED); @@ -2105,7 +2105,7 @@ bool SQRNetworkManager_PS3::SelectRandomServer() // Kick off the search - we'll get a callback to DefaultRequestCallback with the result from this app.DebugPrintf(CMinecraftApp::USER_RR,"Kicking off sceNpMatching2GetServerInfo for server id %d\n",reqParam.serverId); - int ret = sceNpMatching2GetServerInfo( m_matchingContext, &reqParam, NULL, &m_serverSearchRequestId); + int ret = sceNpMatching2GetServerInfo( m_matchingContext, &reqParam, nullptr, &m_serverSearchRequestId); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_GET_SERVER_INFO) ) { // Jump straight to an error state for this server @@ -2125,7 +2125,7 @@ void SQRNetworkManager_PS3::DeleteServerContext() reqParam.serverId = m_serverId; m_serverContextValid = false; SetState(SNM_INT_STATE_SERVER_DELETING_CONTEXT); - int ret = sceNpMatching2DeleteServerContext( m_matchingContext, &reqParam, NULL, &m_serverContextRequestId ); + int ret = sceNpMatching2DeleteServerContext( m_matchingContext, &reqParam, nullptr, &m_serverContextRequestId ); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_DELETE_SERVER_CONTEXT) ) { ResetToIdle(); @@ -2203,7 +2203,7 @@ bool SQRNetworkManager_PS3::CreateRudpConnections(SceNpMatching2RoomId roomId, S if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT) ) return false; if( m_isHosting ) { - m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, NULL ); + m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, nullptr ); } else { @@ -2237,7 +2237,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRudpCtx(int rudpCtx) { return it->second; } - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRoomMemberAndLocalIdx(int roomMember, int localIdx) @@ -2249,7 +2249,7 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRoomMemberAndLocalIdx(int return it->second; } } - return NULL; + return nullptr; } @@ -2342,7 +2342,7 @@ void SQRNetworkManager_PS3::ContextCallback(SceNpMatching2ContextId id, SceNpMa { manager->SetState( SNM_INT_STATE_IDLE ); - manager->GetExtDataForRoom(0, NULL, NULL, NULL); + manager->GetExtDataForRoom(0, nullptr, nullptr, nullptr); break; } @@ -2373,7 +2373,7 @@ void SQRNetworkManager_PS3::ContextCallback(SceNpMatching2ContextId id, SceNpMa // if(s_SignInCompleteCallbackFn) // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); -// s_SignInCompleteCallbackFn = NULL; +// s_SignInCompleteCallbackFn = nullptr; // } @@ -2510,7 +2510,7 @@ void SQRNetworkManager_PS3::DefaultRequestCallback(SceNpMatching2ContextId id, S } } - // If there was some problem getting data, then silently ignore as we don't want to go any further with a NULL data pointer, and this will just be indicating that the networking context + // If there was some problem getting data, then silently ignore as we don't want to go any further with a nullptr data pointer, and this will just be indicating that the networking context // is invalid which will be picked up elsewhere to shut everything down properly if( dataError ) { @@ -2706,7 +2706,7 @@ void SQRNetworkManager_PS3::DefaultRequestCallback(SceNpMatching2ContextId id, S // Set flag to indicate whether we were kicked for being out of room or not reqParam.optData.data[0] = isFull ? 1 : 0; reqParam.optData.len = 1; - int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, NULL, &manager->m_kickRequestId); + int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, nullptr, &manager->m_kickRequestId); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2KickoutRoomMember returns error 0x%x\n",ret); break; } @@ -2814,7 +2814,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM case SCE_NP_MATCHING2_ROOM_EVENT_RoomDestroyed: { SonyVoiceChat::signalRoomDestroyed(); - SceNpMatching2RoomUpdateInfo *pUpdateInfo=NULL; + SceNpMatching2RoomUpdateInfo *pUpdateInfo=nullptr; if( dataSize <= SCE_NP_MATCHING2_EVENT_DATA_MAX_SIZE_RoomUpdateInfo ) { @@ -2937,7 +2937,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, NULL, &manager->m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, nullptr, &manager->m_setRoomMemberInternalDataRequestId ); } } @@ -3037,7 +3037,7 @@ void SQRNetworkManager_PS3::SignallingCallback(SceNpMatching2ContextId ctxId, Sc reqParam.attrId = attrs; reqParam.attrIdNum = 1; - sceNpMatching2GetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, NULL, &manager->m_roomMemberDataRequestId); + sceNpMatching2GetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, nullptr, &manager->m_roomMemberDataRequestId); } else { @@ -3118,7 +3118,7 @@ void SQRNetworkManager_PS3::SysUtilCallback(uint64_t status, uint64_t param, voi { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } return; } @@ -3133,7 +3133,7 @@ void SQRNetworkManager_PS3::SysUtilCallback(uint64_t status, uint64_t param, voi { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } @@ -3204,7 +3204,7 @@ void SQRNetworkManager_PS3::RudpContextCallback(int ctx_id, int event_id, int er if( dataSize >= sizeof(SQRNetworkPlayer::InitSendData) ) { SQRNetworkPlayer::InitSendData ISD; - unsigned int bytesRead = cellRudpRead( ctx_id, &ISD, sizeof(SQRNetworkPlayer::InitSendData), 0, NULL ); + unsigned int bytesRead = cellRudpRead( ctx_id, &ISD, sizeof(SQRNetworkPlayer::InitSendData), 0, nullptr ); if( bytesRead == sizeof(SQRNetworkPlayer::InitSendData) ) { manager->NetworkPlayerInitialDataReceived(playerFrom, &ISD); @@ -3225,7 +3225,7 @@ void SQRNetworkManager_PS3::RudpContextCallback(int ctx_id, int event_id, int er if( dataSize > 0 ) { unsigned char *data = new unsigned char [ dataSize ]; - unsigned int bytesRead = cellRudpRead( ctx_id, data, dataSize, 0, NULL ); + unsigned int bytesRead = cellRudpRead( ctx_id, data, dataSize, 0, nullptr ); if( bytesRead > 0 ) { SQRNetworkPlayer *playerFrom, *playerTo; @@ -3241,7 +3241,7 @@ void SQRNetworkManager_PS3::RudpContextCallback(int ctx_id, int event_id, int er playerFrom = manager->m_aRoomSlotPlayers[0]; playerTo = manager->GetPlayerFromRudpCtx( ctx_id ); } - if( ( playerFrom != NULL ) && ( playerTo != NULL ) ) + if( ( playerFrom != nullptr ) && ( playerTo != nullptr ) ) { manager->m_listener->HandleDataReceived( playerFrom, playerTo, data, bytesRead ); } @@ -3306,7 +3306,7 @@ void SQRNetworkManager_PS3::ServerContextValid_CreateRoom() int ret = -1; if( !ForceErrorPoint(SNM_FORCE_ERROR_GET_WORLD_INFO_LIST) ) { - ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, NULL, &m_getWorldRequestId); + ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, nullptr, &m_getWorldRequestId); } if (ret < 0) { @@ -3335,7 +3335,7 @@ void SQRNetworkManager_PS3::ServerContextValid_JoinRoom() reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, NULL, &m_joinRoomRequestId ); + int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, nullptr, &m_joinRoomRequestId ); if ( (ret < 0) || ForceErrorPoint(SNM_FORCE_ERROR_JOIN_ROOM) ) { if( ret == SCE_NP_MATCHING2_SERVER_ERROR_NAT_TYPE_MISMATCH) @@ -3386,9 +3386,9 @@ void SQRNetworkManager_PS3::GetExtDataForRoom( SceNpMatching2RoomId roomId, void static SceNpMatching2RoomId aRoomId[1]; static SceNpMatching2AttributeId attr[1]; - // All parameters will be NULL if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). - // NULL parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList - if( extData != NULL ) + // All parameters will be nullptr if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). + // nullptr parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList + if( extData != nullptr ) { aRoomId[0] = roomId; attr[0] = SCE_NP_MATCHING2_ROOM_BIN_ATTR_EXTERNAL_1_ID; @@ -3412,14 +3412,14 @@ void SQRNetworkManager_PS3::GetExtDataForRoom( SceNpMatching2RoomId roomId, void return; } - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { app.DebugPrintf("Having to recreate matching context, setting state to SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT\n"); return; } - int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, NULL, &m_roomDataExternalListRequestId ); + int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, nullptr, &m_roomDataExternalListRequestId ); // If we hadn't properly detected that a matching context was unvailable, we might still get an error indicating that it is from the previous call. Handle similarly, but we need // to destroy the context first. @@ -3434,7 +3434,7 @@ void SQRNetworkManager_PS3::GetExtDataForRoom( SceNpMatching2RoomId roomId, void m_FriendSessionUpdatedFn(false, m_pParamFriendSessionUpdated); return; }; - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { return; @@ -3530,7 +3530,7 @@ void SQRNetworkManager_PS3::AttemptPSNSignIn(int (*SignInCompleteCallbackFn)(voi { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } diff --git a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.h b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.h index 6143bbb58..4953b08fa 100644 --- a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.h +++ b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.h @@ -125,7 +125,7 @@ private: void LocalDataSend(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, const void *data, unsigned int dataSize); int GetSessionIndex(SQRNetworkPlayer *player); - bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = NULL ); + bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = nullptr ); void RemoveRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int mask ); void RemoveNetworkPlayers( int mask ); void SetLocalPlayersAndSync(); diff --git a/Minecraft.Client/PS3/Network/SonyCommerce_PS3.cpp b/Minecraft.Client/PS3/Network/SonyCommerce_PS3.cpp index 230e03099..7bd101105 100644 --- a/Minecraft.Client/PS3/Network/SonyCommerce_PS3.cpp +++ b/Minecraft.Client/PS3/Network/SonyCommerce_PS3.cpp @@ -9,22 +9,22 @@ bool SonyCommerce_PS3::m_bCommerceInitialised = false; SceNpCommerce2SessionInfo SonyCommerce_PS3::m_sessionInfo; SonyCommerce_PS3::State SonyCommerce_PS3::m_state = e_state_noSession; int SonyCommerce_PS3::m_errorCode = 0; -LPVOID SonyCommerce_PS3::m_callbackParam = NULL; +LPVOID SonyCommerce_PS3::m_callbackParam = nullptr; -void* SonyCommerce_PS3::m_receiveBuffer = NULL; +void* SonyCommerce_PS3::m_receiveBuffer = nullptr; SonyCommerce_PS3::Event SonyCommerce_PS3::m_event; std::queue SonyCommerce_PS3::m_messageQueue; -std::vector* SonyCommerce_PS3::m_pProductInfoList = NULL; -SonyCommerce_PS3::ProductInfoDetailed* SonyCommerce_PS3::m_pProductInfoDetailed = NULL; -SonyCommerce_PS3::ProductInfo* SonyCommerce_PS3::m_pProductInfo = NULL; +std::vector* SonyCommerce_PS3::m_pProductInfoList = nullptr; +SonyCommerce_PS3::ProductInfoDetailed* SonyCommerce_PS3::m_pProductInfoDetailed = nullptr; +SonyCommerce_PS3::ProductInfo* SonyCommerce_PS3::m_pProductInfo = nullptr; -SonyCommerce_PS3::CategoryInfo* SonyCommerce_PS3::m_pCategoryInfo = NULL; -const char* SonyCommerce_PS3::m_pProductID = NULL; -char* SonyCommerce_PS3::m_pCategoryID = NULL; +SonyCommerce_PS3::CategoryInfo* SonyCommerce_PS3::m_pCategoryInfo = nullptr; +const char* SonyCommerce_PS3::m_pProductID = nullptr; +char* SonyCommerce_PS3::m_pCategoryID = nullptr; SonyCommerce_PS3::CheckoutInputParams SonyCommerce_PS3::m_checkoutInputParams; SonyCommerce_PS3::DownloadListInputParams SonyCommerce_PS3::m_downloadInputParams; -SonyCommerce_PS3::CallbackFunc SonyCommerce_PS3::m_callbackFunc = NULL; +SonyCommerce_PS3::CallbackFunc SonyCommerce_PS3::m_callbackFunc = nullptr; sys_memory_container_t SonyCommerce_PS3::m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; bool SonyCommerce_PS3::m_bUpgradingTrial = false; @@ -40,19 +40,19 @@ bool SonyCommerce_PS3::m_contextCreated=false; ///< npcommerce2 context ID c SonyCommerce_PS3::Phase SonyCommerce_PS3::m_currentPhase = e_phase_stopped; ///< Current commerce2 util char SonyCommerce_PS3::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; -C4JThread* SonyCommerce_PS3::m_tickThread = NULL; +C4JThread* SonyCommerce_PS3::m_tickThread = nullptr; bool SonyCommerce_PS3::m_bLicenseChecked=false; // Check the trial/full license for the game SonyCommerce_PS3::ProductInfoDetailed s_trialUpgradeProductInfoDetailed; void SonyCommerce_PS3::Delete() { - m_pProductInfoList=NULL; - m_pProductInfoDetailed=NULL; - m_pProductInfo=NULL; - m_pCategoryInfo = NULL; - m_pProductID = NULL; - m_pCategoryID = NULL; + m_pProductInfoList=nullptr; + m_pProductInfoDetailed=nullptr; + m_pProductInfo=nullptr; + m_pCategoryInfo = nullptr; + m_pProductID = nullptr; + m_pCategoryID = nullptr; } void SonyCommerce_PS3::Init() { @@ -106,11 +106,11 @@ void SonyCommerce_PS3::CheckForTrialUpgradeKey() // 4J-PB - If we are the blu ray disc then we are the full version if(StorageManager.GetBootTypeDisc()) { - CheckForTrialUpgradeKey_Callback(NULL,true); + CheckForTrialUpgradeKey_Callback(nullptr,true); } else { - StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, NULL); + StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, nullptr); } } @@ -498,7 +498,7 @@ int SonyCommerce_PS3::getDetailedProductInfo(ProductInfoDetailed *pInfo, const c if (categoryId && categoryId[0] != 0) { ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); } else { - ret = sceNpCommerce2GetProductInfoStart(requestId, NULL, productId); + ret = sceNpCommerce2GetProductInfoStart(requestId, nullptr, productId); } if (ret < 0) { sceNpCommerce2DestroyReq(requestId); @@ -766,7 +766,7 @@ int SonyCommerce_PS3::checkout(CheckoutInputParams ¶ms) } } - for (int i = 0; i < params.skuIds.size(); i++) { + for (size_t i = 0; i < params.skuIds.size(); i++) { skuIdsTemp[i] = (const char *)(*iter); iter++; } @@ -794,7 +794,7 @@ int SonyCommerce_PS3::downloadList(DownloadListInputParams ¶ms) } } - for (int i = 0; i < params.skuIds.size(); i++) { + for (size_t i = 0; i < params.skuIds.size(); i++) { skuIdsTemp[i] = (const char *)(*iter); iter++; } @@ -887,7 +887,7 @@ int SonyCommerce_PS3::createContext() } // Create commerce2 context - ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, NULL, &m_contextId); + ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, nullptr, &m_contextId); if (ret < 0) { app.DebugPrintf(4,"createContext sceNpCommerce2CreateCtx problem\n"); @@ -1325,7 +1325,7 @@ void SonyCommerce_PS3::processEvent() m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1349,7 +1349,7 @@ void SonyCommerce_PS3::processEvent() m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1410,8 +1410,8 @@ void SonyCommerce_PS3::CreateSession( CallbackFunc cb, LPVOID lpParam ) EnterCriticalSection(&m_queueLock); setCallback(cb,lpParam); m_messageQueue.push(e_message_commerceCreateSession); - if(m_tickThread == NULL) - m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce_PS3 tick"); + if(m_tickThread == nullptr) + m_tickThread = new C4JThread(TickLoop, nullptr, "SonyCommerce_PS3 tick"); if(m_tickThread->isRunning() == false) { m_currentPhase = e_phase_idle; diff --git a/Minecraft.Client/PS3/Network/SonyCommerce_PS3.h b/Minecraft.Client/PS3/Network/SonyCommerce_PS3.h index 1f43341a0..05b48cf85 100644 --- a/Minecraft.Client/PS3/Network/SonyCommerce_PS3.h +++ b/Minecraft.Client/PS3/Network/SonyCommerce_PS3.h @@ -114,14 +114,14 @@ class SonyCommerce_PS3 : public SonyCommerce { assert(m_callbackFunc); CallbackFunc func = m_callbackFunc; - m_callbackFunc = NULL; + m_callbackFunc = nullptr; if(func) func(m_callbackParam, m_errorCode); m_errorCode = CELL_OK; } static void setCallback(CallbackFunc cb,LPVOID lpParam) { - assert(m_callbackFunc == NULL); + assert(m_callbackFunc == nullptr); m_callbackFunc = cb; m_callbackParam = lpParam; } diff --git a/Minecraft.Client/PS3/Network/SonyHttp_PS3.cpp b/Minecraft.Client/PS3/Network/SonyHttp_PS3.cpp index d38a1bc93..4e681354f 100644 --- a/Minecraft.Client/PS3/Network/SonyHttp_PS3.cpp +++ b/Minecraft.Client/PS3/Network/SonyHttp_PS3.cpp @@ -10,10 +10,10 @@ static const int sc_SSLPoolSize = (512 * 1024U); static const int sc_CookiePoolSize = (256 * 1024U); -void* SonyHttp_PS3::uriPool = NULL; -void* SonyHttp_PS3::httpPool = NULL; -void* SonyHttp_PS3::sslPool = NULL; -void* SonyHttp_PS3::cookiePool = NULL; +void* SonyHttp_PS3::uriPool = nullptr; +void* SonyHttp_PS3::httpPool = nullptr; +void* SonyHttp_PS3::sslPool = nullptr; +void* SonyHttp_PS3::cookiePool = nullptr; CellHttpClientId SonyHttp_PS3::client; CellHttpTransId SonyHttp_PS3::trans; bool SonyHttp_PS3:: bInitialised = false; @@ -22,31 +22,31 @@ bool SonyHttp_PS3:: bInitialised = false; bool SonyHttp_PS3::loadCerts(size_t *numBufPtr, CellHttpsData **caListPtr) { - CellHttpsData *caList = NULL; + CellHttpsData *caList = nullptr; size_t size = 0; int ret = 0; - char *buf = NULL; + char *buf = nullptr; - caList = (CellHttpsData *)malloc(sizeof(CellHttpsData)*2); - if (NULL == caList) { + caList = static_cast(malloc(sizeof(CellHttpsData) * 2)); + if (nullptr == caList) { app.DebugPrintf("failed to malloc cert data"); return false; } - ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, NULL, 0, &size); + ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, nullptr, 0, &size); if (ret < 0) { app.DebugPrintf("cellSslCertifacateLoader() failed(1): 0x%08x", ret); return ret; } - buf = (char*)malloc(size); - if (NULL == buf) { + buf = static_cast(malloc(size)); + if (nullptr == buf) { app.DebugPrintf("failed to malloc cert buffer"); free(caList); return false; } - ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, buf, size, NULL); + ret = cellSslCertificateLoader(CELL_SSL_LOAD_CERT_ALL, buf, size, nullptr); if (ret < 0) { app.DebugPrintf("cellSslCertifacateLoader() failed(2): 0x%08x", ret); free(buf); @@ -72,7 +72,7 @@ bool SonyHttp_PS3::init() /*E startup procedures */ httpPool = malloc(sc_HTTPPoolSize); - if (httpPool == NULL) { + if (httpPool == nullptr) { app.DebugPrintf("failed to malloc libhttp memory pool\n"); return false; } @@ -84,7 +84,7 @@ bool SonyHttp_PS3::init() } cookiePool = malloc(sc_CookiePoolSize); - if (cookiePool == NULL) { + if (cookiePool == nullptr) { app.DebugPrintf("failed to malloc ssl memory pool\n"); return false; } @@ -97,7 +97,7 @@ bool SonyHttp_PS3::init() sslPool = malloc(sc_SSLPoolSize); - if (sslPool == NULL) { + if (sslPool == nullptr) { app.DebugPrintf("failed to malloc ssl memory pool\n"); return false; } @@ -109,7 +109,7 @@ bool SonyHttp_PS3::init() } size_t numBuf = 0; - CellHttpsData *caList = NULL; + CellHttpsData *caList = nullptr; if(!loadCerts(&numBuf, &caList)) return false; @@ -153,18 +153,18 @@ bool SonyHttp_PS3::parseUri(const char* szUri, CellHttpUri& parsedUri) { /*E the main part */ size_t poolSize = 0; - int ret = cellHttpUtilParseUri(NULL, szUri, NULL, 0, &poolSize); + int ret = cellHttpUtilParseUri(nullptr, szUri, nullptr, 0, &poolSize); if (0 > ret) { app.DebugPrintf("error parsing URI... (0x%x)\n\n", ret); return false; } - if (NULL == (uriPool = malloc(poolSize))) + if (nullptr == (uriPool = malloc(poolSize))) { app.DebugPrintf("error mallocing uriPool (%d)\n", poolSize); return false; } - ret = cellHttpUtilParseUri(&parsedUri, szUri, uriPool, poolSize, NULL); + ret = cellHttpUtilParseUri(&parsedUri, szUri, uriPool, poolSize, nullptr); if (0 > ret) { free(uriPool); @@ -185,7 +185,7 @@ void* SonyHttp_PS3::getData(const char* url, int* pDataSize) size_t localRecv = 0; if(!parseUri(url, uri)) - return NULL; + return nullptr; app.DebugPrintf(" scheme: %s\n", uri.scheme); app.DebugPrintf(" hostname: %s\n", uri.hostname); @@ -199,10 +199,10 @@ void* SonyHttp_PS3::getData(const char* url, int* pDataSize) if (0 > ret) { app.DebugPrintf("failed to create http transaction... (0x%x)\n\n", ret); - return NULL; + return nullptr; } - ret = cellHttpSendRequest(trans, NULL, 0, NULL); + ret = cellHttpSendRequest(trans, nullptr, 0, nullptr); if (0 > ret) { app.DebugPrintf("failed to complete http transaction... (0x%x)\n\n", ret); @@ -219,7 +219,7 @@ void* SonyHttp_PS3::getData(const char* url, int* pDataSize) app.DebugPrintf("failed to receive http response... (0x%x)\n\n", ret); cellHttpDestroyTransaction(trans); trans = 0; - return NULL; + return nullptr; } app.DebugPrintf("Status Code is %d\n", code); } @@ -232,19 +232,19 @@ void* SonyHttp_PS3::getData(const char* url, int* pDataSize) app.DebugPrintf("Only supporting data that has a content length : CELL_HTTP_ERROR_NO_CONTENT_LENGTH\n", ret); cellHttpDestroyTransaction(trans); trans = 0; - return NULL; + return nullptr; } else { app.DebugPrintf("error in receiving content length... (0x%x)\n\n", ret); cellHttpDestroyTransaction(trans); trans = 0; - return NULL; + return nullptr; } } int bufferSize = length; - char* buffer = (char*)malloc(bufferSize+1); + char* buffer = static_cast(malloc(bufferSize + 1)); recvd = 0; @@ -261,7 +261,7 @@ void* SonyHttp_PS3::getData(const char* url, int* pDataSize) free(buffer); cellHttpDestroyTransaction(trans); trans = 0; - return NULL; + return nullptr; } else { diff --git a/Minecraft.Client/PS3/Network/SonyRemoteStorage_PS3.cpp b/Minecraft.Client/PS3/Network/SonyRemoteStorage_PS3.cpp index e1d8dffae..ab7b47703 100644 --- a/Minecraft.Client/PS3/Network/SonyRemoteStorage_PS3.cpp +++ b/Minecraft.Client/PS3/Network/SonyRemoteStorage_PS3.cpp @@ -35,7 +35,11 @@ void SonyRemoteStorage_PS3::npauthhandler(int event, int result, void *arg) { psnTicketSize = result; psnTicket = malloc(psnTicketSize); +<<<<<<< HEAD + if (psnTicket == nullptr) +======= if (psnTicket == NULL) +>>>>>>> origin/main { app.DebugPrintf("Failed to allocate for ticket\n"); } @@ -78,7 +82,7 @@ int SonyRemoteStorage_PS3::initPreconditions() cellSysutilCheckCallback(); sys_timer_usleep(50000); //50 milliseconds. } - if(psnTicket == NULL) + if(psnTicket == nullptr) return -1; return 0; @@ -86,7 +90,7 @@ int SonyRemoteStorage_PS3::initPreconditions() void SonyRemoteStorage_PS3::staticInternalCallback(const SceRemoteStorageEvent event, int32_t retCode, void * userData) { - ((SonyRemoteStorage_PS3*)userData)->internalCallback(event, retCode); + static_cast(userData)->internalCallback(event, retCode); } void SonyRemoteStorage_PS3::internalCallback(const SceRemoteStorageEvent event, int32_t retCode) @@ -239,7 +243,7 @@ bool SonyRemoteStorage_PS3::init(CallbackFunc cb, LPVOID lpParam) params.timeout.receiveMs = 120 * 1000; //120 seconds is the default params.timeout.sendMs = 120 * 1000; //120 seconds is the default params.pool.memPoolSize = 7 * 1024 * 1024; - if(m_memPoolBuffer == NULL) + if(m_memPoolBuffer == nullptr) m_memPoolBuffer = malloc(params.pool.memPoolSize); params.pool.memPoolBuffer = m_memPoolBuffer; @@ -343,9 +347,9 @@ bool SonyRemoteStorage_PS3::setDataInternal() bool bHostOptionsRead; DWORD uiTexturePack; char seed[22]; - app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize,(unsigned char *)seed, uiHostOptions, bHostOptionsRead, uiTexturePack); + app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize,reinterpret_cast(seed), uiHostOptions, bHostOptionsRead, uiTexturePack); - int64_t iSeed = strtoll(seed,NULL,10); + int64_t iSeed = strtoll(seed, nullptr,10); char seedHex[17]; sprintf(seedHex,"%016llx",iSeed); memcpy(descData.m_seed,seedHex,16); // Don't copy null @@ -430,20 +434,20 @@ void SonyRemoteStorage_PS3::runCallback() int SonyRemoteStorage_PS3::SaveCompressCallback(LPVOID lpParam,bool bRes) { - SonyRemoteStorage_PS3* pRS = (SonyRemoteStorage_PS3*)lpParam; + SonyRemoteStorage_PS3* pRS = static_cast(lpParam); pRS->m_compressedSaveState = e_state_Idle; return 0; } int SonyRemoteStorage_PS3::LoadCompressCallback(void *pParam,bool bIsCorrupt, bool bIsOwner) { - SonyRemoteStorage_PS3* pRS = (SonyRemoteStorage_PS3*)pParam; + SonyRemoteStorage_PS3* pRS = static_cast(pParam); int origFilesize = StorageManager.GetSaveSize(); void* pOrigSaveData = malloc(origFilesize); unsigned int retFilesize; StorageManager.GetSaveData( pOrigSaveData, &retFilesize ); // check if this save file is already compressed - if(*((int*)pOrigSaveData) != 0) + if(*static_cast(pOrigSaveData) != 0) { app.DebugPrintf("compressing save data\n"); @@ -451,7 +455,7 @@ int SonyRemoteStorage_PS3::LoadCompressCallback(void *pParam,bool bIsCorrupt, bo // We add 4 bytes to the start so that we can signal compressed data // And another 4 bytes to store the decompressed data size unsigned int compLength = origFilesize+8; - byte *compData = (byte *)malloc( compLength ); + byte *compData = static_cast(malloc(compLength)); Compression::UseDefaultThreadStorage(); Compression::getCompression()->Compress(compData+8,&compLength,pOrigSaveData,origFilesize); ZeroMemory(compData,8); diff --git a/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp b/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp index 41c52bed9..7a4d95aa2 100644 --- a/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp +++ b/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp @@ -49,7 +49,7 @@ void SonyVoiceChat::init( SQRNetworkManager_PS3* pNetMan ) sm_pNetworkManager = pNetMan; setState(AVC_STATE_CHAT_INIT); - ProfileManager.GetChatAndContentRestrictions(0,false,&sm_isChatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(0,false,&sm_isChatRestricted,nullptr,nullptr); } void SonyVoiceChat::shutdown() @@ -225,11 +225,11 @@ void SonyVoiceChat::eventcb( CellSysutilAvc2EventId event_id, CellSysutilAvc2Eve { CELL_AVC2_EVENT_LEAVE_FAILED, eventcb_leave }, { CELL_AVC2_EVENT_UNLOAD_SUCCEEDED, eventcb_unload }, { CELL_AVC2_EVENT_UNLOAD_FAILED, eventcb_unload }, - { CELL_AVC2_EVENT_SYSTEM_NEW_MEMBER_JOINED, NULL }, - { CELL_AVC2_EVENT_SYSTEM_MEMBER_LEFT, NULL }, - { CELL_AVC2_EVENT_SYSTEM_SESSION_ESTABLISHED, NULL }, - { CELL_AVC2_EVENT_SYSTEM_SESSION_CANNOT_ESTABLISHED,NULL }, - { CELL_AVC2_EVENT_SYSTEM_SESSION_DISCONNECTED, NULL }, + { CELL_AVC2_EVENT_SYSTEM_NEW_MEMBER_JOINED, nullptr }, + { CELL_AVC2_EVENT_SYSTEM_MEMBER_LEFT, nullptr }, + { CELL_AVC2_EVENT_SYSTEM_SESSION_ESTABLISHED, nullptr }, + { CELL_AVC2_EVENT_SYSTEM_SESSION_CANNOT_ESTABLISHED,nullptr }, + { CELL_AVC2_EVENT_SYSTEM_SESSION_DISCONNECTED, nullptr }, { CELL_AVC2_EVENT_SYSTEM_VOICE_DETECTED, eventcb_voiceDetected }, }; @@ -258,7 +258,7 @@ int SonyVoiceChat::load() ret = cellSysutilAvc2LoadAsync( sm_pNetworkManager->m_matchingContext, SYS_MEMORY_CONTAINER_ID_INVALID, eventcb, - NULL, + nullptr, &g_chat_avc2param ); if( ret != CELL_OK ) { diff --git a/Minecraft.Client/PS3/PS3Extras/C4JSpursJob.cpp b/Minecraft.Client/PS3/PS3Extras/C4JSpursJob.cpp index fd8ddd9ad..bce76078f 100644 --- a/Minecraft.Client/PS3/PS3Extras/C4JSpursJob.cpp +++ b/Minecraft.Client/PS3/PS3Extras/C4JSpursJob.cpp @@ -16,13 +16,13 @@ static const unsigned int NUM_SUBMIT_JOBS = 128; #define DMA_ALIGNMENT (128) #define JOBHEADER_SYMBOL(JobName) _binary_jqjob_##JobName##_jobbin2_jobheader -C4JSpursJobQueue* C4JSpursJobQueue::m_pMainJobQueue = NULL; +C4JSpursJobQueue* C4JSpursJobQueue::m_pMainJobQueue = nullptr; uint16_t C4JSpursJobQueue::Port::s_jobTagBitmask = 0; -C4JSpursJobQueue::Port* C4JSpursJobQueue::Port::s_allocatedPorts[16] = {NULL,NULL,NULL,NULL, - NULL,NULL,NULL,NULL, - NULL,NULL,NULL,NULL, - NULL,NULL,NULL,NULL }; +C4JSpursJobQueue::Port* C4JSpursJobQueue::Port::s_allocatedPorts[16] = {nullptr,nullptr,nullptr,nullptr, + nullptr,nullptr,nullptr,nullptr, + nullptr,nullptr,nullptr,nullptr, + nullptr,nullptr,nullptr,nullptr }; bool C4JSpursJobQueue::Port::s_initialised; CRITICAL_SECTION C4JSpursJobQueue::Port::s_lock; @@ -43,7 +43,7 @@ C4JSpursJobQueue::C4JSpursJobQueue() //E create jobQueue pJobQueue = (JobQueue*)memalign(CELL_SPURS_JOBQUEUE_ALIGN, sizeof(JobQueue)); - assert(pJobQueue != NULL); + assert(pJobQueue != nullptr); ret = JobQueue::create( pJobQueue, spurs, @@ -168,7 +168,7 @@ int C4JSpursJobQueue::Port::getFreeJobTag() void C4JSpursJobQueue::Port::releaseJobTag( int tag ) { s_jobTagBitmask &= ~(1< *pJobQueue; public: - static C4JSpursJobQueue& getMainJobQueue() {if(m_pMainJobQueue == NULL) m_pMainJobQueue = new C4JSpursJobQueue; return *m_pMainJobQueue;} + static C4JSpursJobQueue& getMainJobQueue() {if(m_pMainJobQueue == nullptr) m_pMainJobQueue = new C4JSpursJobQueue; return *m_pMainJobQueue;} C4JSpursJobQueue(); void shutdown(); diff --git a/Minecraft.Client/PS3/PS3Extras/C4JThread_SPU.cpp b/Minecraft.Client/PS3/PS3Extras/C4JThread_SPU.cpp index 94d7ef87d..56dd98783 100644 --- a/Minecraft.Client/PS3/PS3Extras/C4JThread_SPU.cpp +++ b/Minecraft.Client/PS3/PS3Extras/C4JThread_SPU.cpp @@ -17,7 +17,7 @@ static const bool sc_verbose = true; -cell::Spurs::Spurs2* C4JThread_SPU::ms_spurs2Object = NULL; +cell::Spurs::Spurs2* C4JThread_SPU::ms_spurs2Object = nullptr; void C4JThread_SPU::initSPURS() { diff --git a/Minecraft.Client/PS3/PS3Extras/EdgeZLib.cpp b/Minecraft.Client/PS3/PS3Extras/EdgeZLib.cpp index 2b0a523fe..53a8639d4 100644 --- a/Minecraft.Client/PS3/PS3Extras/EdgeZLib.cpp +++ b/Minecraft.Client/PS3/PS3Extras/EdgeZLib.cpp @@ -3,7 +3,7 @@ #include "EdgeZLib.h" #include "edge/zlib/edgezlib_ppu.h" -static CellSpurs* s_pSpurs = NULL; +static CellSpurs* s_pSpurs = nullptr; //Set this to 5 if you want deflate/inflate to run in parallel on 5 SPUs. @@ -12,7 +12,7 @@ const uint32_t kMaxNumDeflateQueueEntries = 64; static CellSpursEventFlag s_eventFlagDeflate; //Cannot be on stack static CellSpursTaskset s_taskSetDeflate; //Cannot be on stack static EdgeZlibDeflateQHandle s_deflateQueue; -static void* s_pDeflateQueueBuffer = NULL; +static void* s_pDeflateQueueBuffer = nullptr; static void* s_pDeflateTaskContext[kNumDeflateTasks]; static uint32_t s_numElementsToCompress; //Cannot be on stack @@ -22,7 +22,7 @@ const uint32_t kMaxNumInflateQueueEntries = 64; static CellSpursEventFlag s_eventFlagInflate; //Cannot be on stack static CellSpursTaskset s_taskSetInflate; //Cannot be on stack static EdgeZlibInflateQHandle s_inflateQueue; -static void* s_pInflateQueueBuffer = NULL; +static void* s_pInflateQueueBuffer = nullptr; static void* s_pInflateTaskContext[kNumInflateTasks]; static uint32_t s_numElementsToDecompress; //Cannot be on stack @@ -195,9 +195,9 @@ bool EdgeZLib::Compress(void* pDestination, uint32_t* pDestSize, const void* pSo // The Deflate Task will wake up and process this work. // ////////////////////////////////////////////////////////////////////////// - uint32_t* pDst = NULL; + uint32_t* pDst = nullptr; bool findingSizeOnly = false; - if(pDestination == NULL && *pDestSize == 0) + if(pDestination == nullptr && *pDestSize == 0) { pDst = (uint32_t*)malloc(SrcSize); findingSizeOnly = true; diff --git a/Minecraft.Client/PS3/PS3Extras/PS3Strings.cpp b/Minecraft.Client/PS3/PS3Extras/PS3Strings.cpp index 03d916ab4..442aab06f 100644 --- a/Minecraft.Client/PS3/PS3Extras/PS3Strings.cpp +++ b/Minecraft.Client/PS3/PS3Extras/PS3Strings.cpp @@ -13,18 +13,18 @@ uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) if( (cd = l10n_get_converter( L10N_UTF16, L10N_UTF8 )) == -1 ) { app.DebugPrintf("l10n_get_converter: no such converter\n"); - return NULL; + return nullptr; } - l10n_convert_str( cd, wchString, &src_len, NULL, &dst_len ); - uint8_t *strUtf8=(uint8_t *)malloc(dst_len); + l10n_convert_str( cd, wchString, &src_len, nullptr, &dst_len ); + uint8_t *strUtf8=static_cast(malloc(dst_len)); memset(strUtf8,0,dst_len); result = l10n_convert_str( cd, wchString, &src_len, strUtf8, &dst_len ); if( result != ConversionOK ) { app.DebugPrintf("l10n_convert: conversion error : 0x%x\n", result); - return NULL; + return nullptr; } return strUtf8; diff --git a/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp b/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp index 4143c555c..c11a85937 100644 --- a/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp +++ b/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp @@ -74,8 +74,8 @@ int _wcsicmp( const wchar_t * dst, const wchar_t * src ) wchar_t f,l; // validation section - // _VALIDATE_RETURN(dst != NULL, EINVAL, _NLSCMPERROR); - // _VALIDATE_RETURN(src != NULL, EINVAL, _NLSCMPERROR); + // _VALIDATE_RETURN(dst != nullptr, EINVAL, _NLSCMPERROR); + // _VALIDATE_RETURN(src != nullptr, EINVAL, _NLSCMPERROR); do { f = towlower(*dst); @@ -90,7 +90,7 @@ size_t wcsnlen(const wchar_t *wcs, size_t maxsize) { size_t n; -// Note that we do not check if s == NULL, because we do not +// Note that we do not check if s == nullptr, because we do not // return errno_t... for (n = 0; n < maxsize && *wcs; n++, wcs++) @@ -134,7 +134,7 @@ VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) lpSystemTime->wMilliseconds = cellRtcGetMicrosecond(&dateTime)/1000; } -HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { PS3_STUBBED; return NULL; } +HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { PS3_STUBBED; return nullptr; } VOID Sleep(DWORD dwMilliseconds) { C4JThread::Sleep(dwMilliseconds); @@ -267,8 +267,8 @@ BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) { return TLSStoragePS3::In LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { int err; - sys_addr_t newAddress = NULL; - if(lpAddress == NULL) + sys_addr_t newAddress = nullptr; + if(lpAddress == nullptr) { // reserve, and possibly commit also int commitSize = 0; @@ -382,7 +382,7 @@ BOOL SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHi int fd = (int) hFile; uint64_t pos = 0, bitsToMove = (int64_t) lDistanceToMove; - if (lpDistanceToMoveHigh != NULL) + if (lpDistanceToMoveHigh != nullptr) bitsToMove |= ((uint64_t) (*lpDistanceToMoveHigh)) << 32; int whence = 0; @@ -490,7 +490,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, } else { - err = cellFsOpen(filePath, flags, &fd ,NULL, 0); + err = cellFsOpen(filePath, flags, &fd ,nullptr, 0); iFilesOpen++; //printf("\n\nFiles Open - %d\n\n",iFilesOpen); } @@ -675,7 +675,7 @@ errno_t _i64toa_s(int64_t _Val, char * _DstBuf, size_t _Size, int _Radix) { if(_ int _wtoi(const wchar_t *_Str) { - return wcstol(_Str, NULL, 10); + return wcstol(_Str, nullptr, 10); } diff --git a/Minecraft.Client/PS3/PS3Extras/ShutdownManager.cpp b/Minecraft.Client/PS3/PS3Extras/ShutdownManager.cpp index e7eca53f4..a04e45d9f 100644 --- a/Minecraft.Client/PS3/PS3Extras/ShutdownManager.cpp +++ b/Minecraft.Client/PS3/PS3Extras/ShutdownManager.cpp @@ -16,12 +16,12 @@ C4JThread::EventArray *ShutdownManager::s_eventArray[eThreadIdCount]; void ShutdownManager::Initialise() { #ifdef __PS3__ - cellSysutilRegisterCallback( 1, SysUtilCallback, NULL ); + cellSysutilRegisterCallback( 1, SysUtilCallback, nullptr ); for( int i = 0; i < eThreadIdCount; i++ ) { s_threadShouldRun[i] = true; s_threadRunning[i] = 0; - s_eventArray[i] = NULL; + s_eventArray[i] = nullptr; } // Special case for storage manager, which we will manually set now to be considered as running - this will be unset by StorageManager.ExitRequest if required s_threadRunning[eStorageManagerThreads] = true; diff --git a/Minecraft.Client/PS3/PS3Extras/TLSStorage.cpp b/Minecraft.Client/PS3/PS3Extras/TLSStorage.cpp index 0906802df..a3b09d6d1 100644 --- a/Minecraft.Client/PS3/PS3Extras/TLSStorage.cpp +++ b/Minecraft.Client/PS3/PS3Extras/TLSStorage.cpp @@ -4,7 +4,7 @@ -TLSStoragePS3* TLSStoragePS3::m_pInstance = NULL; +TLSStoragePS3* TLSStoragePS3::m_pInstance = nullptr; BOOL TLSStoragePS3::m_activeList[sc_maxSlots]; __thread LPVOID TLSStoragePS3::m_values[sc_maxSlots]; @@ -16,7 +16,7 @@ TLSStoragePS3::TLSStoragePS3() for(int i=0;ichDLCKeyname,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,pDLCInfo->chDLCKeyname,sizeof(char)*uiVal,&bytesRead,nullptr); - WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,nullptr); app.DebugPrintf("DLC title %s\n",chDLCTitle); - WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,nullptr); // push this into a vector @@ -345,7 +345,7 @@ void CConsoleMinecraftApp::FatalLoadError() } app.DebugPrintf("Requesting Message Box for Fatal Error\n"); - EMsgBoxResult eResult=InputManager.RequestMessageBox(EMSgBoxType_None,0,NULL,this,(char *)u8Message,0); + EMsgBoxResult eResult=InputManager.RequestMessageBox(EMSgBoxType_None,0,nullptr,this,(char *)u8Message,0); while ((eResult==EMsgBox_Busy) || (eResult==EMsgBox_SysUtilBusy)) { @@ -359,7 +359,7 @@ void CConsoleMinecraftApp::FatalLoadError() _Exit(0); } app.DebugPrintf("Requesting Message Box for Fatal Error again due to BUSY\n"); - eResult=InputManager.RequestMessageBox(EMSgBoxType_None,0,NULL,this,(char *)u8Message,0); + eResult=InputManager.RequestMessageBox(EMSgBoxType_None,0,nullptr,this,(char *)u8Message,0); } while(1) @@ -483,7 +483,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() { ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // From CScene_Main::RunPlayGame Minecraft *pMinecraft=Minecraft::GetInstance(); @@ -521,7 +521,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() #ifdef SAVE_GAME_TO_LOAD param->saveData = LoadSaveFromDisk(wstring(SAVE_GAME_TO_LOAD)); #else - param->saveData = NULL; + param->saveData = nullptr; #endif app.SetGameHostOption(eGameHostOption_Difficulty,0); app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); @@ -728,7 +728,7 @@ SonyCommerce::CategoryInfo *CConsoleMinecraftApp::GetCategoryInfo() { if(m_bCommerceCategoriesRetrieved==false) { - return NULL; + return nullptr; } return &m_CategoryInfo; @@ -742,10 +742,10 @@ void CConsoleMinecraftApp::ClearCommerceDetails() pProductList->clear(); } - if(m_ProductListA!=NULL) + if(m_ProductListA!=nullptr) { delete [] m_ProductListA; - m_ProductListA=NULL; + m_ProductListA=nullptr; } m_ProductListRetrievedC=0; @@ -769,7 +769,7 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch // find the DLC for(int i=0;i* pProductList=&m_ProductListA[i]; auto itEnd = pProductList->end(); @@ -831,7 +831,7 @@ std::vector* CConsoleMinecraftApp::GetProductList(int { if((m_bCommerceProductListRetrieved==false) || (m_bProductListAdditionalDetailsRetrieved==false) ) { - return NULL; + return nullptr; } return &m_ProductListA[iIndex]; @@ -842,7 +842,7 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) // find the DLC for(int i=0;i* pProductList=&m_ProductListA[i]; auto itEnd = pProductList->end(); @@ -1181,7 +1181,7 @@ char *PatchFilelist[] = - NULL + nullptr }; bool CConsoleMinecraftApp::IsFileInPatchList(LPCSTR lpFileName) @@ -1226,7 +1226,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); bool bEmptyStore=true; - if(pCategories!=NULL) + if(pCategories!=nullptr) { if(pCategories->countOfProducts>0) { diff --git a/Minecraft.Client/PS3/PS3_App.h b/Minecraft.Client/PS3/PS3_App.h index d1ecdb6f5..f9293b6fd 100644 --- a/Minecraft.Client/PS3/PS3_App.h +++ b/Minecraft.Client/PS3/PS3_App.h @@ -88,7 +88,7 @@ public: // void SetVoiceChatAndUGCRestricted(bool bRestricted); // bool GetVoiceChatAndUGCRestricted(void); - StringTable *GetStringTable() { return NULL;} + StringTable *GetStringTable() { return nullptr;} // original code virtual void TemporaryCreateGameStart(); diff --git a/Minecraft.Client/PS3/PS3_Minecraft.cpp b/Minecraft.Client/PS3/PS3_Minecraft.cpp index 0ddf48514..07fe57d10 100644 --- a/Minecraft.Client/PS3/PS3_Minecraft.cpp +++ b/Minecraft.Client/PS3/PS3_Minecraft.cpp @@ -359,9 +359,9 @@ void MemSect(int sect) #endif -ID3D11Device* g_pd3dDevice = NULL; -ID3D11DeviceContext* g_pImmediateContext = NULL; -IDXGISwapChain* g_pSwapChain = NULL; +ID3D11Device* g_pd3dDevice = nullptr; +ID3D11DeviceContext* g_pImmediateContext = nullptr; +IDXGISwapChain* g_pSwapChain = nullptr; bool g_bBootedFromInvite = false; //-------------------------------------------------------------------------------------- @@ -423,7 +423,7 @@ static void * load_file( char const * name ) void debugSaveGameDirect() { - C4JThread* thread = new C4JThread(&IUIScene_PauseMenu::SaveWorldThreadProc, NULL, "debugSaveGameDirect"); + C4JThread* thread = new C4JThread(&IUIScene_PauseMenu::SaveWorldThreadProc, nullptr, "debugSaveGameDirect"); thread->Run(); thread->WaitForCompletion(1000); } @@ -450,7 +450,7 @@ int simpleMessageBoxCallback( UINT uiTitle, UINT uiText, ui.RequestMessageBox( uiTitle, uiText, uiOptionA, uiOptionC, dwPad, Func, lpParam, app.GetStringTable(), - NULL, 0 + nullptr, 0 ); return 0; @@ -636,7 +636,7 @@ int LoadSysModules() DEBUG_PRINTF("contentInfoPath - %s\n",contentInfoPath); DEBUG_PRINTF("usrdirPath - %s\n",usrdirPath); - ret=cellGamePatchCheck(&sizeBD,NULL); + ret=cellGamePatchCheck(&sizeBD,nullptr); if(ret < 0) { DEBUG_PRINTF("cellGamePatchCheck() Error: 0x%x\n", ret); @@ -842,7 +842,7 @@ int main() else ui.init(1280,480); - app.CommerceInit(); // MGH - moved this here so GetCommerce isn't NULL + app.CommerceInit(); // MGH - moved this here so GetCommerce isn't nullptr // 4J-PB - Kick of the check for trial or full version - requires ui to be initialised app.GetCommerce()->CheckForTrialUpgradeKey(); @@ -865,7 +865,7 @@ int main() } // Create an XAudio2 mastering voice (utilized by XHV2 when voice data is mixed to main speakers) - hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, NULL); + hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, nullptr); if ( FAILED( hr ) ) { app.DebugPrintf( "Creating XAudio2 mastering voice failed (err = 0x%08x)!\n", hr ); @@ -980,24 +980,24 @@ int main() free(szTemp); StorageManager.SetDefaultImages((PBYTE)baOptionsIcon.data, baOptionsIcon.length,(PBYTE)baSaveImage.data, baSaveImage.length,(PBYTE)baSaveThumbnail.data, baSaveThumbnail.length); - if(baOptionsIcon.data!=NULL) + if(baOptionsIcon.data!=nullptr) { delete [] baOptionsIcon.data; } - if(baSaveThumbnail.data!=NULL) + if(baSaveThumbnail.data!=nullptr) { delete [] baSaveThumbnail.data; } - if(baSaveImage.data!=NULL) + if(baSaveImage.data!=nullptr) { delete [] baSaveImage.data; } wstring wsName=L"Graphics\\SaveChest.png"; byteArray baSaveLoadIcon = app.getArchiveFile(wsName); - if(baSaveLoadIcon.data!=NULL) + if(baSaveLoadIcon.data!=nullptr) { StorageManager.SetSaveLoadIcon((PBYTE)baSaveLoadIcon.data, baSaveLoadIcon.length); delete [] baSaveLoadIcon.data; @@ -1042,7 +1042,7 @@ int main() }*/ // set the achievement text for a trial achievement, now we have the string table loaded - ProfileManager.SetTrialTextStringTable(NULL, IDS_CONFIRM_OK, IDS_CONFIRM_CANCEL); + ProfileManager.SetTrialTextStringTable(nullptr, IDS_CONFIRM_OK, IDS_CONFIRM_CANCEL); ProfileManager.SetTrialAwardText(eAwardType_Achievement,IDS_UNLOCK_TITLE,IDS_UNLOCK_ACHIEVEMENT_TEXT); #ifndef __PS3__ ProfileManager.SetTrialAwardText(eAwardType_GamerPic,IDS_UNLOCK_TITLE,IDS_UNLOCK_GAMERPIC_TEXT); @@ -1112,7 +1112,7 @@ int main() // It's ok to do this for the primary PSN player here - it has this data locally. All other players need to do it on PSN sign in. // bool bChatRestricted=false; -// ProfileManager.GetChatAndContentRestrictions(0,&bChatRestricted,NULL,NULL); +// ProfileManager.GetChatAndContentRestrictions(0,&bChatRestricted,nullptr,nullptr); // 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; @@ -1201,7 +1201,7 @@ int main() else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); @@ -1372,7 +1372,7 @@ vector vRichPresenceStrings; uint8_t * AddRichPresenceString(int iID) { uint8_t *strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); - if( strUtf8 != NULL ) + if( strUtf8 != nullptr ) { vRichPresenceStrings.push_back(strUtf8); } @@ -1382,7 +1382,7 @@ uint8_t * AddRichPresenceString(int iID) void FreeRichPresenceStrings() { uint8_t *strUtf8; - for(int i=0;igetData(x, y, z); int dir = data & 7; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CakeTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CakeTile_SPU.h index 07eb3d86f..e617e84cf 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CakeTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CakeTile_SPU.h @@ -5,7 +5,7 @@ class CakeTile_SPU : public Tile_SPU { public: CakeTile_SPU(int id) : Tile_SPU(id) {} - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { int d = level->getData(x, y, z); float r = 1 / 16.0f; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CauldronTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CauldronTile_SPU.h index 2854b48bb..199fceb6c 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CauldronTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/CauldronTile_SPU.h @@ -6,7 +6,7 @@ class CauldronTile_SPU : public Tile_SPU { public: CauldronTile_SPU(int id) : Tile_SPU(id) {} - virtual Icon_SPU *getTexture(int face, int data) { return NULL; } + virtual Icon_SPU *getTexture(int face, int data) { return nullptr; } //@Override // virtual void updateDefaultShape(); virtual bool isSolidRender(bool isServerLevel = false) { return false; } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ChunkRebuildData.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ChunkRebuildData.cpp index 1cb5e2eec..ac71c572a 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ChunkRebuildData.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ChunkRebuildData.cpp @@ -241,12 +241,12 @@ void ChunkRebuildData::createTileData() m_tileData.signalSource.set(i, Tile::tiles[i]->isSignalSource()); m_tileData.cubeShaped.set(i, Tile::tiles[i]->isCubeShaped()); - m_tileData.xx0[i] = (float)Tile::tiles[i]->getShapeX0(); - m_tileData.yy0[i] = (float)Tile::tiles[i]->getShapeY0(); - m_tileData.zz0[i] = (float)Tile::tiles[i]->getShapeZ0(); - m_tileData.xx1[i] = (float)Tile::tiles[i]->getShapeX1(); - m_tileData.yy1[i] = (float)Tile::tiles[i]->getShapeY1(); - m_tileData.zz1[i] = (float)Tile::tiles[i]->getShapeZ1(); + m_tileData.xx0[i] = static_cast(Tile::tiles[i]->getShapeX0()); + m_tileData.yy0[i] = static_cast(Tile::tiles[i]->getShapeY0()); + m_tileData.zz0[i] = static_cast(Tile::tiles[i]->getShapeZ0()); + m_tileData.xx1[i] = static_cast(Tile::tiles[i]->getShapeX1()); + m_tileData.yy1[i] = static_cast(Tile::tiles[i]->getShapeY1()); + m_tileData.zz1[i] = static_cast(Tile::tiles[i]->getShapeZ1()); Icon* pTex = Tile::tiles[i]->icon; if(pTex) { @@ -269,17 +269,17 @@ void ChunkRebuildData::createTileData() setIconSPUFromIcon(&m_tileData.grass_iconSideOverlay, Tile::grass->iconSideOverlay); // ThinFence - setIconSPUFromIcon(&m_tileData.ironFence_EdgeTexture, ((ThinFenceTile*)Tile::ironFence)->getEdgeTexture()); - setIconSPUFromIcon(&m_tileData.thinGlass_EdgeTexture, ((ThinFenceTile*)Tile::thinGlass)->getEdgeTexture()); + setIconSPUFromIcon(&m_tileData.ironFence_EdgeTexture, static_cast(Tile::ironFence)->getEdgeTexture()); + setIconSPUFromIcon(&m_tileData.thinGlass_EdgeTexture, static_cast(Tile::thinGlass)->getEdgeTexture()); //FarmTile - setIconSPUFromIcon(&m_tileData.farmTile_Dry, ((FarmTile*)Tile::farmland)->iconDry); - setIconSPUFromIcon(&m_tileData.farmTile_Wet, ((FarmTile*)Tile::farmland)->iconWet); + setIconSPUFromIcon(&m_tileData.farmTile_Dry, static_cast(Tile::farmland)->iconDry); + setIconSPUFromIcon(&m_tileData.farmTile_Wet, static_cast(Tile::farmland)->iconWet); // DoorTile for(int i=0;i<8; i++) { - setIconSPUFromIcon(&m_tileData.doorTile_Icons[i], ((DoorTile*)Tile::door_wood)->icons[i]); + setIconSPUFromIcon(&m_tileData.doorTile_Icons[i], static_cast(Tile::door_wood)->icons[i]); // we're not supporting flipped icons, so manually flip here if(i>=4) m_tileData.doorTile_Icons[i].flipHorizontal(); @@ -291,20 +291,20 @@ void ChunkRebuildData::createTileData() // SandStoneTile for(int i=0;i<3; i++) - setIconSPUFromIcon(&m_tileData.sandStone_icons[i], ((SandStoneTile*)Tile::sandStone)->icons[i]); - setIconSPUFromIcon(&m_tileData.sandStone_iconTop, ((SandStoneTile*)Tile::sandStone)->iconTop); - setIconSPUFromIcon(&m_tileData.sandStone_iconBottom, ((SandStoneTile*)Tile::sandStone)->iconBottom); + setIconSPUFromIcon(&m_tileData.sandStone_icons[i], static_cast(Tile::sandStone)->icons[i]); + setIconSPUFromIcon(&m_tileData.sandStone_iconTop, static_cast(Tile::sandStone)->iconTop); + setIconSPUFromIcon(&m_tileData.sandStone_iconBottom, static_cast(Tile::sandStone)->iconBottom); // WoodTile // assert(WoodTile_SPU::WOOD_NAMES_LENGTH == 4); for(int i=0;i<4; i++) - setIconSPUFromIcon(&m_tileData.woodTile_icons[i], ((WoodTile*)Tile::wood)->icons[i]); + setIconSPUFromIcon(&m_tileData.woodTile_icons[i], static_cast(Tile::wood)->icons[i]); // TreeTile // assert(TreeTile_SPU::TREE_NAMES_LENGTH == 4); for(int i=0;i<4; i++) - setIconSPUFromIcon(&m_tileData.treeTile_icons[i], ((TreeTile*)Tile::treeTrunk)->icons[i]); - setIconSPUFromIcon(&m_tileData.treeTile_iconTop, ((TreeTile*)Tile::treeTrunk)->iconTop); + setIconSPUFromIcon(&m_tileData.treeTile_icons[i], static_cast(Tile::treeTrunk)->icons[i]); + setIconSPUFromIcon(&m_tileData.treeTile_iconTop, static_cast(Tile::treeTrunk)->iconTop); // LeafTile for(int i=0;i<2; i++) @@ -313,12 +313,12 @@ void ChunkRebuildData::createTileData() // CropTile for(int i=0;i<8; i++) - setIconSPUFromIcon(&m_tileData.cropTile_icons[i], ((CropTile*)Tile::crops)->icons[i]); + setIconSPUFromIcon(&m_tileData.cropTile_icons[i], static_cast(Tile::crops)->icons[i]); // FurnaceTile - setIconSPUFromIcon(&m_tileData.furnaceTile_iconTop, ((FurnaceTile*)Tile::furnace)->iconTop); - setIconSPUFromIcon(&m_tileData.furnaceTile_iconFront, ((FurnaceTile*)Tile::furnace)->iconFront); - setIconSPUFromIcon(&m_tileData.furnaceTile_iconFront_lit, ((FurnaceTile*)Tile::furnace_lit)->iconFront); + setIconSPUFromIcon(&m_tileData.furnaceTile_iconTop, static_cast(Tile::furnace)->iconTop); + setIconSPUFromIcon(&m_tileData.furnaceTile_iconFront, static_cast(Tile::furnace)->iconFront); + setIconSPUFromIcon(&m_tileData.furnaceTile_iconFront_lit, static_cast(Tile::furnace_lit)->iconFront); //LiquidTile setIconSPUFromIcon(&m_tileData.liquidTile_iconWaterStill, (Tile::water)->icons[0]); @@ -332,64 +332,64 @@ void ChunkRebuildData::createTileData() // Sapling for(int i=0;i<4;i++) - setIconSPUFromIcon(&m_tileData.sapling_icons[i], ((Sapling*)Tile::sapling)->icons[i]); + setIconSPUFromIcon(&m_tileData.sapling_icons[i], static_cast(Tile::sapling)->icons[i]); - m_tileData.glassTile_allowSame = ((GlassTile*)Tile::glass)->allowSame; - m_tileData.iceTile_allowSame = ((IceTile*)Tile::ice)->allowSame; + m_tileData.glassTile_allowSame = static_cast(Tile::glass)->allowSame; + m_tileData.iceTile_allowSame = static_cast(Tile::ice)->allowSame; // DispenserTile - setIconSPUFromIcon(&m_tileData.dispenserTile_iconTop, ((DispenserTile*)Tile::dispenser)->iconTop); - setIconSPUFromIcon(&m_tileData.dispenserTile_iconFront, ((DispenserTile*)Tile::dispenser)->iconFront); - setIconSPUFromIcon(&m_tileData.dispenserTile_iconFrontVertical, ((DispenserTile*)Tile::dispenser)->iconFrontVertical); + setIconSPUFromIcon(&m_tileData.dispenserTile_iconTop, static_cast(Tile::dispenser)->iconTop); + setIconSPUFromIcon(&m_tileData.dispenserTile_iconFront, static_cast(Tile::dispenser)->iconFront); + setIconSPUFromIcon(&m_tileData.dispenserTile_iconFrontVertical, static_cast(Tile::dispenser)->iconFrontVertical); // RailTile - setIconSPUFromIcon(&m_tileData.railTile_iconTurn, ((RailTile*)Tile::rail)->iconTurn); - setIconSPUFromIcon(&m_tileData.railTile_iconTurnGolden, ((RailTile*)Tile::goldenRail)->iconTurn); + setIconSPUFromIcon(&m_tileData.railTile_iconTurn, static_cast(Tile::rail)->iconTurn); + setIconSPUFromIcon(&m_tileData.railTile_iconTurnGolden, static_cast(Tile::goldenRail)->iconTurn); for(int i=0;i<2;i++) - setIconSPUFromIcon(&m_tileData.detectorRailTile_icons[i], ((DetectorRailTile*)Tile::detectorRail)->icons[i]); + setIconSPUFromIcon(&m_tileData.detectorRailTile_icons[i], static_cast(Tile::detectorRail)->icons[i]); // tntTile - setIconSPUFromIcon(&m_tileData.tntTile_iconBottom, ((TntTile*)Tile::tnt)->iconBottom); - setIconSPUFromIcon(&m_tileData.tntTile_iconTop, ((TntTile*)Tile::tnt)->iconTop); + setIconSPUFromIcon(&m_tileData.tntTile_iconBottom, static_cast(Tile::tnt)->iconBottom); + setIconSPUFromIcon(&m_tileData.tntTile_iconTop, static_cast(Tile::tnt)->iconTop); // workbenchTile - setIconSPUFromIcon(&m_tileData.workBench_iconFront, ((WorkbenchTile*)Tile::workBench)->iconFront); - setIconSPUFromIcon(&m_tileData.workBench_iconTop, ((WorkbenchTile*)Tile::workBench)->iconTop); + setIconSPUFromIcon(&m_tileData.workBench_iconFront, static_cast(Tile::workBench)->iconFront); + setIconSPUFromIcon(&m_tileData.workBench_iconTop, static_cast(Tile::workBench)->iconTop); // cactusTile - setIconSPUFromIcon(&m_tileData.cactusTile_iconTop, ((CactusTile*)Tile::cactus)->iconTop); - setIconSPUFromIcon(&m_tileData.cactusTile_iconBottom, ((CactusTile*)Tile::cactus)->iconBottom); + setIconSPUFromIcon(&m_tileData.cactusTile_iconTop, static_cast(Tile::cactus)->iconTop); + setIconSPUFromIcon(&m_tileData.cactusTile_iconBottom, static_cast(Tile::cactus)->iconBottom); // recordPlayer - setIconSPUFromIcon(&m_tileData.recordPlayer_iconTop, ((RecordPlayerTile*)Tile::recordPlayer)->iconTop); + setIconSPUFromIcon(&m_tileData.recordPlayer_iconTop, static_cast(Tile::recordPlayer)->iconTop); // pumpkin - setIconSPUFromIcon(&m_tileData.pumpkinTile_iconTop, ((PumpkinTile*)Tile::pumpkin)->iconTop); - setIconSPUFromIcon(&m_tileData.pumpkinTile_iconFace, ((PumpkinTile*)Tile::pumpkin)->iconFace); - setIconSPUFromIcon(&m_tileData.pumpkinTile_iconFaceLit, ((PumpkinTile*)Tile::litPumpkin)->iconFace); + setIconSPUFromIcon(&m_tileData.pumpkinTile_iconTop, static_cast(Tile::pumpkin)->iconTop); + setIconSPUFromIcon(&m_tileData.pumpkinTile_iconFace, static_cast(Tile::pumpkin)->iconFace); + setIconSPUFromIcon(&m_tileData.pumpkinTile_iconFaceLit, static_cast(Tile::litPumpkin)->iconFace); // cakeTile - setIconSPUFromIcon(&m_tileData.cakeTile_iconTop, ((CakeTile*)Tile::cake)->iconTop); - setIconSPUFromIcon(&m_tileData.cakeTile_iconBottom, ((CakeTile*)Tile::cake)->iconBottom); - setIconSPUFromIcon(&m_tileData.cakeTile_iconInner, ((CakeTile*)Tile::cake)->iconInner); + setIconSPUFromIcon(&m_tileData.cakeTile_iconTop, static_cast(Tile::cake)->iconTop); + setIconSPUFromIcon(&m_tileData.cakeTile_iconBottom, static_cast(Tile::cake)->iconBottom); + setIconSPUFromIcon(&m_tileData.cakeTile_iconInner, static_cast(Tile::cake)->iconInner); // SmoothStoneBrickTile for(int i=0;i<4;i++) - setIconSPUFromIcon(&m_tileData.smoothStoneBrick_icons[i], ((SmoothStoneBrickTile*)Tile::stoneBrickSmooth)->icons[i]); + setIconSPUFromIcon(&m_tileData.smoothStoneBrick_icons[i], static_cast(Tile::stoneBrickSmooth)->icons[i]); // HugeMushroomTile for(int i=0;i<2;i++) - setIconSPUFromIcon(&m_tileData.hugeMushroom_icons[i], ((HugeMushroomTile*)Tile::hugeMushroom1)->icons[i]); - setIconSPUFromIcon(&m_tileData.hugeMushroom_iconStem, ((HugeMushroomTile*)Tile::hugeMushroom1)->iconStem); - setIconSPUFromIcon(&m_tileData.hugeMushroom_iconInside, ((HugeMushroomTile*)Tile::hugeMushroom1)->iconInside); + setIconSPUFromIcon(&m_tileData.hugeMushroom_icons[i], static_cast(Tile::hugeMushroom1)->icons[i]); + setIconSPUFromIcon(&m_tileData.hugeMushroom_iconStem, static_cast(Tile::hugeMushroom1)->iconStem); + setIconSPUFromIcon(&m_tileData.hugeMushroom_iconInside, static_cast(Tile::hugeMushroom1)->iconInside); // MelonTile - setIconSPUFromIcon(&m_tileData.melonTile_iconTop, ((MelonTile*)Tile::melon)->iconTop); + setIconSPUFromIcon(&m_tileData.melonTile_iconTop, static_cast(Tile::melon)->iconTop); // StemTile - setIconSPUFromIcon(&m_tileData.stemTile_iconAngled, ((StemTile*)Tile::melonStem)->iconAngled); + setIconSPUFromIcon(&m_tileData.stemTile_iconAngled, static_cast(Tile::melonStem)->iconAngled); // MycelTile setIconSPUFromIcon(&m_tileData.mycelTile_iconTop, (Tile::mycel)->iconTop); @@ -397,14 +397,14 @@ void ChunkRebuildData::createTileData() // NetherStalkTile for(int i=0;i<3;i++) - setIconSPUFromIcon(&m_tileData.netherStalk_icons[i], ((NetherStalkTile*)Tile::netherStalk)->icons[i]); + setIconSPUFromIcon(&m_tileData.netherStalk_icons[i], static_cast(Tile::netherStalk)->icons[i]); // EnchantmentTableTile - setIconSPUFromIcon(&m_tileData.enchantmentTable_iconTop, ((EnchantmentTableTile*)Tile::enchantTable)->iconTop); - setIconSPUFromIcon(&m_tileData.enchantmentTable_iconBottom, ((EnchantmentTableTile*)Tile::enchantTable)->iconBottom); + setIconSPUFromIcon(&m_tileData.enchantmentTable_iconTop, static_cast(Tile::enchantTable)->iconTop); + setIconSPUFromIcon(&m_tileData.enchantmentTable_iconBottom, static_cast(Tile::enchantTable)->iconBottom); //BrewingStandTile - setIconSPUFromIcon(&m_tileData.brewingStand_iconBase, ((BrewingStandTile*)Tile::brewingStand)->iconBase); + setIconSPUFromIcon(&m_tileData.brewingStand_iconBase, static_cast(Tile::brewingStand)->iconBase); //RedStoneDust setIconSPUFromIcon(&m_tileData.redStoneDust_iconCross, (Tile::redStoneDust)->iconCross); @@ -412,32 +412,32 @@ void ChunkRebuildData::createTileData() setIconSPUFromIcon(&m_tileData.redStoneDust_iconCrossOver, (Tile::redStoneDust)->iconCrossOver); setIconSPUFromIcon(&m_tileData.redStoneDust_iconLineOver, (Tile::redStoneDust)->iconLineOver); - setIconSPUFromIcon(&m_tileData.stoneSlab_iconSide, ((StoneSlabTile*)(Tile::stoneSlab))->iconSide); + setIconSPUFromIcon(&m_tileData.stoneSlab_iconSide, static_cast(Tile::stoneSlab)->iconSide); for(int i=0;i<16;i++) - setIconSPUFromIcon(&m_tileData.clothTile_icons[i], ((ClothTile*)Tile::cloth)->icons[i]); + setIconSPUFromIcon(&m_tileData.clothTile_icons[i], static_cast(Tile::cloth)->icons[i]); // CarrotTile for(int i=0;i<4;i++) - setIconSPUFromIcon(&m_tileData.carrot_icons[i], ((CarrotTile*)Tile::carrots)->icons[i]); + setIconSPUFromIcon(&m_tileData.carrot_icons[i], static_cast(Tile::carrots)->icons[i]); // PotatoTile for(int i=0;i<4;i++) - setIconSPUFromIcon(&m_tileData.potato_icons[i], ((PotatoTile*)Tile::potatoes)->icons[i]); + setIconSPUFromIcon(&m_tileData.potato_icons[i], static_cast(Tile::potatoes)->icons[i]); // AnvilTile for(int i=0;i<3;i++) - setIconSPUFromIcon(&m_tileData.anvil_icons[i], ((AnvilTile*)Tile::anvil)->icons[i]); + setIconSPUFromIcon(&m_tileData.anvil_icons[i], static_cast(Tile::anvil)->icons[i]); // QuartzBlockTile for(int i=0;i<5;i++) - setIconSPUFromIcon(&m_tileData.quartzBlock_icons[i], ((QuartzBlockTile*)Tile::quartzBlock)->icons[i]); + setIconSPUFromIcon(&m_tileData.quartzBlock_icons[i], static_cast(Tile::quartzBlock)->icons[i]); - setIconSPUFromIcon(&m_tileData.quartzBlock_iconChiseledTop, ((QuartzBlockTile*)Tile::quartzBlock)->iconChiseledTop); - setIconSPUFromIcon(&m_tileData.quartzBlock_iconLinesTop, ((QuartzBlockTile*)Tile::quartzBlock)->iconLinesTop); - setIconSPUFromIcon(&m_tileData.quartzBlock_iconTop, ((QuartzBlockTile*)Tile::quartzBlock)->iconTop); - setIconSPUFromIcon(&m_tileData.quartzBlock_iconBottom, ((QuartzBlockTile*)Tile::quartzBlock)->iconBottom); + setIconSPUFromIcon(&m_tileData.quartzBlock_iconChiseledTop, static_cast(Tile::quartzBlock)->iconChiseledTop); + setIconSPUFromIcon(&m_tileData.quartzBlock_iconLinesTop, static_cast(Tile::quartzBlock)->iconLinesTop); + setIconSPUFromIcon(&m_tileData.quartzBlock_iconTop, static_cast(Tile::quartzBlock)->iconTop); + setIconSPUFromIcon(&m_tileData.quartzBlock_iconBottom, static_cast(Tile::quartzBlock)->iconBottom); } // extern int g_lastHitBlockX; @@ -696,7 +696,7 @@ bool ChunkRebuildData::isEmptyTile(int x, int y, int z) bool ChunkRebuildData::isSolidRenderTile(int x, int y, int z) { TileRef_SPU tile(getTile(x,y,z)); - if (tile.getPtr() == NULL) return false; + if (tile.getPtr() == nullptr) return false; // 4J - addition here to make rendering big blocks of leaves more efficient. Normally leaves never consider themselves as solid, so @@ -727,7 +727,7 @@ bool ChunkRebuildData::isSolidRenderTile(int x, int y, int z) bool ChunkRebuildData::isSolidBlockingTile(int x, int y, int z) { TileRef_SPU tile(getTile(x, y, z)); - if (tile.getPtr() == NULL) return false; + if (tile.getPtr() == nullptr) return false; bool ret = tile->getMaterial()->blocksMotion() && tile->isCubeShaped(); return ret; } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/DoorTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/DoorTile_SPU.h index f6671db49..2fcb15146 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/DoorTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/DoorTile_SPU.h @@ -24,7 +24,7 @@ public: virtual bool blocksLight() { return false; } virtual bool isSolidRender(bool isServerLevel = false) { return false; } virtual int getRenderShape() { return Tile_SPU::SHAPE_DOOR; } - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param int getDir(ChunkRebuildData *level, int x, int y, int z); bool isOpen(ChunkRebuildData *level, int x, int y, int z); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceGateTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceGateTile_SPU.h index 6e86d1f03..5e99cc320 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceGateTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceGateTile_SPU.h @@ -12,7 +12,7 @@ public: Icon_SPU *getTexture(int face, int data) { return TileRef_SPU(wood_Id)->getTexture(face); } static int getDirection(int data) { return (data & DIRECTION_MASK); } - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param // Brought forward from 1.2.3 + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param // Brought forward from 1.2.3 { int data = getDirection(level->getData(x, y, z)); if (data == Direction::NORTH || data == Direction::SOUTH) diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.cpp index fcb3baefb..63c206d1d 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.cpp @@ -59,7 +59,7 @@ bool FenceTile_SPU::connectsTo(ChunkRebuildData *level, int x, int y, int z) return true; } TileRef_SPU tileInstance(tile); - if (tileInstance.getPtr() != NULL) + if (tileInstance.getPtr() != nullptr) { if (tileInstance->getMaterial()->isSolidBlocking() && tileInstance->isCubeShaped()) { diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.h index 50a775fb4..bed2e3b72 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/FenceTile_SPU.h @@ -5,7 +5,7 @@ class FenceTile_SPU : public Tile_SPU { public: FenceTile_SPU(int id) : Tile_SPU(id) {} - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual int getRenderShape(); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.cpp index 1cf838219..1dba9757c 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.cpp @@ -3,7 +3,7 @@ #include "Facing_SPU.h" #include "ChunkRebuildData.h" -void HalfSlabTile_SPU::updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData /* = -1 */, TileEntity* forceEntity /* = NULL */) +void HalfSlabTile_SPU::updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData /* = -1 */, TileEntity* forceEntity /* = nullptr */) { if (fullSize()) { diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.h index fd525e96b..c89581ad9 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/HalfSlabTile_SPU.h @@ -9,7 +9,7 @@ public: static const int TOP_SLOT_BIT = 8; HalfSlabTile_SPU(int id) : Tile_SPU(id) {} - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param virtual void updateDefaultShape(); virtual bool isSolidRender(bool isServerLevel); virtual bool shouldRenderFace(ChunkRebuildData *level, int x, int y, int z, int face); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Icon_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Icon_SPU.h index f4ba6ccfa..0597c1fc2 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Icon_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Icon_SPU.h @@ -24,29 +24,29 @@ public: void set(int16_t _x, int16_t _y, int16_t _w, int16_t _h, int texWidth, int texHeight) { - x0 = (int16_t)(4096 * (float(_x) / texWidth)); - y0 = (int16_t)(4096 * (float(_y) / texHeight)); - x1 = x0 + (int16_t)(4096 * (float(_w) / texWidth)); - y1 = y0 + (int16_t)(4096 * (float(_h) / texHeight)); + x0 = static_cast(4096 * (float(_x) / texWidth)); + y0 = static_cast(4096 * (float(_y) / texHeight)); + x1 = x0 + static_cast(4096 * (float(_w) / texWidth)); + y1 = y0 + static_cast(4096 * (float(_h) / texHeight)); } void flipHorizontal() { int16_t temp = x0; x0 = x1; x1 = temp; } void flipVertical() { int16_t temp = y0; y0 = y1; y1 = temp; } - float getU0() const { return (float(x0) / 4096) + UVAdjust; }//sc_texWidth) + getUAdjust(); } - float getU1() const { return (float(x1) / 4096.0f) - UVAdjust; } //sc_texWidth) - getUAdjust(); } + float getU0() const { return (static_cast(x0) / 4096) + UVAdjust; }//sc_texWidth) + getUAdjust(); } + float getU1() const { return (static_cast(x1) / 4096.0f) - UVAdjust; } //sc_texWidth) - getUAdjust(); } float getU(double offset) const { float diff = getU1() - getU0(); - return getU0() + (diff * ((float) offset / 16));//SharedConstants::WORLD_RESOLUTION)); + return getU0() + (diff * (static_cast(offset) / 16));//SharedConstants::WORLD_RESOLUTION)); } - float getV0() const { return (float(y0) / 4096.0f) + UVAdjust; } //sc_texHeight) + getVAdjust(); } - float getV1() const { return (float(y1) / 4096.0f) - UVAdjust; } //sc_texHeight) - getVAdjust(); } + float getV0() const { return (static_cast(y0) / 4096.0f) + UVAdjust; } //sc_texHeight) + getVAdjust(); } + float getV1() const { return (static_cast(y1) / 4096.0f) - UVAdjust; } //sc_texHeight) - getVAdjust(); } float getV(double offset) const { float diff = getV1() - getV0(); - return getV0() + (diff * ((float) offset / 16)); //SharedConstants::WORLD_RESOLUTION)); + return getV0() + (diff * (static_cast(offset) / 16)); //SharedConstants::WORLD_RESOLUTION)); } // virtual wstring getName() const = 0; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/LiquidTile_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/LiquidTile_SPU.cpp index 7f13fd4f9..fa075e716 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/LiquidTile_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/LiquidTile_SPU.cpp @@ -211,12 +211,12 @@ double LiquidTile_SPU::getSlopeAngle(ChunkRebuildData *level, int x, int y, int if (m->getID() == Material_SPU::water_Id) { TileRef_SPU tRef(Tile_SPU::water_Id); - flow = ((LiquidTile_SPU*)tRef.getPtr())->getFlow(level, x, y, z); + flow = static_cast(tRef.getPtr())->getFlow(level, x, y, z); } if (m->getID() == Material_SPU::lava_Id) { TileRef_SPU tRef(Tile_SPU::lava_Id); - flow = ((LiquidTile_SPU*)tRef.getPtr())->getFlow(level, x, y, z); + flow = static_cast(tRef.getPtr())->getFlow(level, x, y, z); } if (flow.x == 0 && flow.z == 0) return -1000; return atan2(flow.z, flow.x) - MATH_PI / 2; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonBaseTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonBaseTile_SPU.h index e8411c885..81ba68c19 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonBaseTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonBaseTile_SPU.h @@ -8,7 +8,7 @@ class PistonBaseTile_SPU : public Tile_SPU public: PistonBaseTile_SPU(int id) : Tile_SPU(id) {} // virtual void updateShape(float x0, float y0, float z0, float x1, float y1, float z1); - virtual Icon_SPU *getTexture(int face, int data) { return NULL; } + virtual Icon_SPU *getTexture(int face, int data) { return nullptr; } virtual int getRenderShape() { return SHAPE_PISTON_BASE; } virtual bool isSolidRender(bool isServerLevel = false) { return false; } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonExtensionTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonExtensionTile_SPU.h index d5460492e..ee559eff2 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonExtensionTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonExtensionTile_SPU.h @@ -6,7 +6,7 @@ class PistonExtensionTile_SPU : public Tile_SPU public: PistonExtensionTile_SPU(int id) : Tile_SPU(id) {} - virtual Icon_SPU *getTexture(int face, int data) { return NULL; } + virtual Icon_SPU *getTexture(int face, int data) { return nullptr; } virtual int getRenderShape() { return SHAPE_PISTON_EXTENSION; } virtual bool isSolidRender(bool isServerLevel = false) { return false; } // virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, shared_ptr forceEntity = shared_ptr()); // 4J added forceData, forceEntity param diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonMovingPiece_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonMovingPiece_SPU.h index 48fc52e91..6ea12648f 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonMovingPiece_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PistonMovingPiece_SPU.h @@ -10,7 +10,7 @@ public: virtual int getRenderShape() { return SHAPE_INVISIBLE; } virtual bool isSolidRender(bool isServerLevel = false) { return false; } - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { // should never get here. } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PortalTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PortalTile_SPU.h index f01313a11..a5a4652d8 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PortalTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PortalTile_SPU.h @@ -5,7 +5,7 @@ class PortalTile_SPU : public HalfTransparentTile_SPU { public: PortalTile_SPU(int id): HalfTransparentTile_SPU(id) {} - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { if (level->getTile(x - 1, y, z) == id || level->getTile(x + 1, y, z) == id) { diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PressurePlateTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PressurePlateTile_SPU.h index 133ec52e5..6742e6f6c 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PressurePlateTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/PressurePlateTile_SPU.h @@ -16,6 +16,6 @@ public: virtual bool isSolidRender(bool isServerLevel = false); virtual bool blocksLight(); - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param virtual void updateDefaultShape(); }; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RailTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RailTile_SPU.h index 615ebec92..2f8639d4f 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RailTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RailTile_SPU.h @@ -10,7 +10,7 @@ public: RailTile_SPU(int id) : Tile_SPU(id) {} virtual bool isSolidRender(bool isServerLevel = false) { return false; } - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { int data = level->getData(x, y, z); if (data >= 2 && data <= 5) diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RedStoneDustTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RedStoneDustTile_SPU.h index 0e461118e..218cbd646 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RedStoneDustTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/RedStoneDustTile_SPU.h @@ -26,7 +26,7 @@ public: case TEXTURE_CROSS_OVERLAY: return &ms_pTileData->redStoneDust_iconCrossOver; case TEXTURE_LINE_OVERLAY: return &ms_pTileData->redStoneDust_iconLineOver; } - return NULL; + return nullptr; } static bool shouldConnectTo(ChunkRebuildData *level, int x, int y, int z, int direction) diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/SignTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/SignTile_SPU.h index 7fe54d991..74bdb95d9 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/SignTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/SignTile_SPU.h @@ -16,7 +16,7 @@ public: } Icon_SPU *getTexture(int face, int data){ return TileRef_SPU(wood_Id)->getTexture(face); } - void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { if (onGround()) return; int face = level->getData(x, y, z); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StairTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StairTile_SPU.h index eefa36b2a..ca5ba279f 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StairTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StairTile_SPU.h @@ -15,7 +15,7 @@ public: public: StairTile_SPU(int id) : Tile_SPU(id) {} - void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param bool isSolidRender(bool isServerLevel = false); int getRenderShape(); void setBaseShape(ChunkRebuildData *level, int x, int y, int z); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StemTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StemTile_SPU.h index 89cd3739c..4923e862d 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StemTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/StemTile_SPU.h @@ -35,7 +35,7 @@ public: this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); } - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { ms_pTileData->yy1[id] = (level->getData(x, y, z) * 2 + 2) / 16.0f; float ss = 0.125f; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tesselator_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tesselator_SPU.cpp index 3d1007af1..efcd44f01 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tesselator_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tesselator_SPU.cpp @@ -68,7 +68,7 @@ typedef unsigned short hfloat; hfloat convertFloatToHFloat(float f) { unsigned int x = *(unsigned int *)&f; - unsigned int sign = (unsigned short)(x >> 31); + unsigned int sign = static_cast(x >> 31); unsigned int mantissa; unsigned int exp; hfloat hf; @@ -90,8 +90,8 @@ hfloat convertFloatToHFloat(float f) // 16-bit half-float representation stores number as Inf mantissa = 0; } - hf = (((hfloat)sign) << 15) | (hfloat)(HALF_FLOAT_MAX_BIASED_EXP) | - (hfloat)(mantissa >> 13); + hf = (static_cast(sign) << 15) | static_cast(HALF_FLOAT_MAX_BIASED_EXP) | + static_cast(mantissa >> 13); } // check if exponent is <= -15 else if (exp <= HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP) @@ -101,13 +101,13 @@ hfloat convertFloatToHFloat(float f) exp = (HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP - exp) >> 23; mantissa >>= (14 + exp); - hf = (((hfloat)sign) << 15) | (hfloat)(mantissa); + hf = (static_cast(sign) << 15) | static_cast(mantissa); } else { - hf = (((hfloat)sign) << 15) | - (hfloat)((exp - HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP) >> 13) | - (hfloat)(mantissa >> 13); + hf = (static_cast(sign) << 15) | + static_cast((exp - HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP) >> 13) | + static_cast(mantissa >> 13); } return hf; @@ -115,8 +115,8 @@ hfloat convertFloatToHFloat(float f) float convertHFloatToFloat(hfloat hf) { - unsigned int sign = (unsigned int)(hf >> 15); - unsigned int mantissa = (unsigned int)(hf & ((1 << 10) - 1)); + unsigned int sign = static_cast(hf >> 15); + unsigned int mantissa = static_cast(hf & ((1 << 10) - 1)); unsigned int exp = (unsigned int)(hf & HALF_FLOAT_MAX_BIASED_EXP); unsigned int f; @@ -170,7 +170,7 @@ float convertHFloatToFloat(hfloat hf) // Tesselator_SPU *Tesselator_SPU::getInstance() { - return NULL; + return nullptr; // return (Tesselator_SPU *)TlsGetValue(tlsIdx); } @@ -329,12 +329,12 @@ void Tesselator_SPU::tex2(int tex2) void Tesselator_SPU::color(float r, float g, float b) { - color((int) (r * 255), (int) (g * 255), (int) (b * 255)); + color(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255)); } void Tesselator_SPU::color(float r, float g, float b, float a) { - color((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); + color(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255), static_cast(a * 255)); } void Tesselator_SPU::color(int r, int g, int b) @@ -539,7 +539,7 @@ void Tesselator_SPU::vertex(float x, float y, float z) // see comments in packCompactQuad() for exact format if( useCompactFormat360 ) { - unsigned int ucol = (unsigned int)col; + unsigned int ucol = static_cast(col); #ifdef _XBOX // Pack as 4:4:4 RGB_ @@ -564,7 +564,7 @@ void Tesselator_SPU::vertex(float x, float y, float z) unsigned short packedcol = ((col & 0xf8000000 ) >> 16 ) | ((col & 0x00fc0000 ) >> 13 ) | ((col & 0x0000f800 ) >> 11 ); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + int ipackedcol = static_cast(packedcol) & 0xffff; // 0 to 65535 range ipackedcol -= 32768; // -32768 to 32767 range ipackedcol &= 0xffff; @@ -597,12 +597,12 @@ void Tesselator_SPU::vertex(float x, float y, float z) pShortData[7] = ((INT_ROUND(tex2V * (8192.0f/256.0f)))&0xffff); incData(4); #else - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); + pShortData[0] = (static_cast((x + xo) * 1024.0f)&0xffff); + pShortData[1] = (static_cast((y + yo) * 1024.0f)&0xffff); + pShortData[2] = (static_cast((z + zo) * 1024.0f)&0xffff); pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); + pShortData[4] = (static_cast(uu * 8192.0f)&0xffff); + pShortData[5] = (static_cast(v * 8192.0f)&0xffff); pShortData[6] = ((int16_t*)&_tex2)[0]; pShortData[7] = ((int16_t*)&_tex2)[1]; incData(4); @@ -723,9 +723,9 @@ void Tesselator_SPU::noColor() void Tesselator_SPU::normal(float x, float y, float z) { hasNormal = true; - byte xx = (byte) (x * 127); - byte yy = (byte) (y * 127); - byte zz = (byte) (z * 127); + byte xx = static_cast(x * 127); + byte yy = static_cast(y * 127); + byte zz = static_cast(z * 127); _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TheEndPortalFrameTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TheEndPortalFrameTile_SPU.h index 8aab31a35..87d87bcfa 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TheEndPortalFrameTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TheEndPortalFrameTile_SPU.h @@ -5,7 +5,7 @@ class TheEndPortalFrameTile_SPU : public Tile_SPU { public: TheEndPortalFrameTile_SPU(int id) : Tile_SPU(id) {} - virtual Icon_SPU *getTexture(int face, int data) { return NULL; } + virtual Icon_SPU *getTexture(int face, int data) { return nullptr; } virtual bool isSolidRender(bool isServerLevel = false) { return false; } virtual int getRenderShape() { return SHAPE_PORTAL_FRAME; } // virtual void updateDefaultShape(); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.cpp index 20393f6ea..9e7d30de6 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.cpp @@ -74,7 +74,7 @@ Icon_SPU *ThinFenceTile_SPU::getEdgeTexture() #ifndef SN_TARGET_PS3_SPU assert(0); #endif - return NULL; + return nullptr; } bool ThinFenceTile_SPU::attachsTo(int tile) diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.h index 61c392010..8f7b601b3 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/ThinFenceTile_SPU.h @@ -11,7 +11,7 @@ public: virtual int getRenderShape(); virtual bool shouldRenderFace(ChunkRebuildData *level, int x, int y, int z, int face); virtual void updateDefaultShape(); - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param virtual Icon_SPU *getEdgeTexture(); bool attachsTo(int tile); }; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.cpp index ab9b2c94c..22c3a26d3 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.cpp @@ -71,7 +71,7 @@ const float smallUV = ( 1.0f / 16.0f ); void TileRenderer_SPU::_init() { - fixedTexture = NULL; + fixedTexture = nullptr; xFlipTexture = false; noCulling = false; blsmooth = 1; @@ -103,7 +103,7 @@ TileRenderer_SPU::TileRenderer_SPU( ChunkRebuildData* level ) TileRenderer_SPU::TileRenderer_SPU() { - this->level = NULL; + this->level = nullptr; _init(); } @@ -122,12 +122,12 @@ void TileRenderer_SPU::setFixedTexture( Icon_SPU *fixedTexture ) void TileRenderer_SPU::clearFixedTexture() { - this->fixedTexture = NULL; + this->fixedTexture = nullptr; } bool TileRenderer_SPU::hasFixedTexture() { - return fixedTexture != NULL; + return fixedTexture != nullptr; } void TileRenderer_SPU::setShape(float x0, float y0, float z0, float x1, float y1, float z1) @@ -270,7 +270,7 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateStemInWorld( tt, x, y, z ); break; case Tile_SPU::SHAPE_LILYPAD: - retVal = tesselateLilypadInWorld( (WaterlilyTile_SPU*)tt, x, y, z ); + retVal = tesselateLilypadInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_ROWS: retVal = tesselateRowInWorld( tt, x, y, z ); @@ -279,7 +279,7 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateTorchInWorld( tt, x, y, z ); break; case Tile_SPU::SHAPE_FIRE: - retVal = tesselateFireInWorld( (FireTile_SPU *)tt, x, y, z ); + retVal = tesselateFireInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_RED_DUST: retVal = tesselateDustInWorld( tt, x, y, z ); @@ -291,19 +291,19 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateDoorInWorld( tt, x, y, z ); break; case Tile_SPU::SHAPE_RAIL: - retVal = tesselateRailInWorld( ( RailTile_SPU* )tt, x, y, z ); + retVal = tesselateRailInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_STAIRS: - retVal = tesselateStairsInWorld( (StairTile_SPU *)tt, x, y, z ); + retVal = tesselateStairsInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_EGG: - retVal = tesselateEggInWorld((EggTile_SPU*) tt, x, y, z); + retVal = tesselateEggInWorld(static_cast(tt), x, y, z); break; case Tile_SPU::SHAPE_FENCE: - retVal = tesselateFenceInWorld( ( FenceTile_SPU* )tt, x, y, z ); + retVal = tesselateFenceInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_WALL: - retVal = tesselateWallInWorld( (WallTile_SPU *) tt, x, y, z); + retVal = tesselateWallInWorld( static_cast(tt), x, y, z); break; case Tile_SPU::SHAPE_LEVER: retVal = tesselateLeverInWorld( tt, x, y, z ); @@ -318,7 +318,7 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateBedInWorld( tt, x, y, z ); break; case Tile_SPU::SHAPE_DIODE: - retVal = tesselateDiodeInWorld( (DiodeTile_SPU *)tt, x, y, z ); + retVal = tesselateDiodeInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_PISTON_BASE: retVal = tesselatePistonBaseInWorld( tt, x, y, z, false, forceData ); @@ -333,7 +333,7 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateVineInWorld( tt, x, y, z ); break; case Tile_SPU::SHAPE_FENCE_GATE: - retVal = tesselateFenceGateInWorld( ( FenceGateTile_SPU* )tt, x, y, z ); + retVal = tesselateFenceGateInWorld( static_cast(tt), x, y, z ); break; case Tile_SPU::SHAPE_CAULDRON: retVal = tesselateCauldronInWorld((CauldronTile_SPU* ) tt, x, y, z); @@ -345,7 +345,7 @@ bool TileRenderer_SPU::tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int retVal = tesselateAnvilInWorld((AnvilTile_SPU *) tt, x, y, z); break; case Tile_SPU::SHAPE_BREWING_STAND: - retVal = tesselateBrewingStandInWorld((BrewingStandTile_SPU* ) tt, x, y, z); + retVal = tesselateBrewingStandInWorld(static_cast(tt), x, y, z); break; case Tile_SPU::SHAPE_PORTAL_FRAME: retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile *)tt, x, y, z); @@ -838,7 +838,7 @@ bool TileRenderer_SPU::tesselateFlowerPotInWorld(FlowerPotTile_SPU *tt, int x, i float xOff = 0; float yOff = 4; float zOff = 0; - Tile *plant = NULL; + Tile *plant = nullptr; switch (type) { @@ -858,7 +858,7 @@ bool TileRenderer_SPU::tesselateFlowerPotInWorld(FlowerPotTile_SPU *tt, int x, i t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); - if (plant != NULL) + if (plant != nullptr) { tesselateInWorld(plant, x, y, z); } @@ -1099,23 +1099,23 @@ bool TileRenderer_SPU::tesselateTorchInWorld( Tile_SPU* tt, int x, int y, int z float h = 0.20f; if ( dir == 1 ) { - tesselateTorch( tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x) - r2, static_cast(y) + h, static_cast(z), -r, 0.0f, 0 ); } else if ( dir == 2 ) { - tesselateTorch( tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x) + r2, static_cast(y) + h, static_cast(z), +r, 0.0f, 0 ); } else if ( dir == 3 ) { - tesselateTorch( tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y) + h, z - r2, 0.0f, -r, 0 ); } else if ( dir == 4 ) { - tesselateTorch( tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y) + h, static_cast(z) + r2, 0.0f, +r, 0 ); } else { - tesselateTorch( tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y), static_cast(z), 0.0f, 0.0f, 0 ); } return true; @@ -1724,7 +1724,7 @@ bool TileRenderer_SPU::tesselateLeverInWorld( Tile_SPU* tt, int x, int y, int z } } - Vec3* c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + Vec3* c0 = nullptr, *c1 = nullptr, *c2 = nullptr, *c3 = nullptr; for ( int i = 0; i < 6; i++ ) { if ( i == 0 ) @@ -1897,7 +1897,7 @@ bool TileRenderer_SPU::tesselateTripwireSourceInWorld(Tile_SPU *tt, int x, int y corners[i]->z += z + 0.5; } - Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + Vec3 *c0 = nullptr, *c1 = nullptr, *c2 = nullptr, *c3 = nullptr; int stickX0 = 7; int stickX1 = 9; int stickY0 = 9; @@ -2321,15 +2321,15 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int float z0_ = z + 0.5f - 0.3f; float z1_ = z + 0.5f + 0.3f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 1), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u0 ), ( float )( v0 ) ); tex = secondTex; u0 = tex->getU0(); @@ -2337,15 +2337,15 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int u1 = tex->getU1(); v1 = tex->getV1(); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); x0 = x + 0.5f - 0.5f; x1 = x + 0.5f + 0.5f; @@ -2357,15 +2357,15 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int z0_ = z + 0.5f - 0.4f; z1_ = z + 0.5f + 0.4f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 1), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u1 ), ( float )( v0 ) ); tex = firstTex; u0 = tex->getU0(); @@ -2373,15 +2373,15 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int u1 = tex->getU1(); v1 = tex->getV1(); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); } else { @@ -2425,10 +2425,10 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int { t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1 - 0), ( float )( y + 0 + yo ), ( float )( z + + 0.0f ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1 - 0), ( float )( y + 0 + yo ), ( float )( z + + 1.0f ), ( float )( u1 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + 1.0f ), ( float )( u1 ), ( float )( v0 ) ); @@ -2504,14 +2504,14 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int if ( ( ( x + y + z ) & 1 ) == 0 ) { - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + + 0), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + + 1), ( float )( u0 ), ( float )( v0 ) ); tex = secondTex; u0 = tex->getU0(); @@ -2523,10 +2523,10 @@ bool TileRenderer_SPU::tesselateFireInWorld( FireTile_SPU* tt, int x, int y, int 1.0f ), ( float )( u1 ), ( float )( v0 ) ); t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), static_cast(z + + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + + 0), ( float )( u0 ), ( float )( v0 ) ); } else { @@ -2789,15 +2789,15 @@ bool TileRenderer_SPU::tesselateRailInWorld( RailTile_SPU* tt, int x, int y, int float r = 1 / 16.0f; - float x0 = ( float )( x + 1 ); - float x1 = ( float )( x + 1 ); - float x2 = ( float )( x + 0 ); - float x3 = ( float )( x + 0 ); + float x0 = static_cast(x + 1); + float x1 = static_cast(x + 1); + float x2 = static_cast(x + 0); + float x3 = static_cast(x + 0); - float z0 = ( float )( z + 0 ); - float z1 = ( float )( z + 1 ); - float z2 = ( float )( z + 1 ); - float z3 = ( float )( z + 0 ); + float z0 = static_cast(z + 0); + float z1 = static_cast(z + 1); + float z2 = static_cast(z + 1); + float z3 = static_cast(z + 0); float y0 = ( float )( y + r ); float y1 = ( float )( y + r ); @@ -2806,24 +2806,24 @@ bool TileRenderer_SPU::tesselateRailInWorld( RailTile_SPU* tt, int x, int y, int if ( data == 1 || data == 2 || data == 3 || data == 7 ) { - x0 = x3 = ( float )( x + 1 ); - x1 = x2 = ( float )( x + 0 ); - z0 = z1 = ( float )( z + 1 ); - z2 = z3 = ( float )( z + 0 ); + x0 = x3 = static_cast(x + 1); + x1 = x2 = static_cast(x + 0); + z0 = z1 = static_cast(z + 1); + z2 = z3 = static_cast(z + 0); } else if ( data == 8 ) { - x0 = x1 = ( float )( x + 0 ); - x2 = x3 = ( float )( x + 1 ); - z0 = z3 = ( float )( z + 1 ); - z1 = z2 = ( float )( z + 0 ); + x0 = x1 = static_cast(x + 0); + x2 = x3 = static_cast(x + 1); + z0 = z3 = static_cast(z + 1); + z1 = z2 = static_cast(z + 0); } else if ( data == 9 ) { - x0 = x3 = ( float )( x + 0 ); - x1 = x2 = ( float )( x + 1 ); - z0 = z1 = ( float )( z + 0 ); - z2 = z3 = ( float )( z + 1 ); + x0 = x3 = static_cast(x + 0); + x1 = x2 = static_cast(x + 1); + z0 = z1 = static_cast(z + 0); + z2 = z3 = static_cast(z + 1); } if ( data == 2 || data == 4 ) @@ -3555,9 +3555,9 @@ bool TileRenderer_SPU::tesselateCrossInWorld( Tile_SPU* tt, int x, int y, int z } t->color( br * r, br * g, br * b ); - float xt = (float)x; - float yt = (float)y; - float zt = (float)z; + float xt = static_cast(x); + float yt = static_cast(y); + float zt = static_cast(z); if (tt->id == Tile_SPU::tallgrass_Id) { @@ -3575,7 +3575,7 @@ bool TileRenderer_SPU::tesselateCrossInWorld( Tile_SPU* tt, int x, int y, int z bool TileRenderer_SPU::tesselateStemInWorld( Tile_SPU* _tt, int x, int y, int z ) { - StemTile_SPU* tt = ( StemTile_SPU* )_tt; + StemTile_SPU* tt = static_cast(_tt); Tesselator_SPU* t = getTesselator(); float br; @@ -3805,7 +3805,7 @@ bool TileRenderer_SPU::tesselateLilypadInWorld(WaterlilyTile_SPU *tt, int x, int int64_t seed = (x * 3129871) ^ (z * 116129781l) ^ (y); seed = seed * seed * 42317861 + seed * 11; - int dir = (int) ((seed >> 16) & 0x3); + int dir = static_cast((seed >> 16) & 0x3); @@ -4017,7 +4017,7 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z { changed = true; Icon_SPU *tex = getTexture( tt, 1, data ); - float angle = ( float )LiquidTile_SPU::getSlopeAngle( level, x, y, z, m ); + float angle = static_cast(LiquidTile_SPU::getSlopeAngle(level, x, y, z, m)); if ( angle > -999 ) { tex = getTexture( tt, 2, data ); @@ -4112,8 +4112,8 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z { hh0 = ( float )( h0 ); hh1 = ( float )( h3 ); - x0 = ( float )( x ); - x1 = ( float )( x + 1 ); + x0 = static_cast(x); + x1 = static_cast(x + 1); z0 = ( float )( z + offs); z1 = ( float )( z + offs); } @@ -4121,8 +4121,8 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z { hh0 = ( float )( h2 ); hh1 = ( float )( h1 ); - x0 = ( float )( x + 1 ); - x1 = ( float )( x ); + x0 = static_cast(x + 1); + x1 = static_cast(x); z0 = ( float )( z + 1 - offs); z1 = ( float )( z + 1 - offs); } @@ -4132,8 +4132,8 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z hh1 = ( float )( h0 ); x0 = ( float )( x + offs); x1 = ( float )( x + offs); - z0 = ( float )( z + 1 ); - z1 = ( float )( z ); + z0 = static_cast(z + 1); + z1 = static_cast(z); } else { @@ -4141,8 +4141,8 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z hh1 = ( float )( h2 ); x0 = ( float )( x + 1 - offs); x1 = ( float )( x + 1 - offs); - z0 = ( float )( z ); - z1 = ( float )( z + 1 ); + z0 = static_cast(z); + z1 = static_cast(z + 1); } @@ -4172,8 +4172,8 @@ bool TileRenderer_SPU::tesselateWaterInWorld( Tile_SPU* tt, int x, int y, int z t->color( c11 * br * r, c11 * br * g, c11 * br * b ); t->vertexUV( ( float )( x0 ), ( float )( y + hh0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v01 ) ); t->vertexUV( ( float )( x1 ), ( float )( y + hh1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v02 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); } @@ -4586,7 +4586,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti else { /*#ifdef _DEBUG - if(dynamic_cast(tt)!=NULL) + if(dynamic_cast(tt)!=nullptr) { // stair tile faceFlags |= tt->shouldRenderFace( level, pX, pY - 1, pZ, 0 ) ? 0x01 : 0; @@ -4786,7 +4786,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4g *= ll4; c4b *= ll4; - renderFaceDown( tt, ( float )pX, ( float )pY, ( float )pZ, getTexture( tt, level, pX, pY, pZ, 0 ) ); + renderFaceDown( tt, static_cast(pX), static_cast(pY), static_cast(pZ), getTexture( tt, level, pX, pY, pZ, 0 ) ); } if ( faceFlags & 0x02 ) { @@ -4878,7 +4878,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4b *= ll4; - renderFaceUp( tt, ( float )pX, ( float )pY, ( float )pZ, getTexture( tt, level, pX, pY, pZ, 1 ) ); + renderFaceUp( tt, static_cast(pX), static_cast(pY), static_cast(pZ), getTexture( tt, level, pX, pY, pZ, 1 ) ); } if ( faceFlags & 0x04 ) { @@ -4946,14 +4946,14 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); + ll1 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX0)); + ll2 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX1)); + ll3 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX1)); + ll4 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX0)); int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); @@ -4998,7 +4998,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti Icon_SPU *tex = getTexture(tt, level, pX, pY, pZ, 2); - renderNorth( tt, ( float )pX, ( float )pY, ( float )pZ, tex ); + renderNorth( tt, static_cast(pX), static_cast(pY), static_cast(pZ), tex ); if ( fancy && (tex == &Tile_SPU::ms_pTileData->iconData[Tile_SPU::grass_Id] && !hasFixedTexture() )) { @@ -5015,7 +5015,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c3b *= pBaseBlue; c4b *= pBaseBlue; bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderNorth( tt, ( float )pX, ( float )pY, ( float )pZ, GrassTile_SPU::getSideTextureOverlay() ); + renderNorth( tt, static_cast(pX), static_cast(pY), static_cast(pZ), GrassTile_SPU::getSideTextureOverlay() ); t->setMipmapEnable( prev ); } } @@ -5082,14 +5082,14 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); + ll1 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX0)); + ll2 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX0)); + ll3 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX1)); + ll4 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX1)); int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); @@ -5134,7 +5134,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4g *= ll4; c4b *= ll4; Icon_SPU *tex = getTexture(tt, level, pX, pY, pZ, 3); - renderSouth( tt, ( float )pX, ( float )pY, ( float )pZ, getTexture(tt, level, pX, pY, pZ, 3 ) ); + renderSouth( tt, static_cast(pX), static_cast(pY), static_cast(pZ), getTexture(tt, level, pX, pY, pZ, 3 ) ); if ( fancy && (tex == &Tile_SPU::ms_pTileData->iconData[Tile_SPU::grass_Id] && !hasFixedTexture() )) { @@ -5151,7 +5151,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c3b *= pBaseBlue; c4b *= pBaseBlue; bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderSouth( tt, ( float )pX, ( float )pY, ( float )pZ, GrassTile_SPU::getSideTextureOverlay() ); + renderSouth( tt, static_cast(pX), static_cast(pY), static_cast(pZ), GrassTile_SPU::getSideTextureOverlay() ); t->setMipmapEnable( prev ); } } @@ -5217,14 +5217,14 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ1); - ll2 = (float) (_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ0); - ll3 = (float) (_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ0); - ll4 = (float) (_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ1); + ll1 = static_cast(_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) + * tileShapeZ1); + ll2 = static_cast(_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) + * tileShapeZ0); + ll3 = static_cast(_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) + * tileShapeZ0); + ll4 = static_cast(_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) + * tileShapeZ1); int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); @@ -5269,7 +5269,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4g *= ll4; c4b *= ll4; Icon_SPU *tex = getTexture(tt, level, pX, pY, pZ, 4); - renderWest( tt, ( float )pX, ( float )pY, ( float )pZ, tex ); + renderWest( tt, static_cast(pX), static_cast(pY), static_cast(pZ), tex ); if ( fancy && (tex == &Tile_SPU::ms_pTileData->iconData[Tile_SPU::grass_Id] && !hasFixedTexture() )) { @@ -5286,7 +5286,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c3b *= pBaseBlue; c4b *= pBaseBlue; bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderWest( tt, ( float )pX, ( float )pY, ( float )pZ, GrassTile_SPU::getSideTextureOverlay() ); + renderWest( tt, static_cast(pX), static_cast(pY), static_cast(pZ), GrassTile_SPU::getSideTextureOverlay() ); t->setMipmapEnable( prev ); } } @@ -5352,14 +5352,14 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - ll1 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 - * tileShapeZ1); - ll2 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 - * tileShapeZ0); - ll3 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 - * tileShapeZ0); - ll4 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 - * tileShapeZ1); + ll1 = static_cast(_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 + * tileShapeZ1); + ll2 = static_cast(_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 + * tileShapeZ0); + ll3 = static_cast(_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 + * tileShapeZ0); + ll4 = static_cast(_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 + * tileShapeZ1); int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); @@ -5405,7 +5405,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4b *= ll4; Icon_SPU *tex = getTexture(tt, level, pX, pY, pZ, 5); - renderEast( tt, ( float )pX, ( float )pY, ( float )pZ, tex ); + renderEast( tt, static_cast(pX), static_cast(pY), static_cast(pZ), tex ); if ( fancy && (tex == &Tile_SPU::ms_pTileData->iconData[Tile_SPU::grass_Id] && !hasFixedTexture() )) { c1r *= pBaseRed; @@ -5422,7 +5422,7 @@ bool TileRenderer_SPU::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Ti c4b *= pBaseBlue; bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderEast( tt, ( float )pX, ( float )pY, ( float )pZ, GrassTile_SPU::getSideTextureOverlay() ); + renderEast( tt, static_cast(pX), static_cast(pY), static_cast(pZ), GrassTile_SPU::getSideTextureOverlay() ); t->setMipmapEnable( prev ); } } @@ -6005,8 +6005,8 @@ int TileRenderer_SPU::blend( int a, int b, int c, int def ) int TileRenderer_SPU::blend(int a, int b, int c, int d, float fa, float fb, float fc, float fd) { - int top = (int) ((float) ((a >> 16) & 0xff) * fa + (float) ((b >> 16) & 0xff) * fb + (float) ((c >> 16) & 0xff) * fc + (float) ((d >> 16) & 0xff) * fd) & 0xff; - int bottom = (int) ((float) (a & 0xff) * fa + (float) (b & 0xff) * fb + (float) (c & 0xff) * fc + (float) (d & 0xff) * fd) & 0xff; + int top = static_cast((float)((a >> 16) & 0xff) * fa + (float)((b >> 16) & 0xff) * fb + (float)((c >> 16) & 0xff) * fc + (float)((d >> 16) & 0xff) * fd) & 0xff; + int bottom = static_cast((float)(a & 0xff) * fa + (float)(b & 0xff) * fb + (float)(c & 0xff) * fc + (float)(d & 0xff) * fd) & 0xff; return (top << 16) | bottom; } @@ -7626,7 +7626,7 @@ Icon_SPU *TileRenderer_SPU::getTexture(Tile_SPU *tile) Icon_SPU *TileRenderer_SPU::getTextureOrMissing(Icon_SPU *Icon_SPU) { - if (Icon_SPU == NULL) + if (Icon_SPU == nullptr) { assert(0); // return minecraft->textures->getMissingIcon_SPU(Icon_SPU::TYPE_TERRAIN); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.h index 2c484faaa..3f34a778a 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TileRenderer_SPU.h @@ -72,8 +72,8 @@ public: void tesselateInWorldFixedTexture( Tile_SPU* tile, int x, int y, int z, Icon_SPU *fixedTexture ); // 4J renamed to differentiate from tesselateInWorld void tesselateInWorldNoCulling( Tile_SPU* tile, int x, int y, int z, int forceData = -1, - TileEntity* forceEntity = NULL ); // 4J added forceData, forceEntity param - bool tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL ); // 4J added forceData, forceEntity param + TileEntity* forceEntity = nullptr ); // 4J added forceData, forceEntity param + bool tesselateInWorld( Tile_SPU* tt, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr ); // 4J added forceData, forceEntity param private: bool tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int x, int y, int z); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.cpp index f2dfeaac7..c5a9be4d7 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.cpp @@ -92,7 +92,7 @@ #include #include "AnvilTile_SPU.h" -TileData_SPU* Tile_SPU::ms_pTileData = NULL; +TileData_SPU* Tile_SPU::ms_pTileData = nullptr; Tile_SPU Tile_SPU::m_tiles[256]; @@ -181,7 +181,7 @@ Icon_SPU *Tile_SPU::getTexture(ChunkRebuildData *level, int x, int y, int z, int } - Icon_SPU *icon = NULL; + Icon_SPU *icon = nullptr; if(opaque) { LeafTile_SPU::setFancy(false); @@ -215,13 +215,13 @@ Icon_SPU *Tile_SPU::getTexture(int face) // void Tile_SPU::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, Entity *source) // { // AABB *aabb = getAABB(level, x, y, z); -// if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); +// if (aabb != nullptr && box->intersects(aabb)) boxes->push_back(aabb); // } // // void Tile_SPU::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes) // { // AABB *aabb = getAABB(level, x, y, z); -// if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); +// if (aabb != nullptr && box->intersects(aabb)) boxes->push_back(aabb); // } // // AABB *Tile_SPU::getAABB(Level *level, int x, int y, int z) @@ -368,18 +368,18 @@ Icon_SPU *Tile_SPU::getTexture(int face) // Vec3 *zh0 = a->clipZ(b, zz0); // Vec3 *zh1 = a->clipZ(b, zz1); // -// Vec3 *closest = NULL; +// Vec3 *closest = nullptr; // -// if (containsX(xh0) && (closest == NULL || a->distanceTo(xh0) < a->distanceTo(closest))) closest = xh0; -// if (containsX(xh1) && (closest == NULL || a->distanceTo(xh1) < a->distanceTo(closest))) closest = xh1; -// if (containsY(yh0) && (closest == NULL || a->distanceTo(yh0) < a->distanceTo(closest))) closest = yh0; -// if (containsY(yh1) && (closest == NULL || a->distanceTo(yh1) < a->distanceTo(closest))) closest = yh1; -// if (containsZ(zh0) && (closest == NULL || a->distanceTo(zh0) < a->distanceTo(closest))) closest = zh0; -// if (containsZ(zh1) && (closest == NULL || a->distanceTo(zh1) < a->distanceTo(closest))) closest = zh1; +// if (containsX(xh0) && (closest == nullptr || a->distanceTo(xh0) < a->distanceTo(closest))) closest = xh0; +// if (containsX(xh1) && (closest == nullptr || a->distanceTo(xh1) < a->distanceTo(closest))) closest = xh1; +// if (containsY(yh0) && (closest == nullptr || a->distanceTo(yh0) < a->distanceTo(closest))) closest = yh0; +// if (containsY(yh1) && (closest == nullptr || a->distanceTo(yh1) < a->distanceTo(closest))) closest = yh1; +// if (containsZ(zh0) && (closest == nullptr || a->distanceTo(zh0) < a->distanceTo(closest))) closest = zh0; +// if (containsZ(zh1) && (closest == nullptr || a->distanceTo(zh1) < a->distanceTo(closest))) closest = zh1; // // LeaveCriticalSection(&m_csShape); // -// if (closest == NULL) return NULL; +// if (closest == nullptr) return nullptr; // // int face = -1; // @@ -395,19 +395,19 @@ Icon_SPU *Tile_SPU::getTexture(int face) // // bool Tile_SPU::containsX(Vec3 *v) // { -// if( v == NULL) return false; +// if( v == nullptr) return false; // return v->y >= yy0 && v->y <= yy1 && v->z >= zz0 && v->z <= zz1; // } // // bool Tile_SPU::containsY(Vec3 *v) // { -// if( v == NULL) return false; +// if( v == nullptr) return false; // return v->x >= xx0 && v->x <= xx1 && v->z >= zz0 && v->z <= zz1; // } // // bool Tile_SPU::containsZ(Vec3 *v) // { -// if( v == NULL) return false; +// if( v == nullptr) return false; // return v->x >= xx0 && v->x <= xx1 && v->y >= yy0 && v->y <= yy1; // } // @@ -516,7 +516,7 @@ void Tile_SPU::updateDefaultShape() // // 4J Stu - Special case - only record a crop destroy if is fully grown // if(id==Tile_SPU::crops_Id) // { -// if( Tile_SPU::crops->getResource(data, NULL, 0) > 0 ) +// if( Tile_SPU::crops->getResource(data, nullptr, 0) > 0 ) // player->awardStat(Stats::blocksMined[id], 1); // } // else @@ -533,7 +533,7 @@ void Tile_SPU::updateDefaultShape() // if (isCubeShaped() && !isEntityTile[id] && EnchantmentHelper::hasSilkTouch(player->inventory)) // { // shared_ptr item = getSilkTouchItemInstance(data); -// if (item != NULL) +// if (item != nullptr) // { // popResource(level, x, y, z, item); // } @@ -625,7 +625,7 @@ float Tile_SPU::getShadeBrightness(ChunkRebuildData *level, int x, int y, int z) Tile_SPU* Tile_SPU::createFromID( int tileID ) { if(tileID == 0) - return NULL; + return nullptr; if(m_tiles[tileID].id != -1) return &m_tiles[tileID]; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.h index 484823efa..e3d11f044 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/Tile_SPU.h @@ -242,7 +242,7 @@ public: Icon_SPU *getTexture(int face, int data); Icon_SPU *getTexture(int face); public: - void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param double getShapeX0(); double getShapeX1(); double getShapeY0(); @@ -465,7 +465,7 @@ public: double getShapeZ1() { return ms_pTileData->zz1[id]; } Material_SPU* getMaterial(); - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL); // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr); // 4J added forceData, forceEntity param virtual void updateDefaultShape(); virtual void setShape(float x0, float y0, float z0, float x1, float y1, float z1); virtual float getBrightness(ChunkRebuildData *level, int x, int y, int z); diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TopSnowTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TopSnowTile_SPU.h index 2b5f86a58..43cffbf8e 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TopSnowTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TopSnowTile_SPU.h @@ -14,7 +14,7 @@ public: bool blocksLight() { return false; } bool isSolidRender(bool isServerLevel = false) { return false; } bool isCubeShaped() { return false; } - void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { int height = level->getData(x, y, z) & HEIGHT_MASK; float o = 2 * (1 + height) / 16.0f; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TrapDoorTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TrapDoorTile_SPU.h index 6f096a17f..4f72c543f 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TrapDoorTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/TrapDoorTile_SPU.h @@ -21,7 +21,7 @@ public: bool isSolidRender(bool isServerLevel = false) { return false; } bool isCubeShaped() { return false; } int getRenderShape() { return Tile_SPU::SHAPE_BLOCK;} - void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { setShape(level->getData(x, y, z)); } diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/VineTile_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/VineTile_SPU.h index e2f4a4ad4..7d94e750d 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/VineTile_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/VineTile_SPU.h @@ -27,7 +27,7 @@ public: return false; } - virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = NULL) // 4J added forceData, forceEntity param + virtual void updateShape(ChunkRebuildData *level, int x, int y, int z, int forceData = -1, TileEntity* forceEntity = nullptr) // 4J added forceData, forceEntity param { const float thickness = 1.0f / 16.0f; diff --git a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/stubs_SPU.h b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/stubs_SPU.h index e298ae2dc..7065210fe 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/stubs_SPU.h +++ b/Minecraft.Client/PS3/SPU_Tasks/ChunkUpdate/stubs_SPU.h @@ -172,15 +172,15 @@ public: // { // public: // ZipFile(File *file) {} -// InputStream *getInputStream(ZipEntry *entry) { return NULL; } -// ZipEntry *getEntry(const wstring& name) {return NULL;} +// InputStream *getInputStream(ZipEntry *entry) { return nullptr; } +// ZipEntry *getEntry(const wstring& name) {return nullptr;} // void close() {} // }; // // class ImageIO // { // public: -// static BufferedImage *read(InputStream *in) { return NULL; } +// static BufferedImage *read(InputStream *in) { return nullptr; } // }; // // class Keyboard diff --git a/Minecraft.Client/PS3/SPU_Tasks/CompressedTile/CompressedTileStorage_SPU.cpp b/Minecraft.Client/PS3/SPU_Tasks/CompressedTile/CompressedTileStorage_SPU.cpp index dc134ecaf..16ea17bb5 100644 --- a/Minecraft.Client/PS3/SPU_Tasks/CompressedTile/CompressedTileStorage_SPU.cpp +++ b/Minecraft.Client/PS3/SPU_Tasks/CompressedTile/CompressedTileStorage_SPU.cpp @@ -315,7 +315,7 @@ void TileCompressData_SPU::loadAndUncompressLowerSection(int block, int x0, int // tile IDs first // --------------------------- - if(m_lowerBlocks[block] != NULL) + if(m_lowerBlocks[block] != nullptr) { int dmaSize = padTo16(m_lowerBlocksSize[block]); DmaData_SPU::getAndWait(m_pTileStorage->getDataPtr(), (uint32_t)m_lowerBlocks[block], dmaSize); @@ -366,7 +366,7 @@ void TileCompressData_SPU::loadAndUncompressLowerSection(int block, int x0, int void TileCompressData_SPU::loadAndUncompressUpperSection(int block, int x0, int z0, int x1, int z1) { - if(m_upperBlocks[block] != NULL) + if(m_upperBlocks[block] != nullptr) { int dmaSize = padTo16(m_upperBlocksSize[block]); DmaData_SPU::getAndWait(m_pTileStorage->getDataPtr(), (uint32_t)m_upperBlocks[block], dmaSize); @@ -507,7 +507,7 @@ void TileCompressData_SPU::setForChunk( Region* region, int x0, int y0, int z0 ) } else { - m_lowerBlocks[i*3+j] = NULL; + m_lowerBlocks[i*3+j] = nullptr; m_lowerBlocksSize[i*3+j] = 0; m_lowerSkyLight[i*3+j] = 0; m_lowerBlockLight[i*3+j] = 0; @@ -527,7 +527,7 @@ void TileCompressData_SPU::setForChunk( Region* region, int x0, int y0, int z0 ) } else { - m_upperBlocks[i*3+j] = NULL; + m_upperBlocks[i*3+j] = nullptr; m_upperBlocksSize[i*3+j] = 0; m_upperSkyLight[i*3+j] = 0; m_upperBlockLight[i*3+j] = 0; diff --git a/Minecraft.Client/PSVita/4JLibs/inc/4J_Input.h b/Minecraft.Client/PSVita/4JLibs/inc/4J_Input.h index c0209eb66..644ab3e74 100644 --- a/Minecraft.Client/PSVita/4JLibs/inc/4J_Input.h +++ b/Minecraft.Client/PSVita/4JLibs/inc/4J_Input.h @@ -145,8 +145,8 @@ public: void SetMenuDisplayed(int iPad, bool bVal); -// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); -// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); +// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); +// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); EKeyboardResult RequestKeyboard(LPCWSTR Title, LPCWSTR Text, DWORD dwPad, UINT uiMaxChars, int( *Func)(LPVOID,const bool),LPVOID lpParam,C_4JInput::EKeyboardMode eMode); void GetText(uint16_t *UTF16String); diff --git a/Minecraft.Client/PSVita/4JLibs/inc/4J_Profile.h b/Minecraft.Client/PSVita/4JLibs/inc/4J_Profile.h index ab6b6131f..4c1f4e013 100644 --- a/Minecraft.Client/PSVita/4JLibs/inc/4J_Profile.h +++ b/Minecraft.Client/PSVita/4JLibs/inc/4J_Profile.h @@ -191,7 +191,7 @@ public: ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void InitialiseTrophies(); //CD - Don't use this, auto setup after login void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); + CXuiStringTable*pStringTable=nullptr, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=nullptr, unsigned int uiThemeSize=0L); int GetAwardId(int iAwardNumber); eAwardType GetAwardType(int iAwardNumber); bool CanBeAwarded(int iQuadrant, int iAwardNumber); diff --git a/Minecraft.Client/PSVita/4JLibs/inc/4J_Render.h b/Minecraft.Client/PSVita/4JLibs/inc/4J_Render.h index b08c9fba6..e5d19e20e 100644 --- a/Minecraft.Client/PSVita/4JLibs/inc/4J_Render.h +++ b/Minecraft.Client/PSVita/4JLibs/inc/4J_Render.h @@ -20,8 +20,8 @@ public: int GetType() { return m_type; } void *GetBufferPointer() { return m_pBuffer; } int GetBufferSize() { return m_bufferSize; } - void Release() { free(m_pBuffer); m_pBuffer = NULL; } - bool Allocated() { return m_pBuffer != NULL; } + void Release() { free(m_pBuffer); m_pBuffer = nullptr; } + bool Allocated() { return m_pBuffer != nullptr; } }; typedef struct @@ -63,7 +63,7 @@ public: void InitialiseContext(); void StartFrame(); void Present(); - void Clear(int flags, D3D11_RECT *pRect = NULL); + void Clear(int flags, D3D11_RECT *pRect = nullptr); void SetClearColour(const float colourRGBA[4]); bool IsWidescreen(); bool IsHiDef(); diff --git a/Minecraft.Client/PSVita/4JLibs/inc/4J_Storage.h b/Minecraft.Client/PSVita/4JLibs/inc/4J_Storage.h index 552c247d4..4c9219a9f 100644 --- a/Minecraft.Client/PSVita/4JLibs/inc/4J_Storage.h +++ b/Minecraft.Client/PSVita/4JLibs/inc/4J_Storage.h @@ -298,7 +298,7 @@ public: // Get details of existing savedata C4JStorage::ESaveGameState GetSavesInfo(int iPad,int ( *Func)(LPVOID lpParam,SAVE_DETAILS *pSaveDetails,const bool),LPVOID lpParam,char *pszSavePackName); // Start search - PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or NULL if not yet received) + PSAVE_DETAILS ReturnSavesInfo(); // Returns result of search (or nullptr if not yet received) void ClearSavesInfo(); // Clears results C4JStorage::ESaveGameState LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo,int( *Func)(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes), LPVOID lpParam); // Get the thumbnail for an individual save referenced by pSaveInfo @@ -374,8 +374,8 @@ public: EDLCStatus GetInstalledDLC(int iPad,int( *Func)(LPVOID, int, int),LPVOID lpParam); CONTENT_DATA& GetDLC(DWORD dw); DWORD GetAvailableDLCCount( int iPad ); - DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive = NULL); - DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL); + DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive = nullptr); + DWORD UnmountInstalledDLC(LPCSTR szMountDrive = nullptr); void GetMountedDLCFileList(const char* szMountDrive, std::vector& fileList); std::string GetMountedPath(std::string szMount); void SetDLCProductCode(const char* szProductCode); diff --git a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.cpp b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.cpp index fc5b190ad..7594f7ec9 100644 --- a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.cpp +++ b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.cpp @@ -311,7 +311,7 @@ extern "C" void gdraw_psp2_wait(U64 fence_val) // // (once or several times) here // SceGxmNotification notify = gdraw_psp2_End(); // // --- again, may issue rendering calls here (but not draw Iggys) - // sceGxmEndScene(imm_ctx, NULL, ¬ify); + // sceGxmEndScene(imm_ctx, nullptr, ¬ify); // // That is, exactly one gdraw_psp2_Begin/_End pair for that scene, and // all IggyPlayerDraws must be inside that pair. That's it. @@ -360,7 +360,7 @@ static void gdraw_gpu_memcpy(GDrawHandleCache *c, void *dst, void *src, U32 num_ 0, 0, SCE_GXM_TRANSFER_COLORKEY_NONE, SCE_GXM_TRANSFER_FORMAT_RAW128, SCE_GXM_TRANSFER_LINEAR, srcp + offs, 0, 0, row_size, SCE_GXM_TRANSFER_FORMAT_RAW128, SCE_GXM_TRANSFER_LINEAR, dstp + offs, 0, 0, row_size, - NULL, 0, NULL); + nullptr, 0, nullptr); offs += num_rows * row_size; } @@ -375,7 +375,7 @@ static void gdraw_gpu_memcpy(GDrawHandleCache *c, void *dst, void *src, U32 num_ 0, 0, SCE_GXM_TRANSFER_COLORKEY_NONE, SCE_GXM_TRANSFER_FORMAT_RAW128, SCE_GXM_TRANSFER_LINEAR, srcp + offs, 0, 0, row_size, SCE_GXM_TRANSFER_FORMAT_RAW128, SCE_GXM_TRANSFER_LINEAR, dstp + offs, 0, 0, row_size, - NULL, 0, NULL); + nullptr, 0, nullptr); } if (c->is_vertex) @@ -436,7 +436,7 @@ static void api_free_resource(GDrawHandle *r) if (!r->cache->is_vertex) { for (S32 i=0; i < MAX_SAMPLERS; i++) if (gdraw->active_tex[i] == (GDrawTexture *) r) - gdraw->active_tex[i] = NULL; + gdraw->active_tex[i] = nullptr; } } @@ -462,7 +462,7 @@ static void track_dynamic_alloc_attempt(U32 size, U32 align) static void track_dynamic_alloc_failed() { if (gdraw->dynamic_stats.allocs_attempted == gdraw->dynamic_stats.allocs_succeeded + 1) { // warn the first time we run out of mem - IggyGDrawSendWarning(NULL, "GDraw out of dynamic memory"); + IggyGDrawSendWarning(nullptr, "GDraw out of dynamic memory"); } } @@ -506,7 +506,7 @@ GDrawTexture * RADLINK gdraw_psp2_WrappedTextureCreate(SceGxmTexture *tex) { GDrawStats stats = {}; GDrawHandle *p = gdraw_res_alloc_begin(gdraw->texturecache, 0, &stats); - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); gdraw_psp2_WrappedTextureChange((GDrawTexture *) p, tex); return (GDrawTexture *) p; } @@ -561,11 +561,11 @@ static U32 tex_linear_stride(U32 width) static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format gformat, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { S32 bytes_pixel = 4; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; SceGxmTextureFormat format = SCE_GXM_TEXTURE_FORMAT_U8U8U8U8_ABGR; if (width > MAX_TEXTURE2D_DIM || height > MAX_TEXTURE2D_DIM) { - IggyGDrawSendWarning(NULL, "GDraw %d x %d texture not supported by hardware (dimension limit %d)", width, height, MAX_TEXTURE2D_DIM); + IggyGDrawSendWarning(nullptr, "GDraw %d x %d texture not supported by hardware (dimension limit %d)", width, height, MAX_TEXTURE2D_DIM); return false; } @@ -611,7 +611,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, if (flags & GDRAW_MAKETEXTURE_FLAGS_mipmap) { rrbool ok; - assert(p->temp_buffer != NULL); + assert(p->temp_buffer != nullptr); ok = gdraw_MipmapBegin(&gdraw->mipmap, width, height, mipmaps, bytes_pixel, p->temp_buffer, p->temp_buffer_bytes); if (!ok) @@ -626,7 +626,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, p->i2 = height; } else { // non-mipmapped textures, we just upload straight to their destination - p->p1 = NULL; + p->p1 = nullptr; p->texture_data = (U8 *)t->raw_ptr; p->num_rows = height; p->stride_in_bytes = base_stride * bytes_pixel; @@ -723,8 +723,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *t, void *unique_id, GDr static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *stats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); + if (t->owner == unique_id || unique_id == nullptr) { gdraw_res_kill(t, stats); } } @@ -744,7 +744,7 @@ static void RADLINK gdraw_DescribeTexture(GDrawTexture *tex, GDraw_Texture_Descr static void RADLINK gdraw_SetAntialiasTexture(S32 width, U8 *rgba) { - if (sceGxmTextureGetData(&gdraw->aa_tex) != NULL) + if (sceGxmTextureGetData(&gdraw->aa_tex) != nullptr) return; assert(width <= MAX_AATEX_WIDTH); @@ -801,7 +801,7 @@ static rrbool RADLINK gdraw_TryLockVertexBuffer(GDrawVertexBuffer *vb, void *uni static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); // @GDRAW_ASSERT + assert(h != nullptr); // @GDRAW_ASSERT if (h->owner == unique_id) gdraw_res_kill(h, stats); } @@ -931,8 +931,8 @@ static void set_common_renderstate() // clear our state caching memset(gdraw->active_tex, 0, sizeof(gdraw->active_tex)); gdraw->scissor_state = 0; - gdraw->cur_fp = NULL; - gdraw->cur_vp = NULL; + gdraw->cur_fp = nullptr; + gdraw->cur_vp = nullptr; // all the state we won't touch again until we're done rendering sceGxmSetCullMode(gxm, SCE_GXM_CULL_NONE); @@ -1032,7 +1032,7 @@ static void RADLINK gdraw_SetViewSizeAndWorldScale(S32 w, S32 h, F32 scalex, F32 // must include anything necessary for texture creation/update static void RADLINK gdraw_RenderingBegin(void) { - assert(gdraw->gxm != NULL); // call after gdraw_psp2_Begin + assert(gdraw->gxm != nullptr); // call after gdraw_psp2_Begin set_common_renderstate(); } @@ -1061,7 +1061,7 @@ static void RADLINK gdraw_RenderTileBegin(S32 x0, S32 y0, S32 x1, S32 y1, S32 pa // clear our depth/stencil buffers (and also color if requested) clear_whole_surf(true, true, gdraw->next_tile_clear, stats); - gdraw->next_tile_clear = NULL; + gdraw->next_tile_clear = nullptr; } static void RADLINK gdraw_RenderTileEnd(GDrawStats *stats) @@ -1079,7 +1079,7 @@ void gdraw_psp2_Begin(SceGxmContext *context, const SceGxmColorSurface *color, c { U32 xmin, ymin, xmax, ymax; - assert(gdraw->gxm == NULL); // may not nest Begin calls + assert(gdraw->gxm == nullptr); // may not nest Begin calls // need to wait for the buffer to become idle before we can use it! gdraw_psp2_WaitForDynamicBufferIdle(dynamic_buf); @@ -1106,7 +1106,7 @@ void gdraw_psp2_Begin(SceGxmContext *context, const SceGxmColorSurface *color, c // - We need the stencil buffer to support Flash masking operations. // - We need the mask bit to perform pixel-accurate scissor testing. // There's only one format that satisfies both requirements. - IggyGDrawSendWarning(NULL, "Iggy rendering will not work correctly unless a depth/stencil buffer in DF32M_S8 format is provided."); + IggyGDrawSendWarning(nullptr, "Iggy rendering will not work correctly unless a depth/stencil buffer in DF32M_S8 format is provided."); } // For immediate contexts, we need to flush pending vertex transfers before @@ -1125,15 +1125,15 @@ SceGxmNotification gdraw_psp2_End() GDrawStats gdraw_stats = {}; SceGxmNotification notify; - assert(gdraw->gxm != NULL); // please keep Begin / End pairs properly matched + assert(gdraw->gxm != nullptr); // please keep Begin / End pairs properly matched notify = scene_end_notification(); gdraw->dyn_buf->sync = gdraw->scene_end_fence.value; gdraw->dyn_buf->stats = gdraw->dynamic_stats; - gdraw_arena_init(&gdraw->dynamic, NULL, 0); - gdraw->gxm = NULL; - gdraw->dyn_buf = NULL; + gdraw_arena_init(&gdraw->dynamic, nullptr, 0); + gdraw->gxm = nullptr; + gdraw->dyn_buf = nullptr; // NOTE: the stats from these go nowhere. That's a bit unfortunate, but the // GDrawStats model is that things can be accounted to something in the @@ -1173,13 +1173,13 @@ static void RADLINK gdraw_GetInfo(GDrawInfo *d) static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_texture_format format, U32 flags, void *owner, GDrawStats *stats) { - IggyGDrawSendWarning(NULL, "GDraw no rendertarget support on PSP2"); + IggyGDrawSendWarning(nullptr, "GDraw no rendertarget support on PSP2"); return false; } static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) { - return NULL; + return nullptr; } //////////////////////////////////////////////////////////////////////// @@ -1190,13 +1190,13 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) static void RADLINK gdraw_ClearStencilBits(U32 bits) { GDrawStats stats = {}; - clear_whole_surf(false, true, NULL, &stats); + clear_whole_surf(false, true, nullptr, &stats); } static void RADLINK gdraw_ClearID(void) { GDrawStats stats = {}; - clear_whole_surf(true, false, NULL, &stats); + clear_whole_surf(true, false, nullptr, &stats); } //////////////////////////////////////////////////////////////////////// @@ -1451,7 +1451,7 @@ static GDrawHandle *check_resource(void *ptr) #define check_resource(ptr) ((GDrawHandle *)(ptr)) #endif -static RADINLINE void fence_resources(void *r1, void *r2=NULL, void *r3=NULL) +static RADINLINE void fence_resources(void *r1, void *r2=nullptr, void *r3=nullptr) { GDrawFence fence = get_next_fence(); if (r1) check_resource(r1)->fence = fence; @@ -1592,7 +1592,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 // actual filter effects and special blends aren't supported on PSP2. if (r->blend_mode == GDRAW_BLEND_filter || r->blend_mode == GDRAW_BLEND_special) { - IggyGDrawSendWarning(NULL, "GDraw no filter or special blend support on PSP2"); + IggyGDrawSendWarning(nullptr, "GDraw no filter or special blend support on PSP2"); // just don't do anything. } else { // just a plain quad. @@ -1614,7 +1614,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 static bool gxm_check(SceGxmErrorCode err) { if (err != SCE_OK) - IggyGDrawSendWarning(NULL, "GXM error"); + IggyGDrawSendWarning(nullptr, "GXM error"); return err == SCE_OK; } @@ -1643,9 +1643,9 @@ static bool register_and_create_vertex_prog(SceGxmVertexProgram **out_prog, SceG SceGxmVertexStream stream; if (!register_shader(patcher, shader)) - return NULL; + return nullptr; - *out_prog = NULL; + *out_prog = nullptr; if (attr_bytes) { attr.streamIndex = 0; @@ -1659,7 +1659,7 @@ static bool register_and_create_vertex_prog(SceGxmVertexProgram **out_prog, SceG return gxm_check(sceGxmShaderPatcherCreateVertexProgram(patcher, shader->id, &attr, 1, &stream, 1, out_prog)); } else - return gxm_check(sceGxmShaderPatcherCreateVertexProgram(patcher, shader->id, NULL, 0, NULL, 0, out_prog)); + return gxm_check(sceGxmShaderPatcherCreateVertexProgram(patcher, shader->id, nullptr, 0, nullptr, 0, out_prog)); } static void destroy_vertex_prog(SceGxmShaderPatcher *patcher, SceGxmVertexProgram *prog) @@ -1670,8 +1670,8 @@ static void destroy_vertex_prog(SceGxmShaderPatcher *patcher, SceGxmVertexProgra static bool create_fragment_prog(SceGxmFragmentProgram **out_prog, SceGxmShaderPatcher *patcher, ShaderCode *shader, const SceGxmBlendInfo *blend, SceGxmOutputRegisterFormat out_fmt) { - *out_prog = NULL; - return gxm_check(sceGxmShaderPatcherCreateFragmentProgram(patcher, shader->id, out_fmt, SCE_GXM_MULTISAMPLE_NONE, blend, NULL, out_prog)); + *out_prog = nullptr; + return gxm_check(sceGxmShaderPatcherCreateFragmentProgram(patcher, shader->id, out_fmt, SCE_GXM_MULTISAMPLE_NONE, blend, nullptr, out_prog)); } static void destroy_fragment_prog(SceGxmShaderPatcher *patcher, SceGxmFragmentProgram *prog) @@ -1731,10 +1731,10 @@ static bool create_all_programs(SceGxmOutputRegisterFormat reg_format) } if (!register_shader(patcher, pshader_manual_clear_arr) || - !create_fragment_prog(&gdraw->clear_fp, patcher, pshader_manual_clear_arr, NULL, reg_format)) + !create_fragment_prog(&gdraw->clear_fp, patcher, pshader_manual_clear_arr, nullptr, reg_format)) return false; - gdraw->mask_update_fp = NULL; + gdraw->mask_update_fp = nullptr; return gxm_check(sceGxmShaderPatcherCreateMaskUpdateFragmentProgram(patcher, &gdraw->mask_update_fp)); } @@ -1786,7 +1786,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_psp2_resourcetype type, U32 ali one_pool_bytes = align_down(one_pool_bytes / 2, align); if (one_pool_bytes < (S32)align) - return NULL; + return nullptr; cache = (GDrawHandleCache *) IggyGDrawMalloc(cache_size + header_size); if (cache) { @@ -1805,7 +1805,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_psp2_resourcetype type, U32 ali cache->alloc = gfxalloc_create(gdraw_limits[type].ptr, one_pool_bytes, align, num_handles); if (!cache->alloc) { IggyGDrawFree(cache); - return NULL; + return nullptr; } if (use_twopool) { @@ -1813,7 +1813,7 @@ static GDrawHandleCache *make_handle_cache(gdraw_psp2_resourcetype type, U32 ali if (!cache->alloc_other) { IggyGDrawFree(cache->alloc); IggyGDrawFree(cache); - return NULL; + return nullptr; } // two dummy copies to make sure we have gpu read/write access @@ -1898,12 +1898,12 @@ int gdraw_psp2_SetResourceMemory(gdraw_psp2_resourcetype type, S32 num_handles, case GDRAW_PSP2_RESOURCE_texture: free_handle_cache(gdraw->texturecache); gdraw->texturecache = make_handle_cache(GDRAW_PSP2_RESOURCE_texture, GDRAW_PSP2_TEXTURE_ALIGNMENT, true); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_PSP2_RESOURCE_vertexbuffer: free_handle_cache(gdraw->vbufcache); gdraw->vbufcache = make_handle_cache(GDRAW_PSP2_RESOURCE_vertexbuffer, GDRAW_PSP2_VERTEXBUFFER_ALIGNMENT, true); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; default: return 0; @@ -1912,8 +1912,8 @@ int gdraw_psp2_SetResourceMemory(gdraw_psp2_resourcetype type, S32 num_handles, void gdraw_psp2_ResetAllResourceMemory() { - gdraw_psp2_SetResourceMemory(GDRAW_PSP2_RESOURCE_texture, 0, NULL, 0); - gdraw_psp2_SetResourceMemory(GDRAW_PSP2_RESOURCE_vertexbuffer, 0, NULL, 0); + gdraw_psp2_SetResourceMemory(GDRAW_PSP2_RESOURCE_texture, 0, nullptr, 0); + gdraw_psp2_SetResourceMemory(GDRAW_PSP2_RESOURCE_vertexbuffer, 0, nullptr, 0); } GDrawFunctions *gdraw_psp2_CreateContext(SceGxmShaderPatcher *shader_patcher, void *context_mem, volatile U32 *notification, SceGxmOutputRegisterFormat reg_format) @@ -1935,7 +1935,7 @@ GDrawFunctions *gdraw_psp2_CreateContext(SceGxmShaderPatcher *shader_patcher, vo }; gdraw = (GDraw *) IggyGDrawMalloc(sizeof(*gdraw)); - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -1961,7 +1961,7 @@ GDrawFunctions *gdraw_psp2_CreateContext(SceGxmShaderPatcher *shader_patcher, vo if (!gdraw->quad_ib || !gdraw->mask_ib || !create_all_programs(reg_format)) { gdraw_psp2_DestroyContext(); - return NULL; + return nullptr; } // init quad index buffer @@ -1977,7 +1977,7 @@ GDrawFunctions *gdraw_psp2_CreateContext(SceGxmShaderPatcher *shader_patcher, vo gdraw->mask_draw_gpu = gdraw_arena_alloc(&gdraw->context_arena, sceGxmGetPrecomputedDrawSize(gdraw->mask_vp), SCE_GXM_PRECOMPUTED_ALIGNMENT); if (!gdraw->mask_draw_gpu) { gdraw_psp2_DestroyContext(); - return NULL; + return nullptr; } memcpy(gdraw->mask_ib, mask_ib_data, sizeof(mask_ib_data)); @@ -2048,7 +2048,7 @@ void gdraw_psp2_DestroyContext(void) free_handle_cache(gdraw->vbufcache); destroy_all_programs(); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } } @@ -2070,7 +2070,7 @@ void RADLINK gdraw_psp2_EndCustomDraw(IggyCustomDrawCallbackRegion *region) GDrawTexture * RADLINK gdraw_psp2_MakeTextureFromResource(U8 *file_in_memory, S32 len, IggyFileTexturePSP2 *tex) { - SceGxmErrorCode (*init_func)(SceGxmTexture *texture, const void *data, SceGxmTextureFormat texFormat, uint32_t width, uint32_t height, uint32_t mipCount) = NULL; + SceGxmErrorCode (*init_func)(SceGxmTexture *texture, const void *data, SceGxmTextureFormat texFormat, uint32_t width, uint32_t height, uint32_t mipCount) = nullptr; switch (tex->texture.type) { case SCE_GXM_TEXTURE_SWIZZLED: init_func = sceGxmTextureInitSwizzled; break; @@ -2080,15 +2080,15 @@ GDrawTexture * RADLINK gdraw_psp2_MakeTextureFromResource(U8 *file_in_memory, S3 } if (!init_func) { - IggyGDrawSendWarning(NULL, "Unsupported texture type in MakeTextureFromResource"); - return NULL; + IggyGDrawSendWarning(nullptr, "Unsupported texture type in MakeTextureFromResource"); + return nullptr; } SceGxmTexture gxm; SceGxmErrorCode err = init_func(&gxm, file_in_memory + tex->file_offset, (SceGxmTextureFormat)tex->texture.format, tex->texture.width, tex->texture.height, tex->texture.mip_count); if (err != SCE_OK) { - IggyGDrawSendWarning(NULL, "Texture init failed in MakeTextureFromResource (bad data?)"); - return NULL; + IggyGDrawSendWarning(nullptr, "Texture init failed in MakeTextureFromResource (bad data?)"); + return nullptr; } return gdraw_psp2_WrappedTextureCreate(&gxm); diff --git a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.h b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.h index a606fbe3b..da31de707 100644 --- a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.h +++ b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2.h @@ -68,7 +68,7 @@ IDOC extern int gdraw_psp2_SetResourceMemory(gdraw_psp2_resourcetype type, S32 n mapped to the GPU and *writeable*. If it isn't, the GPU will crash during either this function or CreateContext! - Pass in NULL for "ptr" and zero "num_bytes" to free the memory allocated to + Pass in nullptr for "ptr" and zero "num_bytes" to free the memory allocated to a specific pool. GDraw can run into cases where resource memory gets fragmented; we defragment @@ -121,7 +121,7 @@ IDOC extern GDrawFunctions * gdraw_psp2_CreateContext(SceGxmShaderPatcher *shade be valid for as long as a GDraw context is alive. If initialization fails for some reason (the main reason would be an out of memory condition), - NULL is returned. Otherwise, you can pass the return value to IggySetGDraw. */ + nullptr is returned. Otherwise, you can pass the return value to IggySetGDraw. */ IDOC extern void gdraw_psp2_DestroyContext(void); /* Destroys the current GDraw context, if any. diff --git a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2_shaders.inl b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2_shaders.inl index 9e2870eb2..6b0448f5c 100644 --- a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2_shaders.inl +++ b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_psp2_shaders.inl @@ -532,24 +532,24 @@ static unsigned char pshader_basic_17[436] = { }; static ShaderCode pshader_basic_arr[18] = { - { pshader_basic_0, { NULL } }, - { pshader_basic_1, { NULL } }, - { pshader_basic_2, { NULL } }, - { pshader_basic_3, { NULL } }, - { pshader_basic_4, { NULL } }, - { pshader_basic_5, { NULL } }, - { pshader_basic_6, { NULL } }, - { pshader_basic_7, { NULL } }, - { pshader_basic_8, { NULL } }, - { pshader_basic_9, { NULL } }, - { pshader_basic_10, { NULL } }, - { pshader_basic_11, { NULL } }, - { pshader_basic_12, { NULL } }, - { pshader_basic_13, { NULL } }, - { pshader_basic_14, { NULL } }, - { pshader_basic_15, { NULL } }, - { pshader_basic_16, { NULL } }, - { pshader_basic_17, { NULL } }, + { pshader_basic_0, { nullptr } }, + { pshader_basic_1, { nullptr } }, + { pshader_basic_2, { nullptr } }, + { pshader_basic_3, { nullptr } }, + { pshader_basic_4, { nullptr } }, + { pshader_basic_5, { nullptr } }, + { pshader_basic_6, { nullptr } }, + { pshader_basic_7, { nullptr } }, + { pshader_basic_8, { nullptr } }, + { pshader_basic_9, { nullptr } }, + { pshader_basic_10, { nullptr } }, + { pshader_basic_11, { nullptr } }, + { pshader_basic_12, { nullptr } }, + { pshader_basic_13, { nullptr } }, + { pshader_basic_14, { nullptr } }, + { pshader_basic_15, { nullptr } }, + { pshader_basic_16, { nullptr } }, + { pshader_basic_17, { nullptr } }, }; static unsigned char pshader_manual_clear_0[220] = { @@ -570,7 +570,7 @@ static unsigned char pshader_manual_clear_0[220] = { }; static ShaderCode pshader_manual_clear_arr[1] = { - { pshader_manual_clear_0, { NULL } }, + { pshader_manual_clear_0, { nullptr } }, }; static unsigned char vshader_vspsp2_0[360] = { @@ -664,9 +664,9 @@ static unsigned char vshader_vspsp2_2[336] = { }; static ShaderCode vshader_vspsp2_arr[3] = { - { vshader_vspsp2_0, { NULL } }, - { vshader_vspsp2_1, { NULL } }, - { vshader_vspsp2_2, { NULL } }, + { vshader_vspsp2_0, { nullptr } }, + { vshader_vspsp2_1, { nullptr } }, + { vshader_vspsp2_2, { nullptr } }, }; static unsigned char vshader_vspsp2_mask_0[304] = { @@ -692,6 +692,6 @@ static unsigned char vshader_vspsp2_mask_0[304] = { }; static ShaderCode vshader_vspsp2_mask_arr[1] = { - { vshader_vspsp2_mask_0, { NULL } }, + { vshader_vspsp2_mask_0, { nullptr } }, }; diff --git a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_shared.inl b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_shared.inl index 4fae9c12c..6a439d8f1 100644 --- a/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_shared.inl +++ b/Minecraft.Client/PSVita/Iggy/gdraw/gdraw_shared.inl @@ -226,7 +226,7 @@ static void debug_check_raw_values(GDrawHandleCache *c) s = s->next; } s = c->active; - while (s != NULL) { + while (s != nullptr) { assert(s->raw_ptr != t->raw_ptr); s = s->next; } @@ -368,7 +368,7 @@ static void gdraw_HandleTransitionInsertBefore(GDrawHandle *t, GDrawHandleState { check_lists(t->cache); assert(t->state != GDRAW_HANDLE_STATE_sentinel); // sentinels should never get here! - assert(t->state != (U32) new_state); // code should never call "transition" if it's not transitioning! + assert(t->state != static_cast(new_state)); // code should never call "transition" if it's not transitioning! // unlink from prev state t->prev->next = t->next; t->next->prev = t->prev; @@ -433,7 +433,7 @@ static rrbool gdraw_HandleCacheLockStats(GDrawHandle *t, void *owner, GDrawStats static rrbool gdraw_HandleCacheLock(GDrawHandle *t, void *owner) { - return gdraw_HandleCacheLockStats(t, owner, NULL); + return gdraw_HandleCacheLockStats(t, owner, nullptr); } static void gdraw_HandleCacheUnlock(GDrawHandle *t) @@ -461,11 +461,11 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->is_thrashing = false; c->did_defragment = false; for (i=0; i < GDRAW_HANDLE_STATE__count; i++) { - c->state[i].owner = NULL; - c->state[i].cache = NULL; // should never follow cache link from sentinels! + c->state[i].owner = nullptr; + c->state[i].cache = nullptr; // should never follow cache link from sentinels! c->state[i].next = c->state[i].prev = &c->state[i]; #ifdef GDRAW_MANAGE_MEM - c->state[i].raw_ptr = NULL; + c->state[i].raw_ptr = nullptr; #endif c->state[i].fence.value = 0; c->state[i].bytes = 0; @@ -478,7 +478,7 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->handle[i].bytes = 0; c->handle[i].state = GDRAW_HANDLE_STATE_free; #ifdef GDRAW_MANAGE_MEM - c->handle[i].raw_ptr = NULL; + c->handle[i].raw_ptr = nullptr; #endif } c->state[GDRAW_HANDLE_STATE_free].next = &c->handle[0]; @@ -486,10 +486,10 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->prev_frame_start.value = 0; c->prev_frame_end.value = 0; #ifdef GDRAW_MANAGE_MEM - c->alloc = NULL; + c->alloc = nullptr; #endif #ifdef GDRAW_MANAGE_MEM_TWOPOOL - c->alloc_other = NULL; + c->alloc_other = nullptr; #endif check_lists(c); } @@ -497,14 +497,14 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte static GDrawHandle *gdraw_HandleCacheAllocateBegin(GDrawHandleCache *c) { GDrawHandle *free_list = &c->state[GDRAW_HANDLE_STATE_free]; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (free_list->next != free_list) { t = free_list->next; gdraw_HandleTransitionTo(t, GDRAW_HANDLE_STATE_alloc); t->bytes = 0; t->owner = 0; #ifdef GDRAW_MANAGE_MEM - t->raw_ptr = NULL; + t->raw_ptr = nullptr; #endif #ifdef GDRAW_CORRUPTION_CHECK t->has_check_value = false; @@ -562,7 +562,7 @@ static GDrawHandle *gdraw_HandleCacheGetLRU(GDrawHandleCache *c) // at the front of the LRU list are the oldest ones, since in-use resources // will get appended on every transition from "locked" to "live". GDrawHandle *sentinel = &c->state[GDRAW_HANDLE_STATE_live]; - return (sentinel->next != sentinel) ? sentinel->next : NULL; + return (sentinel->next != sentinel) ? sentinel->next : nullptr; } static void gdraw_HandleCacheTick(GDrawHandleCache *c, GDrawFence now) @@ -777,7 +777,7 @@ static GDrawTexture *gdraw_BlurPass(GDrawFunctions *g, GDrawBlurInfo *c, GDrawRe if (!g->TextureDrawBufferBegin(draw_bounds, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, gstats)) return r->tex[0]; - c->BlurPass(r, taps, data, draw_bounds, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, draw_bounds, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -829,7 +829,7 @@ static GDrawTexture *gdraw_BlurPassDownsample(GDrawFunctions *g, GDrawBlurInfo * assert(clamp[0] <= clamp[2]); assert(clamp[1] <= clamp[3]); - c->BlurPass(r, taps, data, &z, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, &z, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -841,7 +841,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR GDrawTexture *t; F32 data[MAX_TAPS][4]; S32 off_axis = 1-axis; - S32 w = ((S32) ceil((blur_width-1)/2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 + S32 w = static_cast(ceil((blur_width - 1) / 2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 F32 edge_weight = 1 - (w - blur_width)/2; // 3 => 0 => 1; 1.2 => 1.8 => 0.9 => 0.1 F32 inverse_weight = 1.0f / blur_width; @@ -948,7 +948,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR // max coverage is 25 samples, or a filter width of 13. with 7 taps, we sample // 13 samples in one pass, max coverage is 13*13 samples or (13*13-1)/2 width, // which is ((2T-1)*(2T-1)-1)/2 or (4T^2 - 4T + 1 -1)/2 or 2T^2 - 2T or 2T*(T-1) - S32 w_mip = (S32) ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS)); + S32 w_mip = static_cast(ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS))); S32 downsample = w_mip; F32 sample_spacing = texel; if (downsample < 2) downsample = 2; @@ -1094,7 +1094,7 @@ static void make_pool_aligned(void **start, S32 *num_bytes, U32 alignment) if (addr_aligned != addr_orig) { S32 diff = (S32) (addr_aligned - addr_orig); if (*num_bytes < diff) { - *start = NULL; + *start = nullptr; *num_bytes = 0; return; } else { @@ -1131,7 +1131,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) UINTa remaining = arena->end - arena->current; UINTa total_size = (ptr - arena->current) + size; if (remaining < total_size) // doesn't fit - return NULL; + return nullptr; arena->current = ptr + size; return ptr; @@ -1156,7 +1156,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // (i.e. block->next->prev == block->prev->next == block) // - All allocated blocks are also kept in a hash table, indexed by their // pointer (to allow free to locate the corresponding block_info quickly). -// There's a single-linked, NULL-terminated list of elements in each hash +// There's a single-linked, nullptr-terminated list of elements in each hash // bucket. // - The physical block list is ordered. It always contains all currently // active blocks and spans the whole managed memory range. There are no @@ -1165,7 +1165,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // they are coalesced immediately. // - The maximum number of blocks that could ever be necessary is allocated // on initialization. All block_infos not currently in use are kept in a -// single-linked, NULL-terminated list of unused blocks. Every block is either +// single-linked, nullptr-terminated list of unused blocks. Every block is either // in the physical block list or the unused list, and the total number of // blocks is constant. // These invariants always hold before and after an allocation/free. @@ -1383,7 +1383,7 @@ static void gfxalloc_check2(gfx_allocator *alloc) static gfx_block_info *gfxalloc_pop_unused(gfx_allocator *alloc) { - GFXALLOC_ASSERT(alloc->unused_list != NULL); + GFXALLOC_ASSERT(alloc->unused_list != nullptr); GFXALLOC_ASSERT(alloc->unused_list->is_unused); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_unused);) @@ -1456,7 +1456,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma U32 i, max_blocks, size; if (!align || (align & (align - 1)) != 0) // align must be >0 and a power of 2 - return NULL; + return nullptr; // for <= max_allocs live allocs, there's <= 2*max_allocs+1 blocks. worst case: // [free][used][free] .... [free][used][free] @@ -1464,7 +1464,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma size = sizeof(gfx_allocator) + max_blocks * sizeof(gfx_block_info); a = (gfx_allocator *) IggyGDrawMalloc(size); if (!a) - return NULL; + return nullptr; memset(a, 0, size); @@ -1505,16 +1505,16 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma a->blocks[i].is_unused = 1; gfxalloc_check(a); - debug_complete_check(a, NULL, 0,0); + debug_complete_check(a, nullptr, 0,0); return a; } static void *gfxalloc_alloc(gfx_allocator *alloc, U32 size_in_bytes) { - gfx_block_info *cur, *best = NULL; + gfx_block_info *cur, *best = nullptr; U32 i, best_wasted = ~0u; U32 size = size_in_bytes; -debug_complete_check(alloc, NULL, 0,0); +debug_complete_check(alloc, nullptr, 0,0); gfxalloc_check(alloc); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_blocks == alloc->num_alloc + alloc->num_free + alloc->num_unused);) GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_free <= alloc->num_blocks+1);) @@ -1564,7 +1564,7 @@ gfxalloc_check(alloc); debug_check_overlap(alloc->cache, best->ptr, best->size); return best->ptr; } else - return NULL; // not enough space! + return nullptr; // not enough space! } static void gfxalloc_free(gfx_allocator *alloc, void *ptr) @@ -1734,7 +1734,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta // (unused for allocated blocks, we'll use it to store a back-pointer to the corresponding handle) for (b = alloc->blocks[0].next_phys; b != alloc->blocks; b=b->next_phys) if (!b->is_free) - b->prev = NULL; + b->prev = nullptr; // go through all handles and store a pointer to the handle in the corresponding memory block for (i=0; i < c->max_handles; i++) @@ -1747,7 +1747,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta break; } - GFXALLOC_ASSERT(b != NULL); // didn't find this block anywhere! + GFXALLOC_ASSERT(b != nullptr); // didn't find this block anywhere! } // clear alloc hash table (we rebuild it during defrag) @@ -1909,7 +1909,7 @@ static rrbool gdraw_CanDefragment(GDrawHandleCache *c) static rrbool gdraw_MigrateResource(GDrawHandle *t, GDrawStats *stats) { GDrawHandleCache *c = t->cache; - void *ptr = NULL; + void *ptr = nullptr; assert(t->state == GDRAW_HANDLE_STATE_live || t->state == GDRAW_HANDLE_STATE_locked || t->state == GDRAW_HANDLE_STATE_pinned); // anything we migrate should be in the "other" (old) pool @@ -2299,7 +2299,7 @@ static void gdraw_bufring_init(gdraw_bufring * RADRESTRICT ring, void *ptr, U32 static void gdraw_bufring_shutdown(gdraw_bufring * RADRESTRICT ring) { - ring->cur = NULL; + ring->cur = nullptr; ring->seg_size = 0; } @@ -2309,7 +2309,7 @@ static void *gdraw_bufring_alloc(gdraw_bufring * RADRESTRICT ring, U32 size, U32 gdraw_bufring_seg *seg; if (size > ring->seg_size) - return NULL; // nope, won't fit + return nullptr; // nope, won't fit assert(align <= ring->align); @@ -2414,7 +2414,7 @@ static rrbool gdraw_res_free_lru(GDrawHandleCache *c, GDrawStats *stats) // was it referenced since end of previous frame (=in this frame)? // if some, we're thrashing; report it to the user, but only once per frame. if (c->prev_frame_end.value < r->fence.value && !c->is_thrashing) { - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); c->is_thrashing = true; } @@ -2434,8 +2434,8 @@ static GDrawHandle *gdraw_res_alloc_outofmem(GDrawHandleCache *c, GDrawHandle *t { if (t) gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); - return NULL; + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); + return nullptr; } #ifndef GDRAW_MANAGE_MEM @@ -2444,7 +2444,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt { GDrawHandle *t; if (size > c->total_bytes) - gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); else { // given how much data we're going to allocate, throw out // data until there's "room" (this basically lets us use @@ -2452,7 +2452,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // packing it and being exact) while (c->bytes_free < size) { if (!gdraw_res_free_lru(c, stats)) { - gdraw_res_alloc_outofmem(c, NULL, "memory"); + gdraw_res_alloc_outofmem(c, nullptr, "memory"); break; } } @@ -2467,8 +2467,8 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // we'd trade off cost of regenerating) if (gdraw_res_free_lru(c, stats)) { t = gdraw_HandleCacheAllocateBegin(c); - if (t == NULL) { - gdraw_res_alloc_outofmem(c, NULL, "handles"); + if (t == nullptr) { + gdraw_res_alloc_outofmem(c, nullptr, "handles"); } } } @@ -2512,7 +2512,7 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) { GDRAW_FENCE_FLUSH(); // dead list is sorted by fence index - make sure all fence values are current. - r->owner = NULL; + r->owner = nullptr; gdraw_HandleCacheInsertDead(r); gdraw_res_reap(r->cache, stats); } @@ -2520,11 +2520,11 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawStats *stats) { GDrawHandle *t; - void *ptr = NULL; + void *ptr = nullptr; gdraw_res_reap(c, stats); // NB this also does GDRAW_FENCE_FLUSH(); if (size > c->total_bytes) - return gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + return gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); // now try to allocate a handle t = gdraw_HandleCacheAllocateBegin(c); @@ -2536,7 +2536,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt gdraw_res_free_lru(c, stats); t = gdraw_HandleCacheAllocateBegin(c); if (!t) - return gdraw_res_alloc_outofmem(c, NULL, "handles"); + return gdraw_res_alloc_outofmem(c, nullptr, "handles"); } // try to allocate first diff --git a/Minecraft.Client/PSVita/Iggy/include/gdraw.h b/Minecraft.Client/PSVita/Iggy/include/gdraw.h index 404a2642b..7cc4ddd0e 100644 --- a/Minecraft.Client/PSVita/Iggy/include/gdraw.h +++ b/Minecraft.Client/PSVita/Iggy/include/gdraw.h @@ -356,13 +356,13 @@ IDOC typedef struct GDrawPrimitive IDOC typedef void RADLINK gdraw_draw_indexed_triangles(GDrawRenderState *r, GDrawPrimitive *prim, GDrawVertexBuffer *buf, GDrawStats *stats); /* Draws a collection of indexed triangles, ignoring special filters or blend modes. - If buf is NULL, then the pointers in 'prim' are machine pointers, and + If buf is nullptr, then the pointers in 'prim' are machine pointers, and you need to make a copy of the data (note currently all triangles implementing strokes (wide lines) go this path). - If buf is non-NULL, then use the appropriate vertex buffer, and the + If buf is non-nullptr, then use the appropriate vertex buffer, and the pointers in prim are actually offsets from the beginning of the - vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) NULL; + vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) nullptr; (note there are separate spaces for vertices and indices; e.g. the first mesh in a given vertex buffer will normally have a 0 offset for the vertices and a 0 offset for the indices) @@ -455,7 +455,7 @@ IDOC typedef GDrawTexture * RADLINK gdraw_make_texture_end(GDraw_MakeTexture_Pro /* Ends specification of a new texture. $:info The same handle initially passed to $gdraw_make_texture_begin - $:return Handle for the newly created texture, or NULL if an error occured + $:return Handle for the newly created texture, or nullptr if an error occured */ IDOC typedef rrbool RADLINK gdraw_update_texture_begin(GDrawTexture *tex, void *unique_id, GDrawStats *stats); diff --git a/Minecraft.Client/PSVita/Iggy/include/iggyexpruntime.h b/Minecraft.Client/PSVita/Iggy/include/iggyexpruntime.h index 1f1a90a1c..a42ccbfff 100644 --- a/Minecraft.Client/PSVita/Iggy/include/iggyexpruntime.h +++ b/Minecraft.Client/PSVita/Iggy/include/iggyexpruntime.h @@ -25,8 +25,8 @@ IDOC RADEXPFUNC HIGGYEXP RADEXPLINK IggyExpCreate(char *ip_address, S32 port, vo $:storage A small block of storage that needed to store the $HIGGYEXP, must be at least $IGGYEXP_MIN_STORAGE $:storage_size_in_bytes The size of the block pointer to by storage -Returns a NULL HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer -can be contacted at the specified address/port. Otherwise returns a non-NULL $HIGGYEXP +Returns a nullptr HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer +can be contacted at the specified address/port. Otherwise returns a non-nullptr $HIGGYEXP which you can pass to $IggyUseExplorer. */ IDOC RADEXPFUNC void RADEXPLINK IggyExpDestroy(HIGGYEXP p); diff --git a/Minecraft.Client/PSVita/Leaderboards/PSVitaLeaderboardManager.cpp b/Minecraft.Client/PSVita/Leaderboards/PSVitaLeaderboardManager.cpp index 958999e4b..c5a44878d 100644 --- a/Minecraft.Client/PSVita/Leaderboards/PSVitaLeaderboardManager.cpp +++ b/Minecraft.Client/PSVita/Leaderboards/PSVitaLeaderboardManager.cpp @@ -20,7 +20,7 @@ PSVitaLeaderboardManager::PSVitaLeaderboardManager() : SonyLeaderboardManager() HRESULT PSVitaLeaderboardManager::initialiseScoreUtility() { - return sceNpScoreInit( SCE_KERNEL_DEFAULT_PRIORITY_USER, SCE_KERNEL_THREAD_CPU_AFFINITY_MASK_DEFAULT, NULL); + return sceNpScoreInit( SCE_KERNEL_DEFAULT_PRIORITY_USER, SCE_KERNEL_THREAD_CPU_AFFINITY_MASK_DEFAULT, nullptr); } bool PSVitaLeaderboardManager::scoreUtilityAlreadyInitialised(HRESULT hr) diff --git a/Minecraft.Client/PSVita/Network/PSVita_NPToolkit.cpp b/Minecraft.Client/PSVita/Network/PSVita_NPToolkit.cpp index 1c5c45e31..9ed61d214 100644 --- a/Minecraft.Client/PSVita/Network/PSVita_NPToolkit.cpp +++ b/Minecraft.Client/PSVita/Network/PSVita_NPToolkit.cpp @@ -331,7 +331,7 @@ void hexStrToBin( val <<= 4; } else { - if (pBinBuf != NULL && binOffset < binBufSize) { + if (pBinBuf != nullptr && binOffset < binBufSize) { memcpy(pBinBuf + binOffset, &val, 1); val = 0; } @@ -339,7 +339,7 @@ void hexStrToBin( } } - if (val != 0 && pBinBuf != NULL && binOffset < binBufSize) { + if (val != 0 && pBinBuf != nullptr && binOffset < binBufSize) { memcpy(pBinBuf + binOffset, &val, 1); } @@ -403,7 +403,7 @@ void PSVitaNPToolkit::init() // extern void npStateCallback(SceNpServiceState state, int retCode, void *userdata); - ret = sceNpRegisterServiceStateCallback(npStateCallback, NULL); + ret = sceNpRegisterServiceStateCallback(npStateCallback, nullptr); if (ret < 0) { app.DebugPrintf("sceNpRegisterServiceStateCallback() failed. ret = 0x%x\n", ret); diff --git a/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp b/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp index dc9ad61e6..4ba6ae2e5 100644 --- a/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp @@ -45,8 +45,8 @@ int SQRNetworkManager_AdHoc_Vita::m_adhocStatus = false; static unsigned char s_Matching2Pool[SCE_NET_ADHOC_MATCHING_POOLSIZE_DEFAULT]; -int (* SQRNetworkManager_AdHoc_Vita::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = NULL; -void * SQRNetworkManager_AdHoc_Vita::s_SignInCompleteParam = NULL; +int (* SQRNetworkManager_AdHoc_Vita::s_SignInCompleteCallbackFn)(void *pParam, bool bContinue, int pad) = nullptr; +void * SQRNetworkManager_AdHoc_Vita::s_SignInCompleteParam = nullptr; sce::Toolkit::NP::PresenceDetails SQRNetworkManager_AdHoc_Vita::s_lastPresenceInfo; int SQRNetworkManager_AdHoc_Vita::s_resendPresenceCountdown = 0; bool SQRNetworkManager_AdHoc_Vita::s_presenceStatusDirty = false; @@ -127,8 +127,8 @@ SQRNetworkManager_AdHoc_Vita::SQRNetworkManager_AdHoc_Vita(ISQRNetworkManagerLis m_isInSession = false; m_offlineGame = false; m_offlineSQR = false; - m_aServerId = NULL; -// m_gameBootInvite = NULL; + m_aServerId = nullptr; +// m_gameBootInvite = nullptr; m_adhocStatus = false; m_bLinkDisconnected = false; m_bIsInitialised=false; @@ -166,7 +166,7 @@ void SQRNetworkManager_AdHoc_Vita::Initialise() int32_t ret = 0; // int32_t libCtxId = 0; -// ret = sceNpInGameMessageInitialize(NP_IN_GAME_MESSAGE_POOL_SIZE, NULL); +// ret = sceNpInGameMessageInitialize(NP_IN_GAME_MESSAGE_POOL_SIZE, nullptr); // assert (ret >= 0); // libCtxId = ret; @@ -203,7 +203,7 @@ void SQRNetworkManager_AdHoc_Vita::Initialise() // npConf.commId = &s_npCommunicationId; // npConf.commPassphrase = &s_npCommunicationPassphrase; // npConf.commSignature = &s_npCommunicationSignature; -// ret = sceNpInit(&npConf, NULL); +// ret = sceNpInit(&npConf, nullptr); // if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) // { // app.DebugPrintf("sceNpInit failed, ret=%x\n", ret); @@ -388,14 +388,14 @@ bool SQRNetworkManager_AdHoc_Vita::CreateMatchingContext(bool bServer /*= false* // Free up any external data that we received from the previous search - for( int i = 0; i < m_aFriendSearchResults.size(); i++ ) + for( size_t i = 0; i < m_aFriendSearchResults.size(); i++ ) { if(m_aFriendSearchResults[i].m_RoomExtDataReceived) free(m_aFriendSearchResults[i].m_RoomExtDataReceived); - m_aFriendSearchResults[i].m_RoomExtDataReceived = NULL; + m_aFriendSearchResults[i].m_RoomExtDataReceived = nullptr; if(m_aFriendSearchResults[i].m_gameSessionData) free(m_aFriendSearchResults[i].m_gameSessionData); - m_aFriendSearchResults[i].m_gameSessionData = NULL; + m_aFriendSearchResults[i].m_gameSessionData = nullptr; } m_friendCount = 0; m_aFriendSearchResults.clear(); @@ -406,7 +406,7 @@ bool SQRNetworkManager_AdHoc_Vita::CreateMatchingContext(bool bServer /*= false* ret = sceNetAdhocMatchingStart(m_matchingContext, SCE_KERNEL_DEFAULT_PRIORITY_USER, MATCHING_EVENT_HANDLER_STACK_SIZE, SCE_KERNEL_THREAD_CPU_AFFINITY_MASK_DEFAULT, - 0, NULL);//sizeof(g_myInfo.name), &g_myInfo.name); + 0, nullptr);//sizeof(g_myInfo.name), &g_myInfo.name); if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_CONTEXT_START_ASYNC ) ) { @@ -448,7 +448,7 @@ void SQRNetworkManager_AdHoc_Vita::InitialiseAfterOnline() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } return; } @@ -512,7 +512,7 @@ void SQRNetworkManager_AdHoc_Vita::Tick() // if( ( m_gameBootInvite m) && ( s_safeToRespondToGameBootInvite ) ) // { // m_listener->HandleInviteReceived( ProfileManager.GetPrimaryPad(), m_gameBootInvite ); -// m_gameBootInvite = NULL; +// m_gameBootInvite = nullptr; // } ErrorHandlingTick(); @@ -585,7 +585,7 @@ void SQRNetworkManager_AdHoc_Vita::ErrorHandlingTick() { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } app.DebugPrintf("Network error: SNM_INT_STATE_INITIALISE_FAILED\n"); if( m_isInSession && m_offlineSQR ) @@ -777,7 +777,7 @@ void SQRNetworkManager_AdHoc_Vita::FriendSearchTick() // { // m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO; // delete m_getFriendCountThread; -// m_getFriendCountThread = NULL; +// m_getFriendCountThread = nullptr; FriendRoomManagerSearch2(); // } } @@ -797,7 +797,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // // do // { -// ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); +// ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, nullptr); // // // 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 ) @@ -855,7 +855,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // // 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; +// SceNpId* friendIDs = nullptr; // if(manager->m_friendCount > 0) // { // // grab all the friend IDs first @@ -995,7 +995,7 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerByIndex(int idx) } else { - return NULL; + return nullptr; } } @@ -1012,7 +1012,7 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerBySmallId(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetLocalPlayerByUserIndex(int idx) @@ -1028,7 +1028,7 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetLocalPlayerByUserIndex(int id } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetHostPlayer() @@ -1041,11 +1041,11 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetHostPlayer() SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerIfReady(SQRNetworkPlayer *player) { - if( player == NULL ) return NULL; + if( player == nullptr ) return nullptr; if( player->IsReady() ) return player; - return NULL; + return nullptr; } // Update state internally @@ -1086,7 +1086,7 @@ void SQRNetworkManager_AdHoc_Vita::ResetToIdle() { memberIDs.push_back(m_aRoomSlotPlayers[i]->m_roomMemberId); } - for(int i=0;im_extData, searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId); - return JoinRoom(searchResult->m_netAddr, localPlayerMask, NULL); + return JoinRoom(searchResult->m_netAddr, localPlayerMask, nullptr); } bool SQRNetworkManager_AdHoc_Vita::JoinRoom(SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId, int localPlayerMask, const PresenceSyncInfo *presence) @@ -1137,7 +1137,7 @@ bool SQRNetworkManager_AdHoc_Vita::JoinRoom(SceNetInAddr netAddr, int localPlaye } else { - for(int i=0;im_type != SQRNetworkPlayer::SNP_TYPE_REMOTE ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1446,7 +1446,7 @@ void SQRNetworkManager_AdHoc_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*= if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_LOCAL ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1538,7 +1538,7 @@ void SQRNetworkManager_AdHoc_Vita::UpdatePlayersFromRoomSyncUIDs() } // Host only - add remote players to our internal storage of player slots, and synchronise this with other room members. -bool SQRNetworkManager_AdHoc_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==NULL*/ ) +bool SQRNetworkManager_AdHoc_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==nullptr*/ ) { assert( m_isHosting ); @@ -1658,7 +1658,7 @@ void SQRNetworkManager_AdHoc_Vita::RemoveRemotePlayersAndSync( SceNpMatching2Roo } // Zero last element, that isn't part of the currently sized array anymore memset(&m_roomSyncData.players[m_roomSyncData.getPlayerCount()],0,sizeof(PlayerSyncData)); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; } else { @@ -1701,7 +1701,7 @@ void SQRNetworkManager_AdHoc_Vita::RemoveNetworkPlayers( int mask ) { if( m_aRoomSlotPlayers[i] == player ) { - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } // And delete the reference from the ctx->player map @@ -1807,7 +1807,7 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe // check we don't have this already int currIndex = -1; bool bChanged = false; - for(int i=0; im_aFriendSearchResults.size(); i++) + for(size_t i=0; im_aFriendSearchResults.size(); i++) { if(manager->m_aFriendSearchResults[i].m_netAddr.s_addr == peer->s_addr) { @@ -1843,7 +1843,7 @@ 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 != nullptr) { ret = SCE_OK;// parentRequestAdd(opt); if (ret != SCE_OK) @@ -1987,7 +1987,7 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe { app.DebugPrintf("P2P SCE_NET_ADHOC_MATCHING_EVENT_DATA Received!!\n"); - if (optlen <= 0 || opt == NULL) + if (optlen <= 0 || opt == nullptr) { assert(0); break; @@ -2270,7 +2270,7 @@ bool SQRNetworkManager_AdHoc_Vita::CreateRudpConnections(SceNetInAddr peer) if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT) ) return false; if( m_isHosting ) { - m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, getRoomMemberID((&peer)), 0, rudpCtx, NULL ); + m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, getRoomMemberID((&peer)), 0, rudpCtx, nullptr ); m_RudpCtxToIPAddrMap[ rudpCtx ] = peer; } else @@ -2311,7 +2311,7 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerFromRudpCtx(int rudpCtx { return it->second; } - return NULL; + return nullptr; } @@ -2322,7 +2322,7 @@ SceNetInAddr* SQRNetworkManager_AdHoc_Vita::GetIPAddrFromRudpCtx(int rudpCtx) { return &it->second; } - return NULL; + return nullptr; } @@ -2336,7 +2336,7 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerFromRoomMemberAndLocalI return it->second; } } - return NULL; + return nullptr; } @@ -2406,7 +2406,7 @@ void SQRNetworkManager_AdHoc_Vita::HandleMatchingContextStart() if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { SetState( SNM_INT_STATE_IDLE ); - GetExtDataForRoom(0, NULL, NULL, NULL); + GetExtDataForRoom(0, nullptr, nullptr, nullptr); } else if( m_state == SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT ) { @@ -2431,7 +2431,7 @@ void SQRNetworkManager_AdHoc_Vita::HandleMatchingContextStart() if(s_SignInCompleteCallbackFn) { s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } @@ -2446,7 +2446,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventCallback(int event, int retCode, uin PSVITA_STUBBED; // SQRNetworkManager_AdHoc_Vita *manager = (SQRNetworkManager_AdHoc_Vita *)arg; // // We aren't allowed to actually get the event directly from this callback, so send our own internal event to a thread dedicated to doing this - // sceKernelTriggerUserEvent(m_basicEventQueue, sc_UserEventHandle, NULL); + // sceKernelTriggerUserEvent(m_basicEventQueue, sc_UserEventHandle, nullptr); return 0; } @@ -2490,7 +2490,7 @@ void SQRNetworkManager_AdHoc_Vita::SysUtilCallback(uint64_t status, uint64_t par // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); // } - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } // return; // } @@ -2505,7 +2505,7 @@ void SQRNetworkManager_AdHoc_Vita::SysUtilCallback(uint64_t status, uint64_t par // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); // } - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } // } // @@ -2542,7 +2542,7 @@ void SQRNetworkManager_AdHoc_Vita::updateNetCheckDialog() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } else @@ -2561,7 +2561,7 @@ void SQRNetworkManager_AdHoc_Vita::updateNetCheckDialog() { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } @@ -2577,7 +2577,7 @@ void SQRNetworkManager_AdHoc_Vita::RudpContextCallback(int ctx_id, int event_id, { case SCE_RUDP_CONTEXT_EVENT_CLOSED: { - SQRVoiceConnection* pVoice = NULL; + SQRVoiceConnection* pVoice = nullptr; if(sc_voiceChatEnabled) SonyVoiceChat_Vita::GetVoiceConnectionFromRudpCtx(ctx_id); @@ -2638,7 +2638,7 @@ void SQRNetworkManager_AdHoc_Vita::RudpContextCallback(int ctx_id, int event_id, case SCE_RUDP_CONTEXT_EVENT_READABLE: if( manager->m_listener ) { - SQRVoiceConnection* pVoice = NULL; + SQRVoiceConnection* pVoice = nullptr; if(sc_voiceChatEnabled) { SonyVoiceChat_Vita::GetVoiceConnectionFromRudpCtx(ctx_id); @@ -2698,7 +2698,7 @@ void SQRNetworkManager_AdHoc_Vita::RudpContextCallback(int ctx_id, int event_id, playerFrom = manager->m_aRoomSlotPlayers[0]; playerTo = manager->GetPlayerFromRudpCtx( ctx_id ); } - if( ( playerFrom != NULL ) && ( playerTo != NULL ) ) + if( ( playerFrom != nullptr ) && ( playerTo != nullptr ) ) { manager->m_listener->HandleDataReceived( playerFrom, playerTo, data, bytesRead ); } @@ -2761,7 +2761,7 @@ void SQRNetworkManager_AdHoc_Vita::ServerContextValid_CreateRoom() int ret = -1; if( !ForceErrorPoint(SNM_FORCE_ERROR_GET_WORLD_INFO_LIST) ) { - ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, NULL, &m_getWorldRequestId); + ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, nullptr, &m_getWorldRequestId); } if (ret < 0) { @@ -2790,7 +2790,7 @@ void SQRNetworkManager_AdHoc_Vita::ServerContextValid_JoinRoom() reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, NULL, &m_joinRoomRequestId ); + int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, nullptr, &m_joinRoomRequestId ); if ( (ret < 0) || ForceErrorPoint(SNM_FORCE_ERROR_JOIN_ROOM) ) { if( ret == SCE_NP_MATCHING2_SERVER_ERROR_NAT_TYPE_MISMATCH) @@ -2814,14 +2814,14 @@ const SceNpCommunicationSignature* SQRNetworkManager_AdHoc_Vita::GetSceNpCommsSi const SceNpTitleId* SQRNetworkManager_AdHoc_Vita::GetSceNpTitleId() { PSVITA_STUBBED; - return NULL; + return nullptr; // return &s_npTitleId; } const SceNpTitleSecret* SQRNetworkManager_AdHoc_Vita::GetSceNpTitleSecret() { PSVITA_STUBBED; - return NULL; + return nullptr; // return &s_npTitleSecret; } @@ -2852,7 +2852,7 @@ int SQRNetworkManager_AdHoc_Vita::GetRemovedMask(int newMask, int oldMask) void SQRNetworkManager_AdHoc_Vita::GetExtDataForRoom( SceNpMatching2RoomId roomId, void *extData, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) { - for(int i=0;i= 0); // libCtxId = ret; @@ -162,7 +162,7 @@ void SQRNetworkManager_Vita::Initialise() } SetState(SNM_INT_STATE_SIGNING_IN); - // AttemptPSNSignIn(NULL, NULL); + // AttemptPSNSignIn(nullptr, nullptr); // SonyHttp::init(); @@ -170,7 +170,7 @@ void SQRNetworkManager_Vita::Initialise() // npConf.commId = &s_npCommunicationId; // npConf.commPassphrase = &s_npCommunicationPassphrase; // npConf.commSignature = &s_npCommunicationSignature; - // ret = sceNpInit(&npConf, NULL); + // ret = sceNpInit(&npConf, nullptr); // if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) // { // app.DebugPrintf("sceNpInit failed, ret=%x\n", ret); @@ -295,7 +295,7 @@ void SQRNetworkManager_Vita::InitialiseAfterOnline() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } return; } @@ -329,7 +329,7 @@ void SQRNetworkManager_Vita::InitialiseAfterOnline() app.DebugPrintf("sceNpMatching2CreateContext\n"); ret = sceNpMatching2CreateContext(&npID, GetSceNpCommsId(), &s_npCommunicationPassphrase, &m_matchingContext); - //ret = sceNpMatching2CreateContext(&npID, NULL, NULL, &m_matchingContext); + //ret = sceNpMatching2CreateContext(&npID, nullptr, nullptr, &m_matchingContext); if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_CREATE_MATCHING_CONTEXT ) ) { @@ -377,7 +377,7 @@ void SQRNetworkManager_Vita::Tick() if( ( m_gameBootInvite ) && ( s_safeToRespondToGameBootInvite ) ) { m_listener->HandleInviteReceived( ProfileManager.GetPrimaryPad(), m_gameBootInvite ); - m_gameBootInvite = NULL; + m_gameBootInvite = nullptr; } ErrorHandlingTick(); @@ -444,12 +444,12 @@ void SQRNetworkManager_Vita::Tick() if( s_signInCompleteCallbackIfFailed ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } else if(s_SignInCompleteCallbackFn) { s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } @@ -467,7 +467,7 @@ void SQRNetworkManager_Vita::ErrorHandlingTick() { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } app.DebugPrintf("Network error: SNM_INT_STATE_INITIALISE_FAILED\n"); if( m_isInSession && m_offlineGame) // m_offlineSQR ) // MGH - changed this to m_offlineGame, as m_offlineSQR can be true when running an online game but the init has failed because the servers are down @@ -578,7 +578,7 @@ void SQRNetworkManager_Vita::UpdateExternalRoomData() reqParam.roomBinAttrExternal = &roomBinAttr; app.DebugPrintf("sceNpMatching2SetRoomDataExternal\n"); - int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + int ret = sceNpMatching2SetRoomDataExternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SetRoomDataExternal returns 0x%x, number of players %d\n",ret,((char *)m_joinExtData)[174]); if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA ) ) { @@ -608,11 +608,11 @@ bool SQRNetworkManager_Vita::FriendRoomManagerSearch() } // Free up any external data that we received from the previous search - for( int i = 0; i < m_aFriendSearchResults.size(); i++ ) + for( size_t i = 0; i < m_aFriendSearchResults.size(); i++ ) { if(m_aFriendSearchResults[i].m_RoomExtDataReceived) free(m_aFriendSearchResults[i].m_RoomExtDataReceived); - m_aFriendSearchResults[i].m_RoomExtDataReceived = NULL; + m_aFriendSearchResults[i].m_RoomExtDataReceived = nullptr; } m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT; @@ -675,7 +675,7 @@ void SQRNetworkManager_Vita::FriendSearchTick() { m_friendSearchState = SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO; delete m_getFriendCountThread; - m_getFriendCountThread = NULL; + m_getFriendCountThread = nullptr; FriendRoomManagerSearch2(); } } @@ -695,7 +695,7 @@ int SQRNetworkManager_Vita::BasicEventThreadProc( void *lpParameter ) // // do // { - // ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); + // ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, nullptr); // // // 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 ) @@ -753,7 +753,7 @@ int SQRNetworkManager_Vita::GetFriendsThreadProc( void* lpParameter ) // 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; + SceNpId* friendIDs = nullptr; if(manager->m_friendCount > 0) { // grab all the friend IDs first @@ -890,7 +890,7 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerByIndex(int idx) } else { - return NULL; + return nullptr; } } @@ -907,7 +907,7 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerBySmallId(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_Vita::GetLocalPlayerByUserIndex(int idx) @@ -923,7 +923,7 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetLocalPlayerByUserIndex(int idx) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } SQRNetworkPlayer *SQRNetworkManager_Vita::GetHostPlayer() @@ -936,11 +936,11 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetHostPlayer() SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerIfReady(SQRNetworkPlayer *player) { - if( player == NULL ) return NULL; + if( player == nullptr ) return nullptr; if( player->IsReady() ) return player; - return NULL; + return nullptr; } // Update state internally @@ -1039,7 +1039,7 @@ bool SQRNetworkManager_Vita::JoinRoom(SQRNetworkManager_Vita::SessionSearchResul { // Set up the presence info we would like to synchronise out when we have fully joined the game CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData(&s_lastPresenceSyncInfo, searchResult->m_extData, searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId); - return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, NULL); + return JoinRoom(searchResult->m_sessionId.m_RoomId, searchResult->m_sessionId.m_ServerId, localPlayerMask, nullptr); } // Join room with a specified roomId. This is used when joining from an invite, as well as by the previous method @@ -1106,7 +1106,7 @@ void SQRNetworkManager_Vita::LeaveRoom(bool bActuallyLeaveRoom) SetState(SNM_INT_STATE_LEAVING); app.DebugPrintf("sceNpMatching2LeaveRoom\n"); - int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, NULL, &m_leaveRoomRequestId ); + int ret = sceNpMatching2LeaveRoom( m_matchingContext, &reqParam, nullptr, &m_leaveRoomRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_LEAVE_ROOM) ) { SetState(SNM_INT_STATE_LEAVING_FAILED); @@ -1214,7 +1214,7 @@ bool SQRNetworkManager_Vita::AddLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternal = &binAttr; app.DebugPrintf("sceNpMatching2SetRoomMemberDataInternal\n"); - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL) ) { @@ -1264,7 +1264,7 @@ bool SQRNetworkManager_Vita::RemoveLocalPlayerByUserIndex(int idx) // And do any adjusting necessary to the mappings from this room data, to the SQRNetworkPlayers. // This will also delete the SQRNetworkPlayer and do all the callbacks that requires etc. MapRoomSlotPlayers(roomSlotPlayerCount); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; // Sync this back out to our networked clients... SyncRoomData(); @@ -1302,7 +1302,7 @@ bool SQRNetworkManager_Vita::RemoveLocalPlayerByUserIndex(int idx) reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, NULL, &m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( m_matchingContext, &reqParam, nullptr, &m_setRoomMemberInternalDataRequestId ); if( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2) ) { @@ -1526,14 +1526,14 @@ void SQRNetworkManager_Vita::TickJoinablePresenceData() // // Signed in to PSN but not connected (no internet access) // UINT uiIDA[1]; // uiIDA[0] = IDS_OK; - // ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL, app.GetStringTable()); + // ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), nullptr, nullptr, app.GetStringTable()); // } // else { // Not signed in to PSN UINT uiIDA[1]; uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; - ui.RequestAlertMessage( IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, ProfileManager.GetPrimaryPad(), &MustSignInReturnedPresenceInvite, NULL); + ui.RequestAlertMessage( IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, ProfileManager.GetPrimaryPad(), &MustSignInReturnedPresenceInvite, nullptr); } } @@ -1573,7 +1573,7 @@ void SQRNetworkManager_Vita::FindOrCreateNonNetworkPlayer(int slot, int playerTy } } // Create the player - non-network players can be considered complete as soon as we create them as we aren't waiting on their network connections becoming complete, so can flag them as such and notify via callback - PlayerUID *pUID = NULL; + PlayerUID *pUID = nullptr; PlayerUID localUID; if( ( playerType == SQRNetworkPlayer::SNP_TYPE_LOCAL ) || m_isHosting && ( playerType == SQRNetworkPlayer::SNP_TYPE_HOST ) ) @@ -1640,7 +1640,7 @@ void SQRNetworkManager_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_REMOTE ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1696,7 +1696,7 @@ void SQRNetworkManager_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) if( m_aRoomSlotPlayers[i]->m_type != SQRNetworkPlayer::SNP_TYPE_LOCAL ) { m_vecTempPlayers.push_back(m_aRoomSlotPlayers[i]); - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } } @@ -1788,7 +1788,7 @@ void SQRNetworkManager_Vita::UpdatePlayersFromRoomSyncUIDs() } // Host only - add remote players to our internal storage of player slots, and synchronise this with other room members. -bool SQRNetworkManager_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==NULL*/ ) +bool SQRNetworkManager_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull/*==nullptr*/ ) { assert( m_isHosting ); @@ -1908,7 +1908,7 @@ void SQRNetworkManager_Vita::RemoveRemotePlayersAndSync( SceNpMatching2RoomMembe } // Zero last element, that isn't part of the currently sized array anymore memset(&m_roomSyncData.players[m_roomSyncData.getPlayerCount()],0,sizeof(PlayerSyncData)); - m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = NULL; + m_aRoomSlotPlayers[m_roomSyncData.getPlayerCount()] = nullptr; } else { @@ -1951,7 +1951,7 @@ void SQRNetworkManager_Vita::RemoveNetworkPlayers( int mask ) { if( m_aRoomSlotPlayers[i] == player ) { - m_aRoomSlotPlayers[i] = NULL; + m_aRoomSlotPlayers[i] = nullptr; } } // And delete the reference from the ctx->player map @@ -2004,7 +2004,7 @@ void SQRNetworkManager_Vita::SyncRoomData() roomBinAttr.size = sizeof( m_roomSyncData ); reqParam.roomBinAttrInternalNum = 1; reqParam.roomBinAttrInternal = &roomBinAttr; - sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, NULL, &m_setRoomDataRequestId ); + sceNpMatching2SetRoomDataInternal ( m_matchingContext, &reqParam, nullptr, &m_setRoomDataRequestId ); } // Check if the matching context is valid, and if not attempt to create one. If to do this requires starting an asynchronous process, then sets the internal state to the state passed in @@ -2037,7 +2037,7 @@ bool SQRNetworkManager_Vita::GetMatchingContext(eSQRNetworkManagerInternalState // Create context app.DebugPrintf("sceNpMatching2CreateContext\n"); ret = sceNpMatching2CreateContext(&npId, &s_npCommunicationId, &s_npCommunicationPassphrase, &m_matchingContext/*, option*/); - //ret = sceNpMatching2CreateContext(&npId, NULL,NULL, &m_matchingContext/*, option*/); + //ret = sceNpMatching2CreateContext(&npId, nullptr,nullptr, &m_matchingContext/*, option*/); if( ret < 0 ) { app.DebugPrintf("SQRNetworkManager::GetMatchingContext - sceNpMatching2CreateContext failed with code 0x%08x\n", ret); @@ -2137,7 +2137,7 @@ bool SQRNetworkManager_Vita::GetServerContext(SceNpMatching2ServerId serverId) // { // // Get list of server IDs of servers allocated to the application. We don't actually need to do this, but it is as good a way as any to try a matching2 service and check that // // the context *really* is valid. - // int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, NULL, 0 ); + // int serverCount = sceNpMatching2GetServerIdListLocal( m_matchingContext, nullptr, 0 ); // // If an error is returned here, we need to destroy and recerate our server - if this goes ok we should come back through this path again // if( ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_UNAVAILABLE ) || // This error has been seen (occasionally) in a normal working environment // ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error @@ -2233,7 +2233,7 @@ void SQRNetworkManager_Vita::RoomCreateTick() app.DebugPrintf(CMinecraftApp::USER_RR,">> Creating room start\n"); s_roomStartTime = System::currentTimeMillis(); app.DebugPrintf("sceNpMatching2CreateJoinRoom\n"); - int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, NULL, &m_createRoomRequestId ); + int ret = sceNpMatching2CreateJoinRoom( m_matchingContext, &reqParam, nullptr, &m_createRoomRequestId ); if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_JOIN_ROOM) ) { SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED); @@ -2468,7 +2468,7 @@ bool SQRNetworkManager_Vita::CreateVoiceRudpConnections(SceNpMatching2RoomId roo // create this connection if we don't have it already SQRVoiceConnection* pConnection = SonyVoiceChat_Vita::getVoiceConnectionFromRoomMemberID(peerMemberId); - if(pConnection == NULL) + if(pConnection == nullptr) { // Create an Rudp context for the voice connection, this will happen regardless of whether the peer is client or host @@ -2542,7 +2542,7 @@ bool SQRNetworkManager_Vita::CreateRudpConnections(SceNpMatching2RoomId roomId, if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT) ) return false; if( m_isHosting ) { - m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, NULL ); + m_RudpCtxToPlayerMap[ rudpCtx ] = new SQRNetworkPlayer( this, SQRNetworkPlayer::SNP_TYPE_REMOTE, true, playersMemberId, i, rudpCtx, nullptr ); } else { @@ -2576,7 +2576,7 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerFromRudpCtx(int rudpCtx) { return it->second; } - return NULL; + return nullptr; } @@ -2590,7 +2590,7 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerFromRoomMemberAndLocalIdx(int return it->second; } } - return NULL; + return nullptr; } @@ -2693,7 +2693,7 @@ void SQRNetworkManager_Vita::ContextCallback(SceNpMatching2ContextId id, SceNpM if( manager->m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { manager->SetState( SNM_INT_STATE_IDLE ); - manager->GetExtDataForRoom(0, NULL, NULL, NULL); + manager->GetExtDataForRoom(0, nullptr, nullptr, nullptr); break; } @@ -2729,7 +2729,7 @@ void SQRNetworkManager_Vita::ContextCallback(SceNpMatching2ContextId id, SceNpM // if(s_SignInCompleteCallbackFn) // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam, true, 0); - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } @@ -2966,12 +2966,12 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, // Set flag to indicate whether we were kicked for being out of room or not reqParam.optData.data[0] = isFull ? 1 : 0; reqParam.optData.len = 1; - int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, NULL, &manager->m_kickRequestId); + int ret = sceNpMatching2KickoutRoomMember(manager->m_matchingContext, &reqParam, nullptr, &manager->m_kickRequestId); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2KickoutRoomMember returns error 0x%x\n",ret); } else { - if(pRoomMemberData->roomMemberDataInternal->roomMemberBinAttrInternal->data.ptr == NULL) + if(pRoomMemberData->roomMemberDataInternal->roomMemberBinAttrInternal->data.ptr == nullptr) { // the host doesn't send out data, so this must be the host we're connecting to @@ -3220,7 +3220,7 @@ void SQRNetworkManager_Vita::RoomEventCallback(SceNpMatching2ContextId id, SceNp reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, NULL, &manager->m_setRoomMemberInternalDataRequestId ); + int ret = sceNpMatching2SetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, nullptr, &manager->m_setRoomMemberInternalDataRequestId ); } else { @@ -3309,7 +3309,7 @@ void SQRNetworkManager_Vita::SignallingCallback(SceNpMatching2ContextId ctxId, S { 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 == nullptr) // 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 @@ -3336,7 +3336,7 @@ void SQRNetworkManager_Vita::SignallingCallback(SceNpMatching2ContextId ctxId, S reqParam.attrId = attrs; reqParam.attrIdNum = 1; - sceNpMatching2GetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, NULL, &manager->m_roomMemberDataRequestId); + sceNpMatching2GetRoomMemberDataInternal( manager->m_matchingContext, &reqParam, nullptr, &manager->m_roomMemberDataRequestId); } break; } @@ -3349,7 +3349,7 @@ int SQRNetworkManager_Vita::BasicEventCallback(int event, int retCode, uint32_t PSVITA_STUBBED; // SQRNetworkManager_Vita *manager = (SQRNetworkManager_Vita *)arg; // // We aren't allowed to actually get the event directly from this callback, so send our own internal event to a thread dedicated to doing this - // sceKernelTriggerUserEvent(m_basicEventQueue, sc_UserEventHandle, NULL); + // sceKernelTriggerUserEvent(m_basicEventQueue, sc_UserEventHandle, nullptr); return 0; } @@ -3408,7 +3408,7 @@ void SQRNetworkManager_Vita::SysUtilCallback(uint64_t status, uint64_t param, vo // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); // } - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } // return; // } @@ -3423,7 +3423,7 @@ void SQRNetworkManager_Vita::SysUtilCallback(uint64_t status, uint64_t param, vo // { // s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); // } - // s_SignInCompleteCallbackFn = NULL; + // s_SignInCompleteCallbackFn = nullptr; // } // } // @@ -3472,7 +3472,7 @@ void SQRNetworkManager_Vita::updateNetCheckDialog() if( s_SignInCompleteCallbackFn ) { s_SignInCompleteCallbackFn(s_SignInCompleteParam,true,0); - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } else @@ -3488,7 +3488,7 @@ void SQRNetworkManager_Vita::updateNetCheckDialog() { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } @@ -3611,7 +3611,7 @@ void SQRNetworkManager_Vita::RudpContextCallback(int ctx_id, int event_id, int e playerFrom = manager->m_aRoomSlotPlayers[0]; playerTo = manager->GetPlayerFromRudpCtx( ctx_id ); } - if( ( playerFrom != NULL ) && ( playerTo != NULL ) ) + if( ( playerFrom != nullptr ) && ( playerTo != nullptr ) ) { manager->m_listener->HandleDataReceived( playerFrom, playerTo, data, bytesRead ); } @@ -3677,7 +3677,7 @@ void SQRNetworkManager_Vita::ServerContextValid_CreateRoom() { app.DebugPrintf("sceNpMatching2GetWorldInfoList\n"); m_getWorldRequestId=0; - ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, NULL, &m_getWorldRequestId); + ret = sceNpMatching2GetWorldInfoList( m_matchingContext, &reqParam, nullptr, &m_getWorldRequestId); } if (ret < 0) { @@ -3706,7 +3706,7 @@ void SQRNetworkManager_Vita::ServerContextValid_JoinRoom() reqParam.roomMemberBinAttrInternalNum = 1; reqParam.roomMemberBinAttrInternal = &binAttr; - int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, NULL, &m_joinRoomRequestId ); + int ret = sceNpMatching2JoinRoom( m_matchingContext, &reqParam, nullptr, &m_joinRoomRequestId ); if ( (ret < 0) || ForceErrorPoint(SNM_FORCE_ERROR_JOIN_ROOM) ) { if( ret == SCE_NP_MATCHING2_SERVER_ERROR_NAT_TYPE_MISMATCH) @@ -3730,14 +3730,14 @@ const SceNpCommunicationSignature* SQRNetworkManager_Vita::GetSceNpCommsSig() const SceNpTitleId* SQRNetworkManager_Vita::GetSceNpTitleId() { PSVITA_STUBBED; - return NULL; + return nullptr; // return &s_npTitleId; } const SceNpTitleSecret* SQRNetworkManager_Vita::GetSceNpTitleSecret() { PSVITA_STUBBED; - return NULL; + return nullptr; // return &s_npTitleSecret; } @@ -3771,9 +3771,9 @@ void SQRNetworkManager_Vita::GetExtDataForRoom( SceNpMatching2RoomId roomId, voi static SceNpMatching2RoomId aRoomId[1]; static SceNpMatching2AttributeId attr[1]; - // All parameters will be NULL if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). - // NULL parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList - if( extData != NULL ) + // All parameters will be nullptr if this is being called a second time, after creating a new matching context via one of the paths below (using GetMatchingContext). + // nullptr parameters therefore basically represents an attempt to retry the last sceNpMatching2GetRoomDataExternalList + if( extData != nullptr ) { aRoomId[0] = roomId; attr[0] = SCE_NP_MATCHING2_ROOM_BIN_ATTR_EXTERNAL_1_ID; @@ -3797,14 +3797,14 @@ void SQRNetworkManager_Vita::GetExtDataForRoom( SceNpMatching2RoomId roomId, voi return; } - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { app.DebugPrintf("Having to recreate matching context, setting state to SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT\n"); return; } - int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, NULL, &m_roomDataExternalListRequestId ); + int ret = sceNpMatching2GetRoomDataExternalList( m_matchingContext, &reqParam, nullptr, &m_roomDataExternalListRequestId ); // If we hadn't properly detected that a matching context was unvailable, we might still get an error indicating that it is from the previous call. Handle similarly, but we need // to destroy the context first. @@ -3818,7 +3818,7 @@ void SQRNetworkManager_Vita::GetExtDataForRoom( SceNpMatching2RoomId roomId, voi m_FriendSessionUpdatedFn(false, m_pParamFriendSessionUpdated); return; }; - // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with NULL params) once done, so we can reattempt. Don't do anything more now. + // Kicked off an asynchronous thing that will create a matching context, and then call this method back again (with nullptr params) once done, so we can reattempt. Don't do anything more now. if( m_state == SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT ) { return; @@ -3957,7 +3957,7 @@ void SQRNetworkManager_Vita::AttemptPSNSignIn(int (*SignInCompleteCallbackFn)(vo { s_SignInCompleteCallbackFn(s_SignInCompleteParam,false,0); } - s_SignInCompleteCallbackFn = NULL; + s_SignInCompleteCallbackFn = nullptr; } } } @@ -4127,6 +4127,6 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerByXuid(PlayerUID xuid) } } LeaveCriticalSection(&m_csRoomSyncData); - return NULL; + return nullptr; } diff --git a/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.h b/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.h index 0fd0b4149..79befe039 100644 --- a/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.h +++ b/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.h @@ -149,7 +149,7 @@ private: void LocalDataSend(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, const void *data, unsigned int dataSize); int GetSessionIndex(SQRNetworkPlayer *player); - bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = NULL ); + bool AddRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int playerMask, bool *isFull = nullptr ); void RemoveRemotePlayersAndSync( SceNpMatching2RoomMemberId memberId, int mask ); void RemoveNetworkPlayers( int mask ); void SetLocalPlayersAndSync(); diff --git a/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.cpp b/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.cpp index 09852ccbe..88e661c6c 100644 --- a/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.cpp @@ -10,22 +10,22 @@ bool SonyCommerce_Vita::m_bCommerceInitialised = false; // SceNpCommerce2SessionInfo SonyCommerce_Vita::m_sessionInfo; SonyCommerce_Vita::State SonyCommerce_Vita::m_state = e_state_noSession; int SonyCommerce_Vita::m_errorCode = 0; -LPVOID SonyCommerce_Vita::m_callbackParam = NULL; +LPVOID SonyCommerce_Vita::m_callbackParam = nullptr; -void* SonyCommerce_Vita::m_receiveBuffer = NULL; +void* SonyCommerce_Vita::m_receiveBuffer = nullptr; SonyCommerce_Vita::Event SonyCommerce_Vita::m_event; std::queue SonyCommerce_Vita::m_messageQueue; -std::vector* SonyCommerce_Vita::m_pProductInfoList = NULL; -SonyCommerce_Vita::ProductInfoDetailed* SonyCommerce_Vita::m_pProductInfoDetailed = NULL; -SonyCommerce_Vita::ProductInfo* SonyCommerce_Vita::m_pProductInfo = NULL; +std::vector* SonyCommerce_Vita::m_pProductInfoList = nullptr; +SonyCommerce_Vita::ProductInfoDetailed* SonyCommerce_Vita::m_pProductInfoDetailed = nullptr; +SonyCommerce_Vita::ProductInfo* SonyCommerce_Vita::m_pProductInfo = nullptr; -SonyCommerce_Vita::CategoryInfo* SonyCommerce_Vita::m_pCategoryInfo = NULL; -const char* SonyCommerce_Vita::m_pProductID = NULL; -char* SonyCommerce_Vita::m_pCategoryID = NULL; +SonyCommerce_Vita::CategoryInfo* SonyCommerce_Vita::m_pCategoryInfo = nullptr; +const char* SonyCommerce_Vita::m_pProductID = nullptr; +char* SonyCommerce_Vita::m_pCategoryID = nullptr; SonyCommerce_Vita::CheckoutInputParams SonyCommerce_Vita::m_checkoutInputParams; SonyCommerce_Vita::DownloadListInputParams SonyCommerce_Vita::m_downloadInputParams; -SonyCommerce_Vita::CallbackFunc SonyCommerce_Vita::m_callbackFunc = NULL; +SonyCommerce_Vita::CallbackFunc SonyCommerce_Vita::m_callbackFunc = nullptr; // sys_memory_container_t SonyCommerce_Vita::m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; bool SonyCommerce_Vita::m_bUpgradingTrial = false; @@ -39,7 +39,7 @@ bool SonyCommerce_Vita::m_contextCreated=false; ///< npcommerce2 conte SonyCommerce_Vita::Phase SonyCommerce_Vita::m_currentPhase = e_phase_stopped; ///< Current commerce2 util // char SonyCommerce_Vita::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; -C4JThread* SonyCommerce_Vita::m_tickThread = NULL; +C4JThread* SonyCommerce_Vita::m_tickThread = nullptr; bool SonyCommerce_Vita::m_bLicenseChecked=false; // Check the trial/full license for the game bool SonyCommerce_Vita::m_bLicenseInstalled=false; // set to true when the licence has been downloaded and installed (but maybe not checked yet) bool SonyCommerce_Vita::m_bDownloadsPending=false; // set to true if there are any downloads happening in the background, so we check for them completing, and install when finished @@ -60,12 +60,12 @@ static bool s_showingPSStoreIcon = false; SonyCommerce_Vita::ProductInfoDetailed s_trialUpgradeProductInfoDetailed; void SonyCommerce_Vita::Delete() { - m_pProductInfoList=NULL; - m_pProductInfoDetailed=NULL; - m_pProductInfo=NULL; - m_pCategoryInfo = NULL; - m_pProductID = NULL; - m_pCategoryID = NULL; + m_pProductInfoList=nullptr; + m_pProductInfoDetailed=nullptr; + m_pProductInfo=nullptr; + m_pCategoryInfo = nullptr; + m_pProductID = nullptr; + m_pCategoryID = nullptr; } void SonyCommerce_Vita::Init() @@ -108,7 +108,7 @@ bool SonyCommerce_Vita::LicenseChecked() void SonyCommerce_Vita::CheckForTrialUpgradeKey() { - StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, NULL); + StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, nullptr); } int SonyCommerce_Vita::Shutdown() @@ -163,7 +163,7 @@ void SonyCommerce_Vita::checkBackgroundDownloadStatus() // install the content if(bInstallContent) { - InstallContent(InstallContentCallback, NULL); + InstallContent(InstallContentCallback, nullptr); } } } @@ -665,7 +665,7 @@ int SonyCommerce_Vita::createContext() // } // // // Create commerce2 context - // ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, NULL, &m_contextId); + // ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, nullptr, &m_contextId); // if (ret < 0) // { // app.DebugPrintf(4,"createContext sceNpCommerce2CreateCtx problem\n"); @@ -771,7 +771,7 @@ void SonyCommerce_Vita::commerce2Handler( const sce::Toolkit::NP::Event& event) // if(ret == SCE_OK) // { copyCategoryInfo(m_pCategoryInfo, g_categoryInfo.get()); - m_pCategoryInfo = NULL; + m_pCategoryInfo = nullptr; m_event = e_event_commerceGotCategoryInfo; // } @@ -781,7 +781,7 @@ void SonyCommerce_Vita::commerce2Handler( const sce::Toolkit::NP::Event& event) case sce::Toolkit::NP::Event::UserEvent::commerceGotProductList: { copyProductList(m_pProductInfoList, g_productList.get()); - m_pProductInfoDetailed = NULL; + m_pProductInfoDetailed = nullptr; m_event = e_event_commerceGotProductList; break; } @@ -791,12 +791,12 @@ void SonyCommerce_Vita::commerce2Handler( const sce::Toolkit::NP::Event& event) if(m_pProductInfoDetailed) { copyDetailedProductInfo(m_pProductInfoDetailed, g_detailedProductInfo.get()); - m_pProductInfoDetailed = NULL; + m_pProductInfoDetailed = nullptr; } else { copyAddDetailedProductInfo(m_pProductInfo, g_detailedProductInfo.get()); - m_pProductInfo = NULL; + m_pProductInfo = nullptr; } m_event = e_event_commerceGotDetailedProductInfo; break; @@ -1180,7 +1180,7 @@ void SonyCommerce_Vita::processEvent() break; case e_event_commerceProductBrowseFinished: app.DebugPrintf(4,"e_event_commerceProductBrowseFinished succeeded: 0x%x\n", m_errorCode); - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1232,7 +1232,7 @@ void SonyCommerce_Vita::processEvent() ProfileManager.SetSysUIShowing(false); // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { // get the detailed product info again, to see if the purchase has happened or not EnterCriticalSection(&m_queueLock); @@ -1260,7 +1260,7 @@ void SonyCommerce_Vita::processEvent() ProfileManager.SetSysUIShowing(false); // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) + if(m_callbackFunc!=nullptr) { runCallback(); } @@ -1328,10 +1328,10 @@ void SonyCommerce_Vita::CreateSession( CallbackFunc cb, LPVOID lpParam ) if(m_tickThread && (m_tickThread->isRunning() == false)) { delete m_tickThread; - m_tickThread = NULL; + m_tickThread = nullptr; } - if(m_tickThread == NULL) - m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce_Vita tick"); + if(m_tickThread == nullptr) + m_tickThread = new C4JThread(TickLoop, nullptr, "SonyCommerce_Vita tick"); if(m_tickThread->isRunning() == false) { m_currentPhase = e_phase_idle; @@ -1439,7 +1439,7 @@ void SonyCommerce_Vita::DownloadAlreadyPurchased_Game( CallbackFunc cb, LPVOID l void SonyCommerce_Vita::InstallContent( CallbackFunc cb, LPVOID lpParam ) { - if(m_callbackFunc == NULL && m_messageQueue.size() == 0) // wait till other processes have finished + if(m_callbackFunc == nullptr && m_messageQueue.size() == 0) // wait till other processes have finished { EnterCriticalSection(&m_queueLock); m_bInstallingContent = true; diff --git a/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.h b/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.h index 6285832cd..c8f76bf7d 100644 --- a/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.h +++ b/Minecraft.Client/PSVita/Network/SonyCommerce_Vita.h @@ -121,14 +121,14 @@ class SonyCommerce_Vita : public SonyCommerce { assert(m_callbackFunc); CallbackFunc func = m_callbackFunc; - m_callbackFunc = NULL; + m_callbackFunc = nullptr; if(func) func(m_callbackParam, m_errorCode); m_errorCode = SCE_OK; } static void setCallback(CallbackFunc cb,LPVOID lpParam) { - assert(m_callbackFunc == NULL); + assert(m_callbackFunc == nullptr); m_callbackFunc = cb; m_callbackParam = lpParam; } diff --git a/Minecraft.Client/PSVita/Network/SonyHttp_Vita.cpp b/Minecraft.Client/PSVita/Network/SonyHttp_Vita.cpp index 9110edf55..2015f9303 100644 --- a/Minecraft.Client/PSVita/Network/SonyHttp_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SonyHttp_Vita.cpp @@ -131,10 +131,10 @@ int SonyHttp_Vita::sslCallback(SceUInt32 verifyErr, SceSslCert * const sslCert[] (void)userArg; app.DebugPrintf("Ssl callback:\n"); - app.DebugPrintf("\tbase tmpl[%x]\n", (SceInt32)userArg); + app.DebugPrintf("\tbase tmpl[%x]\n", static_cast(userArg)); if (verifyErr != 0){ - printSslError((SceInt32)SCE_HTTPS_ERROR_CERT, verifyErr); + printSslError(static_cast(SCE_HTTPS_ERROR_CERT), verifyErr); } for (i = 0; i < certNum; i++){ printSslCertInfo(sslCert[i]); @@ -192,7 +192,7 @@ bool SonyHttp_Vita::http_get(const char *targetUrl, void** ppOutData, int* pData } /* Register SSL callback */ - ret = sceHttpsSetSslCallback(tmplId, sslCallback, (void*)&tmplId); + ret = sceHttpsSetSslCallback(tmplId, sslCallback, static_cast(&tmplId)); if (ret < 0) { app.DebugPrintf("sceHttpsSetSslCallback() error: 0x%08X\n", ret); @@ -215,7 +215,7 @@ bool SonyHttp_Vita::http_get(const char *targetUrl, void** ppOutData, int* pData } reqId = ret; - ret = sceHttpSendRequest(reqId, NULL, 0); + ret = sceHttpSendRequest(reqId, nullptr, 0); if (ret < 0) { app.DebugPrintf("sceHttpSendRequest() error: 0x%08X\n", ret); diff --git a/Minecraft.Client/PSVita/Network/SonyRemoteStorage_Vita.cpp b/Minecraft.Client/PSVita/Network/SonyRemoteStorage_Vita.cpp index c103b32fd..dd6c83727 100644 --- a/Minecraft.Client/PSVita/Network/SonyRemoteStorage_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SonyRemoteStorage_Vita.cpp @@ -26,7 +26,7 @@ static SceRemoteStorageData s_getDataOutput; void SonyRemoteStorage_Vita::staticInternalCallback(const SceRemoteStorageEvent event, int32_t retCode, void * userData) { - ((SonyRemoteStorage_Vita*)userData)->internalCallback(event, retCode); + static_cast(userData)->internalCallback(event, retCode); } void SonyRemoteStorage_Vita::internalCallback(const SceRemoteStorageEvent event, int32_t retCode) @@ -218,7 +218,7 @@ bool SonyRemoteStorage_Vita::init(CallbackFunc cb, LPVOID lpParam) params.timeout.receiveMs = 120 * 1000; //120 seconds is the default params.timeout.sendMs = 120 * 1000; //120 seconds is the default params.pool.memPoolSize = 7 * 1024 * 1024; - if(m_memPoolBuffer == NULL) + if(m_memPoolBuffer == nullptr) m_memPoolBuffer = malloc(params.pool.memPoolSize); params.pool.memPoolBuffer = m_memPoolBuffer; @@ -298,8 +298,8 @@ bool SonyRemoteStorage_Vita::setDataInternal() snprintf(m_saveFilename, sizeof(m_saveFilename), "%s:%s/GAMEDATA.bin", "savedata0", m_setDataSaveInfo->UTF8SaveFilename); - SceFiosSize outSize = sceFiosFileGetSizeSync(NULL, m_saveFilename); - m_uploadSaveSize = (int)outSize; + SceFiosSize outSize = sceFiosFileGetSizeSync(nullptr, m_saveFilename); + m_uploadSaveSize = static_cast(outSize); strcpy(m_saveFileDesc, m_setDataSaveInfo->UTF8SaveTitle); m_status = e_setDataInProgress; diff --git a/Minecraft.Client/PSVita/Network/SonyVoiceChat_Vita.cpp b/Minecraft.Client/PSVita/Network/SonyVoiceChat_Vita.cpp index 842e6b8de..37fea8282 100644 --- a/Minecraft.Client/PSVita/Network/SonyVoiceChat_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SonyVoiceChat_Vita.cpp @@ -67,7 +67,7 @@ void LoadPCMVoiceData() { char filename[64]; sprintf(filename, "voice%d.pcm", i+1); - HANDLE file = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(filename, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); DWORD dwHigh=0; g_loadedPCMVoiceDataSizes[i] = GetFileSize(file,&dwHigh); @@ -75,7 +75,7 @@ void LoadPCMVoiceData() { g_loadedPCMVoiceData[i] = new char[g_loadedPCMVoiceDataSizes[i]]; DWORD bytesRead; - BOOL bSuccess = ReadFile(file, g_loadedPCMVoiceData[i], g_loadedPCMVoiceDataSizes[i], &bytesRead, NULL); + BOOL bSuccess = ReadFile(file, g_loadedPCMVoiceData[i], g_loadedPCMVoiceDataSizes[i], &bytesRead, nullptr); assert(bSuccess); } g_loadedPCMVoiceDataPos[i] = 0; @@ -285,7 +285,7 @@ void SQRVoiceConnection::readRemoteData() if( dataSize > 0 ) { VoicePacket packet; - unsigned int bytesRead = sceRudpRead( m_rudpCtx, &packet, dataSize, 0, NULL ); + unsigned int bytesRead = sceRudpRead( m_rudpCtx, &packet, dataSize, 0, nullptr ); unsigned int writeSize; if( bytesRead > 0 ) { @@ -378,7 +378,7 @@ uint32_t lastReadFrameCnt = 0; void PrintAllOutputVoiceStates( std::vector& connections) { - for(int rIdx=0;rIdxm_bConnected) @@ -668,7 +668,7 @@ void SonyVoiceChat_Vita::tick() EnterCriticalSection(&m_csRemoteConnections); - for(int i=m_remoteConnections.size()-1;i>=0;i--) + for(int i = (int)m_remoteConnections.size() - 1; i >= 0; i--) { if(m_remoteConnections[i]->m_bFlaggedForShutdown) { @@ -911,7 +911,7 @@ void SonyVoiceChat_Vita::initLocalPlayer(int playerIndex) if(m_localVoiceDevices[playerIndex].isValid() == false) { bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,nullptr,nullptr); // create all device ports required m_localVoiceDevices[playerIndex].init(chatRestricted); @@ -948,7 +948,7 @@ SQRVoiceConnection* SonyVoiceChat_Vita::GetVoiceConnectionFromRudpCtx( int RudpC if(m_remoteConnections[i]->m_rudpCtx == RudpCtx) return m_remoteConnections[i]; } - return NULL; + return nullptr; } void SonyVoiceChat_Vita::connectPlayerToAll( int playerIndex ) @@ -973,7 +973,7 @@ SQRVoiceConnection* SonyVoiceChat_Vita::getVoiceConnectionFromRoomMemberID( SceN } } - return NULL; + return nullptr; } void SonyVoiceChat_Vita::disconnectLocalPlayer( int localIdx ) @@ -998,7 +998,7 @@ void SonyVoiceChat_Vita::disconnectLocalPlayer( int localIdx ) if(m_numLocalDevicesConnected == 0) // no more local players, kill all the remote connections { - for(int i=0;i(malloc(m_HashSize * sizeof(SCustomMapNode))); clear(); } @@ -87,7 +87,7 @@ void CustomMap::insert(const ChunkPos &Key, bool Value) Node->Hash = Hash; Node->first = Key; Node->second = Value; - Node->Next = NULL; + Node->Next = nullptr; // are any nodes in this hash index if( !m_HashTable[Index] ) @@ -115,16 +115,16 @@ void CustomMap::resize() SCustomMapNode **NodePool; if( m_NodePool ) { - NodePool = (SCustomMapNode**) realloc(m_NodePool, m_NodePoolSize * sizeof(SCustomMapNode)); + NodePool = static_cast(realloc(m_NodePool, m_NodePoolSize * sizeof(SCustomMapNode))); } else { - NodePool = (SCustomMapNode**) malloc(m_NodePoolSize * sizeof(SCustomMapNode)); + NodePool = static_cast(malloc(m_NodePoolSize * sizeof(SCustomMapNode))); } for( int i = 0;i < m_NodePoolSize - OldPoolSize;i += 1 ) { - NodePool[i + OldPoolSize] = (SCustomMapNode*) malloc(sizeof(SCustomMapNode)); + NodePool[i + OldPoolSize] = static_cast(malloc(sizeof(SCustomMapNode))); } m_NodePool = NodePool; diff --git a/Minecraft.Client/PSVita/PSVitaExtras/CustomSet.cpp b/Minecraft.Client/PSVita/PSVitaExtras/CustomSet.cpp index 6538a2360..4b96f1aa7 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/CustomSet.cpp +++ b/Minecraft.Client/PSVita/PSVitaExtras/CustomSet.cpp @@ -4,12 +4,12 @@ CustomSet::CustomSet() { - m_NodePool = NULL; + m_NodePool = nullptr; m_NodePoolSize = 0; m_NodePoolIndex = 0; m_HashSize = 1024; - m_HashTable = (SCustomSetNode**) malloc(m_HashSize * sizeof(SCustomSetNode)); + m_HashTable = static_cast(malloc(m_HashSize * sizeof(SCustomSetNode))); clear(); } @@ -85,7 +85,7 @@ void CustomSet::insert(const ChunkPos &Key) unsigned int Index = Hash & (m_HashSize-1); Node->Hash = Hash; Node->key = Key; - Node->Next = NULL; + Node->Next = nullptr; // are any nodes in this hash index if( !m_HashTable[Index] ) @@ -113,16 +113,16 @@ void CustomSet::resize() SCustomSetNode **NodePool; if( m_NodePool ) { - NodePool = (SCustomSetNode**) realloc(m_NodePool, m_NodePoolSize * sizeof(SCustomSetNode)); + NodePool = static_cast(realloc(m_NodePool, m_NodePoolSize * sizeof(SCustomSetNode))); } else { - NodePool = (SCustomSetNode**) malloc(m_NodePoolSize * sizeof(SCustomSetNode)); + NodePool = static_cast(malloc(m_NodePoolSize * sizeof(SCustomSetNode))); } for( int i = 0;i < m_NodePoolSize - OldPoolSize;i += 1 ) { - NodePool[i + OldPoolSize] = (SCustomSetNode*) malloc(sizeof(SCustomSetNode)); + NodePool[i + OldPoolSize] = static_cast(malloc(sizeof(SCustomSetNode))); } m_NodePool = NodePool; diff --git a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaStrings.cpp b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaStrings.cpp index ad9e423bb..b33a56015 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaStrings.cpp +++ b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaStrings.cpp @@ -15,7 +15,7 @@ uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) if( result != S_OK ) { app.DebugPrintf("sceCesUcsContextInit failed\n"); - return NULL; + return nullptr; } uint32_t utf16Len; @@ -44,7 +44,7 @@ uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) if( result != SCE_OK ) { app.DebugPrintf("sceCesUtf16StrToUtf8Str: conversion error : 0x%x\n", result); - return NULL; + return nullptr; } return strUtf8; diff --git a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTLSStorage.cpp b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTLSStorage.cpp index 0261f318a..054e9f025 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTLSStorage.cpp +++ b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTLSStorage.cpp @@ -137,7 +137,7 @@ BOOL PSVitaTLSStorage::SetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) #else -PSVitaTLSStorage* m_pInstance = NULL; +PSVitaTLSStorage* m_pInstance = nullptr; #define sc_maxSlots 64 BOOL m_activeList[sc_maxSlots]; @@ -157,7 +157,7 @@ void PSVitaTLSStorage::Init() for(int i=0;iwMilliseconds = sceRtcGetMicrosecond(&dateTime)/1000; } -HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { PSVITA_STUBBED; return NULL; } +HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { PSVITA_STUBBED; return nullptr; } VOID Sleep(DWORD dwMilliseconds) { C4JThread::Sleep(dwMilliseconds); @@ -186,7 +186,7 @@ VOID InitializeCriticalSection(PCRITICAL_SECTION CriticalSection) { char name[1] = {0}; - int err = sceKernelCreateLwMutex((SceKernelLwMutexWork *)(&CriticalSection->mutex), name, SCE_KERNEL_LW_MUTEX_ATTR_TH_PRIO | SCE_KERNEL_LW_MUTEX_ATTR_RECURSIVE, 0, NULL); + int err = sceKernelCreateLwMutex((SceKernelLwMutexWork *)(&CriticalSection->mutex), name, SCE_KERNEL_LW_MUTEX_ATTR_TH_PRIO | SCE_KERNEL_LW_MUTEX_ATTR_RECURSIVE, 0, nullptr); PSVITA_ASSERT_SCE_ERROR(err); } @@ -207,7 +207,7 @@ extern CRITICAL_SECTION g_singleThreadCS; VOID EnterCriticalSection(PCRITICAL_SECTION CriticalSection) { - int err = sceKernelLockLwMutex ((SceKernelLwMutexWork *)(&CriticalSection->mutex), 1, NULL); + int err = sceKernelLockLwMutex ((SceKernelLwMutexWork *)(&CriticalSection->mutex), 1, nullptr); PSVITA_ASSERT_SCE_ERROR(err); } @@ -233,7 +233,7 @@ VOID InitializeCriticalRWSection(PCRITICAL_RW_SECTION CriticalSection) { char name[1] = {0}; - CriticalSection->RWLock = sceKernelCreateRWLock(name, SCE_KERNEL_RW_LOCK_ATTR_TH_PRIO | SCE_KERNEL_RW_LOCK_ATTR_RECURSIVE, NULL); + CriticalSection->RWLock = sceKernelCreateRWLock(name, SCE_KERNEL_RW_LOCK_ATTR_TH_PRIO | SCE_KERNEL_RW_LOCK_ATTR_RECURSIVE, nullptr); } VOID DeleteCriticalRWSection(PCRITICAL_RW_SECTION CriticalSection) @@ -270,11 +270,9 @@ VOID LeaveCriticalRWSection(PCRITICAL_RW_SECTION CriticalSection, bool Write) PSVITA_ASSERT_SCE_ERROR(err); } - - BOOL CloseHandle(HANDLE hObject) { - sceFiosFHCloseSync(NULL,(SceFiosFH)((int32_t)hObject)); + sceFiosFHCloseSync(nullptr,(SceFiosFH)(reinterpret_cast(hObject))); return true; } @@ -514,7 +512,7 @@ BOOL VirtualWriteFile(LPCSTR lpFileName, LPCVOID lpBuffer, DWORD nNumberOfBytesT void* Data = VirtualAllocs[Page]; DWORD numberOfBytesWritten=0; - WriteFileWithName(lpFileName, Data, BytesToWrite, &numberOfBytesWritten,NULL); + WriteFileWithName(lpFileName, Data, BytesToWrite, &numberOfBytesWritten,nullptr); *lpNumberOfBytesWritten += numberOfBytesWritten; nNumberOfBytesToWrite -= BytesToWrite; @@ -656,7 +654,7 @@ DWORD GetFileSize( HANDLE hFile, LPDWORD lpFileSizeHigh ) //SceFiosSize FileSize; //FileSize=sceFiosFHGetSize(fh); SceFiosStat statData; - int err = sceFiosFHStatSync(NULL,fh,&statData); + int err = sceFiosFHStatSync(nullptr,fh,&statData); SceFiosOffset FileSize = statData.fileSize; if(lpFileSizeHigh) @@ -675,7 +673,7 @@ BOOL WriteFileWithName(LPCSTR lpFileName, LPCVOID lpBuffer, DWORD nNumberOfByte { char filePath[256]; sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); - SceFiosSize bytesWritten = sceFiosFileWriteSync( NULL, filePath, lpBuffer, nNumberOfBytesToWrite, 0 ); + SceFiosSize bytesWritten = sceFiosFileWriteSync( nullptr, filePath, lpBuffer, nNumberOfBytesToWrite, 0 ); if(bytesWritten != nNumberOfBytesToWrite) { // error @@ -698,7 +696,7 @@ BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD { SceFiosFH fh = (SceFiosFH)((int64_t)hFile); // sceFiosFHReadSync - Non-negative values are the number of bytes read, 0 <= result <= length. Negative values are error codes. - SceFiosSize bytesRead = sceFiosFHReadSync(NULL, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToRead); + SceFiosSize bytesRead = sceFiosFHReadSync(nullptr, fh, lpBuffer, (SceFiosSize)nNumberOfBytesToRead); if(bytesRead < 0) { // error @@ -718,7 +716,7 @@ BOOL SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHi uint64_t bitsToMove = (int64_t) lDistanceToMove; SceFiosOffset pos = 0; - if (lpDistanceToMoveHigh != NULL) + if (lpDistanceToMoveHigh != nullptr) bitsToMove |= ((uint64_t) (*lpDistanceToMoveHigh)) << 32; SceFiosWhence whence = SCE_FIOS_SEEK_SET; @@ -761,7 +759,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, if( dwDesiredAccess == GENERIC_WRITE ) { //CD - Create a blank file - int err = sceFiosFileWriteSync( NULL, filePath, NULL, 0, 0 ); + int err = sceFiosFileWriteSync( nullptr, filePath, nullptr, 0, 0 ); assert( err == SCE_FIOS_OK ); } @@ -770,7 +768,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, #endif SceFiosFH fh; - int err = sceFiosFHOpenSync(NULL, &fh, filePath, NULL); + int err = sceFiosFHOpenSync(nullptr, &fh, filePath, nullptr); assert( err == SCE_FIOS_OK ); return (void*)fh; @@ -816,7 +814,7 @@ DWORD GetFileAttributesA(LPCSTR lpFileName) // check if the file exists first SceFiosStat statData; - if(sceFiosStatSync(NULL, filePath, &statData) != SCE_FIOS_OK) + if(sceFiosStatSync(nullptr, filePath, &statData) != SCE_FIOS_OK) { app.DebugPrintf("*** sceFiosStatSync Failed\n"); return -1; @@ -904,7 +902,7 @@ BOOL GetFileAttributesExA(LPCSTR lpFileName,GET_FILEEX_INFO_LEVELS fInfoLevelId, // check if the file exists first SceFiosStat statData; - if(sceFiosStatSync(NULL, filePath, &statData) != SCE_FIOS_OK) + if(sceFiosStatSync(nullptr, filePath, &statData) != SCE_FIOS_OK) { app.DebugPrintf("*** sceFiosStatSync Failed\n"); return false; @@ -937,7 +935,7 @@ errno_t _i64toa_s(long long _Val, char * _DstBuf, size_t _Size, int _Radix) { if int _wtoi(const wchar_t *_Str) { - return wcstol(_Str, NULL, 10); + return wcstol(_Str, nullptr, 10); } DWORD XGetLanguage() diff --git a/Minecraft.Client/PSVita/PSVitaExtras/ShutdownManager.cpp b/Minecraft.Client/PSVita/PSVitaExtras/ShutdownManager.cpp index e7eca53f4..a04e45d9f 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/ShutdownManager.cpp +++ b/Minecraft.Client/PSVita/PSVitaExtras/ShutdownManager.cpp @@ -16,12 +16,12 @@ C4JThread::EventArray *ShutdownManager::s_eventArray[eThreadIdCount]; void ShutdownManager::Initialise() { #ifdef __PS3__ - cellSysutilRegisterCallback( 1, SysUtilCallback, NULL ); + cellSysutilRegisterCallback( 1, SysUtilCallback, nullptr ); for( int i = 0; i < eThreadIdCount; i++ ) { s_threadShouldRun[i] = true; s_threadRunning[i] = 0; - s_eventArray[i] = NULL; + s_eventArray[i] = nullptr; } // Special case for storage manager, which we will manually set now to be considered as running - this will be unset by StorageManager.ExitRequest if required s_threadRunning[eStorageManagerThreads] = true; diff --git a/Minecraft.Client/PSVita/PSVitaExtras/libdivide.h b/Minecraft.Client/PSVita/PSVitaExtras/libdivide.h index 007a84165..338378751 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/libdivide.h +++ b/Minecraft.Client/PSVita/PSVitaExtras/libdivide.h @@ -210,7 +210,7 @@ LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg4(__m128i numers, const struct static inline uint32_t libdivide__mullhi_u32(uint32_t x, uint32_t y) { uint64_t xl = x, yl = y; uint64_t rl = xl * yl; - return (uint32_t)(rl >> 32); + return static_cast(rl >> 32); } static uint64_t libdivide__mullhi_u64(uint64_t x, uint64_t y) { @@ -221,12 +221,12 @@ static uint64_t libdivide__mullhi_u64(uint64_t x, uint64_t y) { #else //full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) const uint32_t mask = 0xFFFFFFFF; - const uint32_t x0 = (uint32_t)(x & mask), x1 = (uint32_t)(x >> 32); - const uint32_t y0 = (uint32_t)(y & mask), y1 = (uint32_t)(y >> 32); + const uint32_t x0 = static_cast(x & mask), x1 = static_cast(x >> 32); + const uint32_t y0 = static_cast(y & mask), y1 = static_cast(y >> 32); const uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); - const uint64_t x0y1 = x0 * (uint64_t)y1; - const uint64_t x1y0 = x1 * (uint64_t)y0; - const uint64_t x1y1 = x1 * (uint64_t)y1; + const uint64_t x0y1 = x0 * static_cast(y1); + const uint64_t x1y0 = x1 * static_cast(y0); + const uint64_t x1y1 = x1 * static_cast(y1); uint64_t temp = x1y0 + x0y0_hi; uint64_t temp_lo = temp & mask, temp_hi = temp >> 32; @@ -242,12 +242,12 @@ static inline int64_t libdivide__mullhi_s64(int64_t x, int64_t y) { #else //full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) const uint32_t mask = 0xFFFFFFFF; - const uint32_t x0 = (uint32_t)(x & mask), y0 = (uint32_t)(y & mask); - const int32_t x1 = (int32_t)(x >> 32), y1 = (int32_t)(y >> 32); + const uint32_t x0 = static_cast(x & mask), y0 = static_cast(y & mask); + const int32_t x1 = static_cast(x >> 32), y1 = static_cast(y >> 32); const uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); - const int64_t t = x1*(int64_t)y0 + x0y0_hi; - const int64_t w1 = x0*(int64_t)y1 + (t & mask); - return x1*(int64_t)y1 + (t >> 32) + (w1 >> 32); + const int64_t t = x1*static_cast(y0) + x0y0_hi; + const int64_t w1 = x0*static_cast(y1) + (t & mask); + return x1*static_cast(y1) + (t >> 32) + (w1 >> 32); #endif } @@ -398,7 +398,7 @@ static inline int32_t libdivide__count_trailing_zeros64(uint64_t val) { /* Pretty good way to count trailing zeros. Note that this hangs for val = 0! */ uint32_t lo = val & 0xFFFFFFFF; if (lo != 0) return libdivide__count_trailing_zeros32(lo); - return 32 + libdivide__count_trailing_zeros32((uint32_t)(val >> 32)); + return 32 + libdivide__count_trailing_zeros32(static_cast(val >> 32)); #endif } @@ -444,9 +444,9 @@ static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, } #else static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { - uint64_t n = (((uint64_t)u1) << 32) | u0; - uint32_t result = (uint32_t)(n / v); - *r = (uint32_t)(n - result * (uint64_t)v); + uint64_t n = (static_cast(u1) << 32) | u0; + uint32_t result = static_cast(n / v); + *r = static_cast(n - result * static_cast(v)); return result; } #endif @@ -478,9 +478,9 @@ static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, int s; // Shift amount for norm. if (u1 >= v) { // If overflow, set rem. - if (r != NULL) // to an impossible value, - *r = (uint64_t)(-1); // and return the largest - return (uint64_t)(-1);} // possible quotient. + if (r != nullptr) // to an impossible value, + *r = static_cast(-1); // and return the largest + return static_cast(-1);} // possible quotient. /* count leading zeros */ s = libdivide__count_leading_zeros64(v); // 0 <= s <= 63. @@ -513,7 +513,7 @@ again2: rhat = rhat + vn1; if (rhat < b) goto again2;} - if (r != NULL) // If remainder is wanted, + if (r != nullptr) // If remainder is wanted, *r = (un21*b + un0 - q0*v) >> s; // return it. return q1*b + q0; } @@ -770,14 +770,14 @@ __m128i libdivide_u64_do_vector_alg2(__m128i numers, const struct libdivide_u64_ static inline int32_t libdivide__mullhi_s32(int32_t x, int32_t y) { int64_t xl = x, yl = y; int64_t rl = xl * yl; - return (int32_t)(rl >> 32); //needs to be arithmetic shift + return static_cast(rl >> 32); //needs to be arithmetic shift } struct libdivide_s32_t libdivide_s32_gen(int32_t d) { struct libdivide_s32_t result; /* If d is a power of 2, or negative a power of 2, we have to use a shift. This is especially important because the magic algorithm fails for -1. To check if d is a power of 2 or its inverse, it suffices to check whether its absolute value has exactly one bit set. This works even for INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set and is a power of 2. */ - uint32_t absD = (uint32_t)(d < 0 ? -d : d); //gcc optimizes this to the fast abs trick + uint32_t absD = static_cast(d < 0 ? -d : d); //gcc optimizes this to the fast abs trick if ((absD & (absD - 1)) == 0) { //check if exactly one bit is set, don't care if absD is 0 since that's divide by zero result.magic = 0; result.more = libdivide__count_trailing_zeros32(absD) | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0) | LIBDIVIDE_S32_SHIFT_PATH; @@ -805,7 +805,7 @@ struct libdivide_s32_t libdivide_s32_gen(int32_t d) { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); //use the general algorithm } proposed_m += 1; - result.magic = (d < 0 ? -(int32_t)proposed_m : (int32_t)proposed_m); + result.magic = (d < 0 ? -static_cast(proposed_m) : static_cast(proposed_m)); result.more = more; } @@ -818,14 +818,14 @@ int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t shifter = more & LIBDIVIDE_32_SHIFT_MASK; int32_t q = numer + ((numer >> 31) & ((1 << shifter) - 1)); q = q >> shifter; - int32_t shiftMask = (int8_t)more >> 7; //must be arithmetic shift and then sign-extend + int32_t shiftMask = static_cast(more) >> 7; //must be arithmetic shift and then sign-extend q = (q ^ shiftMask) - shiftMask; return q; } else { int32_t q = libdivide__mullhi_s32(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { - int32_t sign = (int8_t)more >> 7; //must be arithmetic shift and then sign extend + int32_t sign = static_cast(more) >> 7; //must be arithmetic shift and then sign extend q += ((numer ^ sign) - sign); } q >>= more & LIBDIVIDE_32_SHIFT_MASK; @@ -946,7 +946,7 @@ struct libdivide_s64_t libdivide_s64_gen(int64_t d) { struct libdivide_s64_t result; /* If d is a power of 2, or negative a power of 2, we have to use a shift. This is especially important because the magic algorithm fails for -1. To check if d is a power of 2 or its inverse, it suffices to check whether its absolute value has exactly one bit set. This works even for INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set and is a power of 2. */ - const uint64_t absD = (uint64_t)(d < 0 ? -d : d); //gcc optimizes this to the fast abs trick + const uint64_t absD = static_cast(d < 0 ? -d : d); //gcc optimizes this to the fast abs trick if ((absD & (absD - 1)) == 0) { //check if exactly one bit is set, don't care if absD is 0 since that's divide by zero result.more = libdivide__count_trailing_zeros64(absD) | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); result.magic = 0; @@ -974,7 +974,7 @@ struct libdivide_s64_t libdivide_s64_gen(int64_t d) { } proposed_m += 1; result.more = more; - result.magic = (d < 0 ? -(int64_t)proposed_m : (int64_t)proposed_m); + result.magic = (d < 0 ? -static_cast(proposed_m) : static_cast(proposed_m)); } return result; } @@ -986,14 +986,14 @@ int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) { uint32_t shifter = more & LIBDIVIDE_64_SHIFT_MASK; int64_t q = numer + ((numer >> 63) & ((1LL << shifter) - 1)); q = q >> shifter; - int64_t shiftMask = (int8_t)more >> 7; //must be arithmetic shift and then sign-extend + int64_t shiftMask = static_cast(more) >> 7; //must be arithmetic shift and then sign-extend q = (q ^ shiftMask) - shiftMask; return q; } else { int64_t q = libdivide__mullhi_s64(magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { - int64_t sign = (int8_t)more >> 7; //must be arithmetic shift and then sign extend + int64_t sign = static_cast(more) >> 7; //must be arithmetic shift and then sign extend q += ((numer ^ sign) - sign); } q >>= more & LIBDIVIDE_64_SHIFT_MASK; @@ -1141,11 +1141,11 @@ namespace libdivide_internal { #endif /* Some bogus unswitch functions for unsigned types so the same (presumably templated) code can work for both signed and unsigned. */ - uint32_t crash_u32(uint32_t, const libdivide_u32_t *) { abort(); return *(uint32_t *)NULL; } - uint64_t crash_u64(uint64_t, const libdivide_u64_t *) { abort(); return *(uint64_t *)NULL; } + uint32_t crash_u32(uint32_t, const libdivide_u32_t *) { abort(); return *static_cast(nullptr); } + uint64_t crash_u64(uint64_t, const libdivide_u64_t *) { abort(); return *static_cast(nullptr); } #if LIBDIVIDE_USE_SSE2 - __m128i crash_u32_vector(__m128i, const libdivide_u32_t *) { abort(); return *(__m128i *)NULL; } - __m128i crash_u64_vector(__m128i, const libdivide_u64_t *) { abort(); return *(__m128i *)NULL; } + __m128i crash_u32_vector(__m128i, const libdivide_u32_t *) { abort(); return *(__m128i *)nullptr; } + __m128i crash_u64_vector(__m128i, const libdivide_u64_t *) { abort(); return *(__m128i *)nullptr; } #endif template diff --git a/Minecraft.Client/PSVita/PSVitaExtras/user_malloc.c b/Minecraft.Client/PSVita/PSVitaExtras/user_malloc.c index 7036728f3..6b0e67b72 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/user_malloc.c +++ b/Minecraft.Client/PSVita/PSVitaExtras/user_malloc.c @@ -52,14 +52,14 @@ typedef struct int Malloc_BlocksAlloced; // this shows how many block node chunks have been allocated in Malloc_BlocksMemory } SThreadStorage; -__thread SThreadStorage *Malloc_ThreadStorage = NULL; +__thread SThreadStorage *Malloc_ThreadStorage = nullptr; /**E Replace _malloc_init function. */ /**J _malloc_init 関数と置き換わる */ void user_malloc_init(void) { int res; - void *base = NULL; + void *base = nullptr; /**E Allocate a memory block from the kernel */ /**J カーネルからメモリブロックを確保する */ @@ -80,7 +80,7 @@ void user_malloc_init(void) /**E Generate mspace */ /**J mspace を生成する */ s_mspace = mspace_create(base, HEAP_SIZE); - if (s_mspace == NULL) { + if (s_mspace == nullptr) { /**E Error handling */ /**J エラー処理 */ sceLibcSetHeapInitError(HEAP_ERROR3); @@ -95,7 +95,7 @@ void user_malloc_finalize(void) { int res; - if (s_mspace != NULL) { + if (s_mspace != nullptr) { /**E Free mspace */ /**J mspace を解放する */ res = mspace_destroy(s_mspace); @@ -104,7 +104,7 @@ void user_malloc_finalize(void) /**J エラー処理 */ __breakpoint(0); } - s_mspace = NULL; + s_mspace = nullptr; } if (SCE_OK <= s_heapUid) { @@ -125,9 +125,9 @@ void user_malloc_finalize(void) void user_registerthread() { Malloc_ThreadStorage = mspace_malloc(s_mspace, sizeof(SThreadStorage)); - Malloc_ThreadStorage->Malloc_Blocks = NULL; + Malloc_ThreadStorage->Malloc_Blocks = nullptr; Malloc_ThreadStorage->Malloc_BlocksAlloced = 0; - Malloc_ThreadStorage->Malloc_MemoryPool = NULL; + Malloc_ThreadStorage->Malloc_MemoryPool = nullptr; } // before a thread is destroyed make sure we free any space it might be holding on to @@ -157,7 +157,7 @@ void user_removethread() } mspace_free(s_mspace, psStorage); - Malloc_ThreadStorage = NULL; + Malloc_ThreadStorage = nullptr; } } @@ -165,19 +165,19 @@ void user_removethread() /**J malloc 関数と置き換わる */ void *user_malloc(size_t size) { - void *p = NULL; + void *p = nullptr; SThreadStorage *psStorage = Malloc_ThreadStorage; if( psStorage ) { // is this the first time we've malloced - if( psStorage->Malloc_MemoryPool == NULL ) + if( psStorage->Malloc_MemoryPool == nullptr ) { // create an array of pointers to Block nodes, one pointer for each memory bytes size up to 1036 psStorage->Malloc_MemoryPool = mspace_malloc(s_mspace, (MaxRetainedBytes+1) * 4); for( int i = 0;i < (MaxRetainedBytes+1);i += 1 ) { - psStorage->Malloc_MemoryPool[i] = NULL; + psStorage->Malloc_MemoryPool[i] = nullptr; } } @@ -261,7 +261,7 @@ void user_free(void *ptr) } // we need a block node to retain the memory on our stack. do we have any block nodes available - if( psStorage->Malloc_Blocks == NULL ) + if( psStorage->Malloc_Blocks == nullptr ) { if( psStorage->Malloc_BlocksAlloced == Malloc_BlocksMemorySize ) { @@ -319,7 +319,7 @@ void *user_calloc(size_t nelem, size_t size) /**J realloc 関数と置き換わる */ void *user_realloc(void *ptr, size_t size) { - void* p = NULL; + void* p = nullptr; if( Malloc_ThreadStorage ) { diff --git a/Minecraft.Client/PSVita/PSVitaExtras/user_malloc_for_tls.c b/Minecraft.Client/PSVita/PSVitaExtras/user_malloc_for_tls.c index 531bbd604..54cc0d728 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/user_malloc_for_tls.c +++ b/Minecraft.Client/PSVita/PSVitaExtras/user_malloc_for_tls.c @@ -27,7 +27,7 @@ void user_free_for_tls(void *ptr); void user_malloc_for_tls_init(void) { int res; - void *base = NULL; + void *base = nullptr; /**E Allocate a memory block from the kernel */ /**J カーネルからメモリブロックを確保する */ @@ -48,7 +48,7 @@ void user_malloc_for_tls_init(void) /**E Generate mspace */ /**J mspace を生成する */ s_mspace = mspace_create(base, HEAP_SIZE); - if (s_mspace == NULL) { + if (s_mspace == nullptr) { /**E Error handling */ /**J エラー処理 */ sceLibcSetHeapInitError(HEAP_ERROR3); @@ -63,7 +63,7 @@ void user_malloc_for_tls_finalize(void) { int res; - if (s_mspace != NULL) { + if (s_mspace != nullptr) { /**E Free mspace */ /**J mspace を解放する */ res = mspace_destroy(s_mspace); diff --git a/Minecraft.Client/PSVita/PSVitaExtras/user_new.cpp b/Minecraft.Client/PSVita/PSVitaExtras/user_new.cpp index 1f71f6d21..b9cc48502 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/user_new.cpp +++ b/Minecraft.Client/PSVita/PSVitaExtras/user_new.cpp @@ -28,13 +28,13 @@ void *user_new(std::size_t size) throw(std::bad_alloc) if (size == 0) size = 1; - while ((ptr = (void *)std::malloc(size)) == NULL) { + while ((ptr = (void *)std::malloc(size)) == nullptr) { /**E Obtain new_handler */ /**J new_handler を取得する */ std::new_handler handler = std::_get_new_handler(); - /**E When new_handler is a NULL pointer, bad_alloc is send. If not, new_handler is called. */ - /**J new_handler が NULL ポインタの場合、bad_alloc を送出する、そうでない場合、new_handler を呼び出す */ + /**E When new_handler is a nullptr pointer, bad_alloc is send. If not, new_handler is called. */ + /**J new_handler が nullptr ポインタの場合、bad_alloc を送出する、そうでない場合、new_handler を呼び出す */ if (!handler) throw std::bad_alloc(); else @@ -56,22 +56,22 @@ void *user_new(std::size_t size, const std::nothrow_t& x) throw() if (size == 0) size = 1; - while ((ptr = (void *)std::malloc(size)) == NULL) { + while ((ptr = (void *)std::malloc(size)) == nullptr) { /**E Obtain new_handler */ /**J new_handler を取得する */ std::new_handler handler = std::_get_new_handler(); - /**E When new_handler is a NULL pointer, NULL is returned. */ - /**J new_handler が NULL ポインタの場合、NULL を返す */ + /**E When new_handler is a nullptr pointer, nullptr is returned. */ + /**J new_handler が nullptr ポインタの場合、nullptr を返す */ if (!handler) - return NULL; + return nullptr; - /**E Call new_handler. If new_handler sends bad_alloc, NULL is returned. */ - /**J new_handler を呼び出す、new_handler が bad_alloc を送出した場合、NULL を返す */ + /**E Call new_handler. If new_handler sends bad_alloc, nullptr is returned. */ + /**J new_handler を呼び出す、new_handler が bad_alloc を送出した場合、nullptr を返す */ try { (*handler)(); } catch (std::bad_alloc) { - return NULL; + return nullptr; } } return ptr; @@ -98,9 +98,9 @@ void *user_new_array(std::size_t size, const std::nothrow_t& x) throw() void user_delete(void *ptr) throw() { // SCE_DBG_LOG_TRACE("Called operator delete(%p)", ptr); - /**E In the case of the NULL pointer, no action will be taken. */ - /**J NULL ポインタの場合、何も行わない */ - if (ptr != NULL) + /**E In the case of the nullptr pointer, no action will be taken. */ + /**J nullptr ポインタの場合、何も行わない */ + if (ptr != nullptr) std::free(ptr); } diff --git a/Minecraft.Client/PSVita/PSVitaExtras/zlib.h b/Minecraft.Client/PSVita/PSVitaExtras/zlib.h index 3e0c7672a..b0e74c454 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/zlib.h +++ b/Minecraft.Client/PSVita/PSVitaExtras/zlib.h @@ -91,7 +91,7 @@ typedef struct z_stream_s { uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total number of bytes output so far */ - z_const char *msg; /* last error message, NULL if no error */ + z_const char *msg; /* last error message, nullptr if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ @@ -1254,7 +1254,7 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); reading, this will be detected automatically by looking for the magic two- byte gzip header. - gzopen returns NULL if the file could not be opened, if there was + gzopen returns nullptr if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the @@ -1277,7 +1277,7 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); close the associated file descriptor, so they need to have different file descriptors. - gzdopen returns NULL if there was insufficient memory to allocate the + gzdopen returns nullptr if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen @@ -1377,7 +1377,7 @@ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. - gzgets returns buf which is a null-terminated string, or it returns NULL + gzgets returns buf which is a null-terminated string, or it returns nullptr for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ @@ -1393,7 +1393,7 @@ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. - it does not check to see if file is NULL, nor whether the structure file + it does not check to see if file is nullptr, nor whether the structure file points to has been clobbered or not. */ diff --git a/Minecraft.Client/PSVita/PSVita_App.cpp b/Minecraft.Client/PSVita/PSVita_App.cpp index 542102d2a..8c9236c77 100644 --- a/Minecraft.Client/PSVita/PSVita_App.cpp +++ b/Minecraft.Client/PSVita/PSVita_App.cpp @@ -32,15 +32,15 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_bVoiceChatAndUGCRestricted=false; m_bDisplayFullVersionPurchase=false; - m_ProductListA=NULL; + m_ProductListA=nullptr; m_pRemoteStorage = new SonyRemoteStorage_Vita; m_bSaveIncompleteDialogRunning = false; m_bSaveDataDeleteDialogState = eSaveDataDeleteState_idle; - m_pSaveToDelete = NULL; - m_pCheckoutProductInfo = NULL; + m_pSaveToDelete = nullptr; + m_pCheckoutProductInfo = nullptr; } void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) @@ -62,7 +62,7 @@ char *CConsoleMinecraftApp::GetCommerceCategory() } char *CConsoleMinecraftApp::GetTexturePacksCategoryID() { - return NULL; // ProductCodes.chTexturePackID; + return nullptr; // ProductCodes.chTexturePackID; } char *CConsoleMinecraftApp::GetUpgradeKey() { @@ -101,7 +101,7 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(char *pchTitle) { app.DebugPrintf("Couldn't find DLC info for %s\n", pchTitle); assert(0); - return NULL; + return nullptr; } return it->second; @@ -118,7 +118,7 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(int iTexturePackID) if(it->second->iConfig == iTexturePackID) return it->second; } - return NULL; + return nullptr; } @@ -128,7 +128,7 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() char chDLCTitle[64]; // 4J-PB - Read the file containing the product codes. This will be different for the SCEE/SCEA/SCEJ builds - HANDLE file = CreateFile("PSVita/PSVitaProductCodes.bin", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile("PSVita/PSVitaProductCodes.bin", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { DWORD error = GetLastError(); @@ -143,13 +143,13 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() { DWORD bytesRead; - WRAPPED_READFILE(file,ProductCodes.chProductCode,PRODUCT_CODE_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,NULL); - //WRAPPED_READFILE(file,ProductCodes.chDiscSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,NULL); - WRAPPED_READFILE(file,ProductCodes.chCommerceCategory,COMMERCE_CATEGORY_SIZE,&bytesRead,NULL); - //WRAPPED_READFILE(file,ProductCodes.chTexturePackID,SCE_NP_COMMERCE2_CATEGORY_ID_LEN,&bytesRead,NULL); // TODO - WRAPPED_READFILE(file,ProductCodes.chUpgradeKey,UPGRADE_KEY_SIZE,&bytesRead,NULL); - //WRAPPED_READFILE(file,ProductCodes.chSkuPostfix,SKU_POSTFIX_SIZE,&bytesRead,NULL); + WRAPPED_READFILE(file,ProductCodes.chProductCode,PRODUCT_CODE_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,nullptr); + //WRAPPED_READFILE(file,ProductCodes.chDiscSaveFolderPrefix,SAVEFOLDERPREFIX_SIZE,&bytesRead,nullptr); + WRAPPED_READFILE(file,ProductCodes.chCommerceCategory,COMMERCE_CATEGORY_SIZE,&bytesRead,nullptr); + //WRAPPED_READFILE(file,ProductCodes.chTexturePackID,SCE_NP_COMMERCE2_CATEGORY_ID_LEN,&bytesRead,nullptr); // TODO + WRAPPED_READFILE(file,ProductCodes.chUpgradeKey,UPGRADE_KEY_SIZE,&bytesRead,nullptr); + //WRAPPED_READFILE(file,ProductCodes.chSkuPostfix,SKU_POSTFIX_SIZE,&bytesRead,nullptr); app.DebugPrintf("ProductCodes.chProductCode %s\n",ProductCodes.chProductCode); app.DebugPrintf("ProductCodes.chSaveFolderPrefix %s\n",ProductCodes.chSaveFolderPrefix); @@ -161,7 +161,7 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() // DLC unsigned int uiDLC; - WRAPPED_READFILE(file,&uiDLC,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&uiDLC,sizeof(int),&bytesRead,nullptr); for(unsigned int i=0;ichDLCKeyname,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,pDLCInfo->chDLCKeyname,sizeof(char)*uiVal,&bytesRead,nullptr); - WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,NULL); + WRAPPED_READFILE(file,&uiVal,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,chDLCTitle,sizeof(char)*uiVal,&bytesRead,nullptr); app.DebugPrintf("DLC title %s\n",chDLCTitle); - WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,NULL); - WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,NULL); + WRAPPED_READFILE(file,&pDLCInfo->eDLCType,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,&pDLCInfo->iFirstSkin,sizeof(int),&bytesRead,nullptr); + WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,nullptr); // push this into a vector @@ -296,7 +296,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() { ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // From CScene_Main::RunPlayGame Minecraft *pMinecraft=Minecraft::GetInstance(); @@ -322,7 +322,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() NetworkGameInitData *param = new NetworkGameInitData(); param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; g_NetworkManager.HostGame(0,false,true,MINECRAFT_NET_MAX_PLAYERS,0); @@ -545,7 +545,7 @@ SonyCommerce::CategoryInfo *CConsoleMinecraftApp::GetCategoryInfo() { if(m_bCommerceCategoriesRetrieved==false) { - return NULL; + return nullptr; } return &m_CategoryInfo; @@ -561,10 +561,10 @@ void CConsoleMinecraftApp::ClearCommerceDetails() pProductList->clear(); } - if(m_ProductListA!=NULL) + if(m_ProductListA!=nullptr) { delete [] m_ProductListA; - m_ProductListA=NULL; + m_ProductListA=nullptr; } m_ProductListRetrievedC=0; @@ -590,7 +590,7 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch // find the DLC for(int i=0;i* pProductList=&m_ProductListA[i]; auto itEnd = pProductList->end(); @@ -613,11 +613,11 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch void CConsoleMinecraftApp::Checkout(char *pchSkuID) { - SonyCommerce::ProductInfo* productInfo = NULL; + SonyCommerce::ProductInfo* productInfo = nullptr; for(int i=0;i* pProductList=&m_ProductListA[i]; auto itEnd = pProductList->end(); @@ -684,7 +684,7 @@ std::vector* CConsoleMinecraftApp::GetProductList(int { if((m_bCommerceProductListRetrieved==false) || (m_bProductListAdditionalDetailsRetrieved==false) ) { - return NULL; + return nullptr; } return &m_ProductListA[iIndex]; @@ -697,7 +697,7 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) // find the DLC for(int i=0;i* pProductList=&m_ProductListA[i]; auto itEnd = pProductList->end(); @@ -1076,7 +1076,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); bool bEmptyStore=true; - if(pCategories!=NULL) + if(pCategories!=nullptr) { if(pCategories->countOfProducts>0) { @@ -1288,7 +1288,7 @@ int CConsoleMinecraftApp::cbConfirmDeleteMessageBox(void *pParam, int iPad, cons { CConsoleMinecraftApp *pClass = (CConsoleMinecraftApp*) pParam; - if (pClass != NULL && pClass->m_pSaveToDelete != NULL) + if (pClass != nullptr && pClass->m_pSaveToDelete != nullptr) { if (result == C4JStorage::EMessage_ResultDecline) { @@ -1408,12 +1408,12 @@ void CConsoleMinecraftApp::initSaveDataDeleteDialog() ui.SetSysUIShowing(true); // Start getting saves data to use when deleting. - if (StorageManager.ReturnSavesInfo() == NULL) + if (StorageManager.ReturnSavesInfo() == nullptr) { C4JStorage::ESaveGameState eSGIStatus = StorageManager.GetSavesInfo( ProfileManager.GetPrimaryPad(), - NULL, + nullptr, this, "save" ); @@ -1471,15 +1471,15 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() if ( dialogResult.result == SCE_COMMON_DIALOG_RESULT_OK ) { SceAppUtilSaveDataSlotParam slotParam; - ret = sceAppUtilSaveDataSlotGetParam( dialogResult.slotId, &slotParam, NULL ); + ret = sceAppUtilSaveDataSlotGetParam( dialogResult.slotId, &slotParam, nullptr ); if (ret == SCE_OK) { int saveindex = -1; - PSAVE_INFO pSaveInfo = NULL; + PSAVE_INFO pSaveInfo = nullptr; PSAVE_DETAILS pSaveDetails = StorageManager.ReturnSavesInfo(); - if (pSaveDetails != NULL) + if (pSaveDetails != nullptr) { app.DebugPrintf("[SaveDataDeleteDialog] Searching for save files:\n"); @@ -1504,7 +1504,7 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() app.DebugPrintf("[SaveDataDeleteDialog] ERROR: PERFORMING DELETE OPERATION, pSavesDetails is null.\n"); } - if (pSaveInfo != NULL) + if (pSaveInfo != nullptr) { app.DebugPrintf( "[SaveDataDeleteDialog] User wishes to delete slot_%d:\n\t" @@ -1603,7 +1603,7 @@ void CConsoleMinecraftApp::getSaveDataDeleteDialogParam(SceSaveDataDialogParam * for (unsigned int i = 2; i < SCE_APPUTIL_SAVEDATA_SLOT_MAX; i++) { SceAppUtilSaveDataSlotParam slotParam; - int ret = sceAppUtilSaveDataSlotGetParam( i, &slotParam, NULL ); + int ret = sceAppUtilSaveDataSlotGetParam( i, &slotParam, nullptr ); if (ret == SCE_OK) { @@ -1645,8 +1645,8 @@ void CConsoleMinecraftApp::getSaveDataDeleteDialogParam(SceSaveDataDialogParam * // baseParam->commonParam.dimmerColor = &s_dColor; - static uint8_t *strPtr = NULL; - if (strPtr != NULL) delete strPtr; + static uint8_t *strPtr = nullptr; + if (strPtr != nullptr) delete strPtr; strPtr = mallocAndCreateUTF8ArrayFromString( IDS_TOOLTIPS_DELETESAVE ); listParam.listTitle = (const SceChar8 *) strPtr; diff --git a/Minecraft.Client/PSVita/PSVita_App.h b/Minecraft.Client/PSVita/PSVita_App.h index 209fb91a0..5e31a3bea 100644 --- a/Minecraft.Client/PSVita/PSVita_App.h +++ b/Minecraft.Client/PSVita/PSVita_App.h @@ -83,7 +83,7 @@ public: // BANNED LEVEL LIST virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable *GetStringTable() { return nullptr;} // original code virtual void TemporaryCreateGameStart(); diff --git a/Minecraft.Client/PSVita/PSVita_Minecraft.cpp b/Minecraft.Client/PSVita/PSVita_Minecraft.cpp index 7544c98d8..db1e7f0fd 100644 --- a/Minecraft.Client/PSVita/PSVita_Minecraft.cpp +++ b/Minecraft.Client/PSVita/PSVita_Minecraft.cpp @@ -289,7 +289,7 @@ void MemSect(int sect) void debugSaveGameDirect() { - C4JThread* thread = new C4JThread(&IUIScene_PauseMenu::SaveWorldThreadProc, NULL, "debugSaveGameDirect"); + C4JThread* thread = new C4JThread(&IUIScene_PauseMenu::SaveWorldThreadProc, nullptr, "debugSaveGameDirect"); thread->Run(); thread->WaitForCompletion(1000); } @@ -521,7 +521,7 @@ int main() PSVitaNPToolkit::init(); // initialise the storage manager with a default save display name, a Minimum save size, and a callback for displaying the saving message - StorageManager.Init( 0, L"savegame.dat", "savePackName", FIFTY_ONE_MB, &CConsoleMinecraftApp::DisplaySavingMessage, (LPVOID)&app, NULL); + StorageManager.Init( 0, L"savegame.dat", "savePackName", FIFTY_ONE_MB, &CConsoleMinecraftApp::DisplaySavingMessage, (LPVOID)&app, nullptr); StorageManager.SetDLCProductCode(app.GetProductCode()); StorageManager.SetProductUpgradeKey(app.GetUpgradeKey()); ProfileManager.SetServiceID(app.GetCommerceCategory()); @@ -625,9 +625,9 @@ int main() StorageManager.SetDefaultImages((PBYTE)baOptionsIcon.data, baOptionsIcon.length,(PBYTE)baSaveImage.data, baSaveImage.length,(PBYTE)baSaveThumbnail.data, baSaveThumbnail.length); - if(baOptionsIcon.data!=NULL){ delete [] baOptionsIcon.data; } - if(baSaveThumbnail.data!=NULL){ delete [] baSaveThumbnail.data; } - if(baSaveImage.data!=NULL){ delete [] baSaveImage.data; } + if(baOptionsIcon.data!=nullptr){ delete [] baOptionsIcon.data; } + if(baSaveThumbnail.data!=nullptr){ delete [] baSaveThumbnail.data; } + if(baSaveImage.data!=nullptr){ delete [] baSaveImage.data; } StorageManager.SetIncompleteSaveCallback(CConsoleMinecraftApp::Callback_SaveGameIncomplete, (LPVOID)&app); @@ -656,7 +656,7 @@ int main() #endif StorageManager.SetDLCInfoMap(app.GetSonyDLCMap()); - app.CommerceInit(); // MGH - moved this here so GetCommerce isn't NULL + app.CommerceInit(); // MGH - moved this here so GetCommerce isn't nullptr // 4J-PB - Kick of the check for trial or full version - requires ui to be initialised app.GetCommerce()->CheckForTrialUpgradeKey(); @@ -857,7 +857,7 @@ int main() else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); @@ -1068,7 +1068,7 @@ vector vRichPresenceStrings; uint8_t * AddRichPresenceString(int iID) { uint8_t *strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); - if( strUtf8 != NULL ) + if( strUtf8 != nullptr ) { vRichPresenceStrings.push_back(strUtf8); } @@ -1078,7 +1078,7 @@ uint8_t * AddRichPresenceString(int iID) void FreeRichPresenceStrings() { uint8_t *strUtf8; - for(int i=0;i _painting, double x, double y, random->setSeed(187); glPushMatrix(); - glTranslatef((float)x, (float)y, (float)z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); glRotatef(rot, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); bindTexture(painting); // 4J was L"/art/kz.png" diff --git a/Minecraft.Client/Particle.cpp b/Minecraft.Client/Particle.cpp index 1091a26aa..643dc6695 100644 --- a/Minecraft.Client/Particle.cpp +++ b/Minecraft.Client/Particle.cpp @@ -19,7 +19,7 @@ void Particle::_init(Level *level, double x, double y, double z) { // 4J - added these initialisers alpha = 1.0f; - tex = NULL; + tex = nullptr; gravity = 0.0f; setSize(0.2f, 0.2f); @@ -35,7 +35,7 @@ void Particle::_init(Level *level, double x, double y, double z) size = (random->nextFloat() * 0.5f + 0.5f) * 2; - lifetime = (int) (4 / (random->nextFloat() * 0.9f + 0.1f)); + lifetime = static_cast(4 / (random->nextFloat() * 0.9f + 0.1f)); age = 0; texX = 0; @@ -51,10 +51,10 @@ Particle::Particle(Level *level, double x, double y, double z, double xa, double { _init(level,x,y,z); - xd = xa + (float) (Math::random() * 2 - 1) * 0.4f; - yd = ya + (float) (Math::random() * 2 - 1) * 0.4f; - zd = za + (float) (Math::random() * 2 - 1) * 0.4f; - float speed = (float) (Math::random() + Math::random() + 1) * 0.15f; + xd = xa + static_cast(Math::random() * 2 - 1) * 0.4f; + yd = ya + static_cast(Math::random() * 2 - 1) * 0.4f; + zd = za + static_cast(Math::random() * 2 - 1) * 0.4f; + float speed = static_cast(Math::random() + Math::random() + 1) * 0.15f; float dd = (float) (Mth::sqrt(xd * xd + yd * yd + zd * zd)); xd = xd / dd * speed * 0.4f; @@ -156,7 +156,7 @@ void Particle::render(Tesselator *t, float a, float xa, float ya, float za, floa float v1 = v0 + 0.999f / 16.0f; float r = 0.1f * size; - if (tex != NULL) + if (tex != nullptr) { u0 = tex->getU0(); u1 = tex->getU1(); @@ -164,9 +164,9 @@ void Particle::render(Tesselator *t, float a, float xa, float ya, float za, floa v1 = tex->getV1(); } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); float br = 1.0f; // 4J - change brought forward from 1.8.2 if( !SharedConstants::TEXTURE_LIGHTING ) diff --git a/Minecraft.Client/ParticleEngine.cpp b/Minecraft.Client/ParticleEngine.cpp index 7fe260632..f8a8ec230 100644 --- a/Minecraft.Client/ParticleEngine.cpp +++ b/Minecraft.Client/ParticleEngine.cpp @@ -17,7 +17,7 @@ ResourceLocation ParticleEngine::PARTICLES_LOCATION = ResourceLocation(TN_PARTIC ParticleEngine::ParticleEngine(Level *level, Textures *textures) { -// if (level != NULL) // 4J - removed - we want level to be initialised to *something* +// if (level != nullptr) // 4J - removed - we want level to be initialised to *something* { this->level = level; } @@ -83,6 +83,11 @@ void ParticleEngine::tick() void ParticleEngine::render(shared_ptr player, float a, int list) { + if (player == nullptr) + { + return; + } + // 4J - change brought forward from 1.2.3 float xa = Camera::xa; float za = Camera::za; @@ -188,8 +193,8 @@ void ParticleEngine::renderLit(shared_ptr player, float a, int list) void ParticleEngine::setLevel(Level *level) { this->level = level; - // 4J - we've now got a set of particle vectors for each dimension, and only clearing them when its game over & the level is set to NULL - if( level == NULL ) + // 4J - we've now got a set of particle vectors for each dimension, and only clearing them when its game over & the level is set to nullptr + if( level == nullptr ) { for( int l = 0; l < 3; l++ ) { @@ -218,7 +223,7 @@ void ParticleEngine::destroy(int x, int y, int z, int tid, int data) double yp = y + (yy + 0.5) / SD; double zp = z + (zz + 0.5) / SD; int face = random->nextInt(6); - add(( shared_ptr(new TerrainParticle(level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, zp - z - 0.5f, tile, face, data, textures) ) )->init(x, y, z, data)); + add((std::make_shared(level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, zp - z - 0.5f, tile, face, data, textures))->init(x, y, z, data)); } } @@ -237,7 +242,7 @@ void ParticleEngine::crack(int x, int y, int z, int face) if (face == 3) zp = z + tile->getShapeZ1() + r; if (face == 4) xp = x + tile->getShapeX0() - r; if (face == 5) xp = x + tile->getShapeX1() + r; - add(( shared_ptr(new TerrainParticle(level, xp, yp, zp, 0, 0, 0, tile, face, level->getData(x, y, z), textures) ) )->init(x, y, z, level->getData(x, y, z))->setPower(0.2f)->scale(0.6f)); + add((std::make_shared(level, xp, yp, zp, 0, 0, 0, tile, face, level->getData(x, y, z), textures))->init(x, y, z, level->getData(x, y, z))->setPower(0.2f)->scale(0.6f)); } diff --git a/Minecraft.Client/PauseScreen.cpp b/Minecraft.Client/PauseScreen.cpp index 18d066b5a..a17e52dfb 100644 --- a/Minecraft.Client/PauseScreen.cpp +++ b/Minecraft.Client/PauseScreen.cpp @@ -54,12 +54,12 @@ void PauseScreen::buttonClicked(Button button) minecraft->level->disconnect(); } - minecraft->setLevel(NULL); + minecraft->setLevel(nullptr); minecraft->setScreen(new TitleScreen()); } if (button.id == 4) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft->grabMouse(); // 4J - removed } @@ -88,7 +88,7 @@ void PauseScreen::render(int xm, int ym, float a) { float col = ((visibleTime % 10) + a) / 10.0f; col = Mth::sin(col * PI * 2) * 0.2f + 0.8f; - int br = (int) (255 * col); + int br = static_cast(255 * col); drawString(font, L"Saving level..", 8, height - 16, br << 16 | br << 8 | br); } diff --git a/Minecraft.Client/PendingConnection.cpp b/Minecraft.Client/PendingConnection.cpp index 29ab7c281..f24086c1b 100644 --- a/Minecraft.Client/PendingConnection.cpp +++ b/Minecraft.Client/PendingConnection.cpp @@ -14,6 +14,11 @@ #include "..\Minecraft.World\net.minecraft.world.item.h" #include "..\Minecraft.World\SharedConstants.h" #include "Settings.h" +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include "..\Minecraft.Server\ServerLogManager.h" +#include "..\Minecraft.Server\Access\Access.h" +#include "..\Minecraft.World\Socket.h" +#endif // #ifdef __PS3__ // #include "PS3\Network\NetworkPlayerSony.h" // #endif @@ -24,6 +29,24 @@ Random *PendingConnection::random = new Random(); bool g_bRejectDuplicateNames = true; #endif +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +namespace +{ + static unsigned char GetPendingConnectionSmallId(Connection *connection) + { + if (connection != nullptr) + { + Socket *socket = connection->getSocket(); + if (socket != nullptr) + { + return socket->getSmallId(); + } + } + return 0; + } +} +#endif + PendingConnection::PendingConnection(MinecraftServer *server, Socket *socket, const wstring& id) { // 4J - added initialisers @@ -45,7 +68,7 @@ PendingConnection::~PendingConnection() void PendingConnection::tick() { - if (acceptedLogin != NULL) + if (acceptedLogin != nullptr) { this->handleAcceptedLogin(acceptedLogin); acceptedLogin = nullptr; @@ -65,7 +88,7 @@ void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) // try { // 4J - removed try/catch // logger.info("Disconnecting " + getName() + ": " + reason); app.DebugPrintf("Pending connection disconnect: %d\n", reason ); - connection->send( shared_ptr( new DisconnectPacket(reason) ) ); + connection->send(std::make_shared(reason)); connection->sendAndQuit(); done = true; // } catch (Exception e) { @@ -121,7 +144,7 @@ void PendingConnection::sendPreLoginResponse() // Need to use the online XUID otherwise friend checks will fail on the client ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID; - if( player->connection->getNetworkPlayer() != NULL && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; + if( player->connection->getNetworkPlayer() != nullptr && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; ++ugcXuidCount; } @@ -136,9 +159,9 @@ void PendingConnection::sendPreLoginResponse() else #endif { - DWORD cappedCount = (ugcXuidCount > 255u) ? 255u : static_cast(ugcXuidCount); + DWORD cappedCount = (ugcXuidCount > 255u) ? 255u : ugcXuidCount; BYTE cappedHostIndex = (hostIndex >= 255u) ? 254 : static_cast(hostIndex); - connection->send( shared_ptr( new PreLoginPacket(L"-", ugcXuids, cappedCount, ugcFriendsOnlyBits, server->m_ugcPlayersVersion,szUniqueMapName,app.GetGameHostOption(eGameHostOption_All),cappedHostIndex, server->m_texturePackId) ) ); + connection->send(std::make_shared(L"-", ugcXuids, cappedCount, ugcFriendsOnlyBits, server->m_ugcPlayersVersion, szUniqueMapName, app.GetGameHostOption(eGameHostOption_All), cappedHostIndex, server->m_texturePackId)); } } @@ -180,18 +203,59 @@ void PendingConnection::handleLogin(shared_ptr packet) duplicateXuid = true; } + bool bannedXuid = false; + if (loginXuid != INVALID_XUID) + { + bannedXuid = server->getPlayers()->isXuidBanned(loginXuid); + } + if (!bannedXuid && packet->m_onlineXuid != INVALID_XUID && packet->m_onlineXuid != loginXuid) + { + bannedXuid = server->getPlayers()->isXuidBanned(packet->m_onlineXuid); + } + + bool whitelistSatisfied = true; +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + if (ServerRuntime::Access::IsWhitelistEnabled()) + { + whitelistSatisfied = false; + if (loginXuid != INVALID_XUID) + { + whitelistSatisfied = ServerRuntime::Access::IsPlayerWhitelisted(loginXuid); + } + if (!whitelistSatisfied && packet->m_onlineXuid != INVALID_XUID && packet->m_onlineXuid != loginXuid) + { + whitelistSatisfied = ServerRuntime::Access::IsPlayerWhitelisted(packet->m_onlineXuid); + } + } +#endif + if( sentDisconnect ) { // Do nothing } - else if( server->getPlayers()->isXuidBanned( packet->m_onlineXuid ) ) + else if (bannedXuid) { +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnRejectedPlayerLogin(GetPendingConnectionSmallId(connection), name, ServerRuntime::ServerLogManager::eLoginRejectReason_BannedXuid); +#endif + disconnect(DisconnectPacket::eDisconnect_Banned); + } + else if (!whitelistSatisfied) + { +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnRejectedPlayerLogin(GetPendingConnectionSmallId(connection), name, ServerRuntime::ServerLogManager::eLoginRejectReason_NotWhitelisted); +#endif disconnect(DisconnectPacket::eDisconnect_Banned); } else if (duplicateXuid) { - // if same XUID already in use by another player so disconnect this one. - app.DebugPrintf("Rejecting duplicate xuid for name: %ls\n", name.c_str()); +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnRejectedPlayerLogin(GetPendingConnectionSmallId(connection), name, ServerRuntime::ServerLogManager::eLoginRejectReason_DuplicateXuid); +#endif + // Reject the incoming connection — a player with this UID is already + // on the server. Allowing duplicates causes invisible players and + // other undefined behaviour. + app.DebugPrintf("LOGIN: Rejecting duplicate xuid for name: %ls\n", name.c_str()); disconnect(DisconnectPacket::eDisconnect_Banned); } #ifdef _WINDOWS64 @@ -201,7 +265,7 @@ void PendingConnection::handleLogin(shared_ptr packet) vector >& pl = server->getPlayers()->players; for (const auto& i : pl) { - if (i != NULL && i->name == name) + if (i != nullptr && i->name == name) { nameTaken = true; break; @@ -209,6 +273,9 @@ void PendingConnection::handleLogin(shared_ptr packet) } if (nameTaken) { +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnRejectedPlayerLogin(GetPendingConnectionSmallId(connection), name, ServerRuntime::ServerLogManager::eLoginRejectReason_DuplicateName); +#endif app.DebugPrintf("Rejecting duplicate name: %ls\n", name.c_str()); disconnect(DisconnectPacket::eDisconnect_Banned); } @@ -264,10 +331,13 @@ void PendingConnection::handleAcceptedLogin(shared_ptr packet) if(playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; shared_ptr playerEntity = server->getPlayers()->getPlayerForLogin(this, name, playerXuid,packet->m_onlineXuid); - if (playerEntity != NULL) + if (playerEntity != nullptr) { +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnAcceptedPlayerLogin(GetPendingConnectionSmallId(connection), name); +#endif server->getPlayers()->placeNewPlayer(connection, playerEntity, packet); - connection = NULL; // We've moved responsibility for this over to the new PlayerConnection, NULL so we don't delete our reference to it here in our dtor + connection = nullptr; // We've moved responsibility for this over to the new PlayerConnection, nullptr so we don't delete our reference to it here in our dtor } done = true; @@ -284,7 +354,7 @@ void PendingConnection::handleGetInfo(shared_ptr packet) //try { //String message = server->motd + "�" + server->players->getPlayerCount() + "�" + server->players->getMaxPlayers(); //connection->send(new DisconnectPacket(message)); - connection->send(shared_ptr(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull) ) ); + connection->send(std::make_shared(DisconnectPacket::eDisconnect_ServerFull)); connection->sendAndQuit(); server->connection->removeSpamProtection(connection->getSocket()); done = true; @@ -323,4 +393,4 @@ bool PendingConnection::isServerPacketListener() bool PendingConnection::isDisconnected() { return done; -} \ No newline at end of file +} diff --git a/Minecraft.Client/PistonPieceRenderer.cpp b/Minecraft.Client/PistonPieceRenderer.cpp index c51d2e0f8..0982e69ae 100644 --- a/Minecraft.Client/PistonPieceRenderer.cpp +++ b/Minecraft.Client/PistonPieceRenderer.cpp @@ -12,7 +12,7 @@ ResourceLocation PistonPieceRenderer::SIGN_LOCATION = ResourceLocation(TN_ITEM_S PistonPieceRenderer::PistonPieceRenderer() { - tileRenderer = NULL; + tileRenderer = nullptr; } void PistonPieceRenderer::render(shared_ptr _entity, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) @@ -21,7 +21,7 @@ void PistonPieceRenderer::render(shared_ptr _entity, double x, doubl shared_ptr entity = dynamic_pointer_cast(_entity); Tile *tile = Tile::tiles[entity->getId()]; - if (tile != NULL && entity->getProgress(a) <= 1) // 4J - changed condition from < to <= as our chunk update is async to main thread and so we can have to render these with progress of 1 + if (tile != nullptr && entity->getProgress(a) <= 1) // 4J - changed condition from < to <= as our chunk update is async to main thread and so we can have to render these with progress of 1 { Tesselator *t = Tesselator::getInstance(); bindTexture(&TextureAtlas::LOCATION_BLOCKS); @@ -35,7 +35,7 @@ void PistonPieceRenderer::render(shared_ptr _entity, double x, doubl t->begin(); - t->offset((float) x - entity->x + entity->getXOff(a), (float) y - entity->y + entity->getYOff(a), (float) z - entity->z + entity->getZOff(a)); + t->offset(static_cast(x) - entity->x + entity->getXOff(a), static_cast(y) - entity->y + entity->getYOff(a), static_cast(z) - entity->z + entity->getZOff(a)); t->color(1, 1, 1); if (tile == Tile::pistonExtension && entity->getProgress(a) < 0.5f) { @@ -45,11 +45,11 @@ void PistonPieceRenderer::render(shared_ptr _entity, double x, doubl else if (entity->isSourcePiston() && !entity->isExtending()) { // special case for withdrawing the arm back into the base - Tile::pistonExtension->setOverrideTopTexture(((PistonBaseTile *) tile)->getPlatformTexture()); + Tile::pistonExtension->setOverrideTopTexture(static_cast(tile)->getPlatformTexture()); tileRenderer->tesselatePistonArmNoCulling(Tile::pistonExtension, entity->x, entity->y, entity->z, entity->getProgress(a) < 0.5f, entity->getData()); Tile::pistonExtension->clearOverrideTopTexture(); - t->offset((float) x - entity->x, (float) y - entity->y, (float) z - entity->z); + t->offset(static_cast(x) - entity->x, static_cast(y) - entity->y, static_cast(z) - entity->z); tileRenderer->tesselatePistonBaseForceExtended(tile, entity->x, entity->y, entity->z, entity->getData()); } else diff --git a/Minecraft.Client/PlayerChunkMap.cpp b/Minecraft.Client/PlayerChunkMap.cpp index 42df6284a..bcc3f6ba0 100644 --- a/Minecraft.Client/PlayerChunkMap.cpp +++ b/Minecraft.Client/PlayerChunkMap.cpp @@ -65,7 +65,7 @@ void PlayerChunkMap::PlayerChunk::add(shared_ptr player, bool send player->seenChunks.insert(pos); // 4J Added the sendPacket check. See PlayerChunkMap::add for the usage - if( sendPacket ) player->connection->send( shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, true) ) ); + if( sendPacket ) player->connection->send(std::make_shared(pos.x, pos.z, true)); if (players.empty()) { @@ -83,7 +83,7 @@ void PlayerChunkMap::PlayerChunk::add(shared_ptr player, bool send void PlayerChunkMap::PlayerChunk::remove(shared_ptr player) { - PlayerChunkMap::PlayerChunk *toDelete = NULL; + PlayerChunkMap::PlayerChunk *toDelete = nullptr; //app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove x=%d\tz=%d\n",x,z); auto it = find(players.begin(), players.end(), player); @@ -122,7 +122,7 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr player) // 4J - I don't think there's any point sending these anymore, as we don't need to unload chunks with fixed sized maps // 4J - We do need to send these to unload entities in chunks when players are dead. If we do not and the entity is removed // while they are dead, that entity will remain in the clients world - if (player->connection != NULL && player->seenChunks.find(pos) != player->seenChunks.end()) + if (player->connection != nullptr && player->seenChunks.find(pos) != player->seenChunks.end()) { INetworkPlayer *thisNetPlayer = player->connection->getNetworkPlayer(); bool noOtherPlayersFound = true; @@ -134,7 +134,7 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr player) if ( currPlayer ) { INetworkPlayer *currNetPlayer = currPlayer->connection->getNetworkPlayer(); - if( currNetPlayer != NULL && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) + if( currNetPlayer != nullptr && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) { noOtherPlayersFound = false; break; @@ -144,12 +144,12 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr player) if(noOtherPlayersFound) { //wprintf(L"Sending ChunkVisiblity packet false for chunk (%d,%d) to player %ls\n", x, z, player->name.c_str() ); - player->connection->send( shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, false) ) ); + player->connection->send(std::make_shared(pos.x, pos.z, false)); } } else { - //app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer is NULL\n"); + //app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer is nullptr\n"); } } @@ -188,7 +188,7 @@ void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) if (changes < MAX_CHANGES_BEFORE_RESEND) { - short id = (short) ((x << 12) | (z << 8) | (y)); + short id = static_cast((x << 12) | (z << 8) | (y)); for (int i = 0; i < changes; i++) { @@ -208,7 +208,7 @@ void PlayerChunkMap::PlayerChunk::prioritiseTileChanges() // One system id per machine so we send at most once per system. Local = 256, remote = GetSmallId(). static int getSystemIdForSentTo(INetworkPlayer* np) { - if (np == NULL) return -1; + if (np == nullptr) return -1; return np->IsLocal() ? 256 : (int)np->GetSmallId(); } @@ -219,7 +219,7 @@ void PlayerChunkMap::PlayerChunk::broadcast(shared_ptr packet) { shared_ptr player = players[i]; INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - if (thisPlayer == NULL) continue; + if (thisPlayer == nullptr) continue; int sysId = getSystemIdForSentTo(thisPlayer); if (sysId >= 0 && sentToSystemIds.find(sysId) != sentToSystemIds.end()) continue; @@ -239,15 +239,15 @@ void PlayerChunkMap::PlayerChunk::broadcast(shared_ptr packet) for (size_t i = 0; i < allPlayers.size(); i++) { shared_ptr player = allPlayers[i]; - if (player->connection == NULL || player->connection->isLocal()) continue; + if (player->connection == nullptr || player->connection->isLocal()) continue; INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - if (thisPlayer == NULL) continue; + if (thisPlayer == nullptr) continue; int sysId = getSystemIdForSentTo(thisPlayer); if (sysId >= 0 && sentToSystemIds.find(sysId) != sentToSystemIds.end()) continue; - int flagIndex = ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); + const int flagIndex = ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); if (!g_NetworkManager.SystemFlagGet(thisPlayer, flagIndex)) continue; player->connection->send(packet); @@ -270,7 +270,7 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) int x = pos.x * 16 + xChangeMin; int y = yChangeMin; int z = pos.z * 16 + zChangeMin; - broadcast( shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + broadcast(std::make_shared(x, y, z, level)); if (level->isEntityTile(x, y, z)) { broadcast(level->getTileEntity(x, y, z)); @@ -300,7 +300,7 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) // Block region update packets can only encode ys in a range of 1 - 256 if( ys > 256 ) ys = 256; - broadcast( shared_ptr( new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level) ) ); + broadcast(std::make_shared(xp, yp, zp, xs, ys, zs, level)); vector > *tes = level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, zp + zs); for (unsigned int i = 0; i < tes->size(); i++) { @@ -313,7 +313,7 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) else { // 4J As we only get here if changes is less than MAX_CHANGES_BEFORE_RESEND (10) we only need to send a byte value in the packet - broadcast( shared_ptr( new ChunkTilesUpdatePacket(pos.x, pos.z, changedTiles, (byte)changes, level) ) ); + broadcast(std::make_shared(pos.x, pos.z, changedTiles, static_cast(changes), level)); for (int i = 0; i < changes; i++) { int x = pos.x * 16 + ((changedTiles[i] >> 12) & 15); @@ -334,10 +334,10 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) void PlayerChunkMap::PlayerChunk::broadcast(shared_ptr te) { - if (te != NULL) + if (te != nullptr) { shared_ptr p = te->getUpdatePacket(); - if (p != NULL) + if (p != nullptr) { broadcast(p); } @@ -375,7 +375,7 @@ void PlayerChunkMap::tick() { lastInhabitedUpdate = time; - for (int i = 0; i < knownChunks.size(); i++) + for (size_t i = 0; i < knownChunks.size(); i++) { PlayerChunk *chunk = knownChunks.at(i); @@ -492,8 +492,8 @@ void PlayerChunkMap::tickAddRequests(shared_ptr player) if( addRequests.size() ) { // Find the nearest chunk request to the player - int px = (int)player->x; - int pz = (int)player->z; + int px = static_cast(player->x); + int pz = static_cast(player->z); int minDistSq = -1; auto itNearest = addRequests.end(); @@ -527,7 +527,7 @@ void PlayerChunkMap::broadcastTileUpdate(shared_ptr packet, int x, int y int xc = x >> 4; int zc = z >> 4; PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) + if (chunk != nullptr) { chunk->broadcast(packet); } @@ -538,7 +538,7 @@ void PlayerChunkMap::tileChanged(int x, int y, int z) int xc = x >> 4; int zc = z >> 4; PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) + if (chunk != nullptr) { chunk->tileChanged(x & 15, y, z & 15); } @@ -559,7 +559,7 @@ void PlayerChunkMap::prioritiseTileChanges(int x, int y, int z) int xc = x >> 4; int zc = z >> 4; PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) + if (chunk != nullptr) { chunk->prioritiseTileChanges(); } @@ -569,8 +569,8 @@ void PlayerChunkMap::add(shared_ptr player) { static int direction[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, {0, -1} }; - int xc = (int) player->x >> 4; - int zc = (int) player->z >> 4; + int xc = static_cast(player->x) >> 4; + int zc = static_cast(player->z) >> 4; player->lastMoveX = player->x; player->lastMoveZ = player->z; @@ -660,7 +660,7 @@ void PlayerChunkMap::add(shared_ptr player) } // CraftBukkit end - player->connection->send( shared_ptr( new ChunkVisibilityAreaPacket(minX, maxX, minZ, maxZ) ) ); + player->connection->send(std::make_shared(minX, maxX, minZ, maxZ)); #ifdef _LARGE_WORLDS getLevel()->cache->dontDrop(xc,zc); @@ -672,14 +672,14 @@ void PlayerChunkMap::add(shared_ptr player) void PlayerChunkMap::remove(shared_ptr player) { - int xc = ((int) player->lastMoveX) >> 4; - int zc = ((int) player->lastMoveZ) >> 4; + int xc = static_cast(player->lastMoveX) >> 4; + int zc = static_cast(player->lastMoveZ) >> 4; for (int x = xc - radius; x <= xc + radius; x++) for (int z = zc - radius; z <= zc + radius; z++) { PlayerChunk *playerChunk = getChunk(x, z, false); - if (playerChunk != NULL) playerChunk->remove(player); + if (playerChunk != nullptr) playerChunk->remove(player); } auto it = find(players.begin(), players.end(), player); @@ -715,16 +715,16 @@ bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) // need to be created, so that we aren't creating potentially 20 chunks per player per tick void PlayerChunkMap::move(shared_ptr player) { - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; + int xc = static_cast(player->x) >> 4; + int zc = static_cast(player->z) >> 4; double _xd = player->lastMoveX - player->x; double _zd = player->lastMoveZ - player->z; double dist = _xd * _xd + _zd * _zd; if (dist < 8 * 8) return; - int last_xc = ((int) player->lastMoveX) >> 4; - int last_zc = ((int) player->lastMoveZ) >> 4; + int last_xc = static_cast(player->lastMoveX) >> 4; + int last_zc = static_cast(player->lastMoveZ) >> 4; int xd = xc - last_xc; int zd = zc - last_zc; @@ -759,7 +759,7 @@ bool PlayerChunkMap::isPlayerIn(shared_ptr player, int xChunk, int { PlayerChunk *chunk = getChunk(xChunk, zChunk, false); - if(chunk == NULL) + if(chunk == nullptr) { return false; } @@ -770,7 +770,7 @@ bool PlayerChunkMap::isPlayerIn(shared_ptr player, int xChunk, int return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); } - //return chunk == NULL ? false : chunk->players->contains(player) && !player->chunksToSend->contains(chunk->pos); + //return chunk == nullptr ? false : chunk->players->contains(player) && !player->chunksToSend->contains(chunk->pos); } int PlayerChunkMap::convertChunkRangeToBlock(int radius) @@ -784,13 +784,13 @@ void PlayerChunkMap::setRadius(int newRadius) if( radius != newRadius ) { PlayerList* players = level->getServer()->getPlayerList(); - for( int i = 0;i < players->players.size();i += 1 ) + for( size_t i = 0;i < players->players.size();i += 1 ) { shared_ptr player = players->players[i]; if( player->level == level ) { - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; + int xc = static_cast(player->x) >> 4; + int zc = static_cast(player->z) >> 4; for (int x = xc - newRadius; x <= xc + newRadius; x++) for (int z = zc - newRadius; z <= zc + newRadius; z++) diff --git a/Minecraft.Client/PlayerCloudParticle.cpp b/Minecraft.Client/PlayerCloudParticle.cpp index 6976fbab9..476803a33 100644 --- a/Minecraft.Client/PlayerCloudParticle.cpp +++ b/Minecraft.Client/PlayerCloudParticle.cpp @@ -15,12 +15,12 @@ PlayerCloudParticle::PlayerCloudParticle(Level *level, double x, double y, doubl yd += ya; zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); + rCol = gCol = bCol = 1 - static_cast(Math::random() * 0.3f); size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.3)); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.3)); lifetime *= scale; noPhysics = false; } @@ -50,7 +50,7 @@ void PlayerCloudParticle::tick() yd *= 0.96f; zd *= 0.96f; shared_ptr p = level->getNearestPlayer(shared_from_this(), 2); - if (p != NULL) + if (p != nullptr) { if (y > p->bb->y0) { diff --git a/Minecraft.Client/PlayerConnection.cpp b/Minecraft.Client/PlayerConnection.cpp index 9404a5d68..6319b660e 100644 --- a/Minecraft.Client/PlayerConnection.cpp +++ b/Minecraft.Client/PlayerConnection.cpp @@ -34,9 +34,26 @@ // 4J Added #include "..\Minecraft.World\net.minecraft.world.item.crafting.h" #include "Options.h" +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include "..\Minecraft.Server\ServerLogManager.h" +#endif + +namespace +{ + // Anti-cheat thresholds. Keep server-side checks authoritative even in host mode. + // Base max squared displacement allowed per move packet before speed flags trigger. + const double kMoveBaseAllowanceSq = 100.0; + // Extra squared displacement allowance derived from current server-side velocity. + const double kMoveVelocityAllowanceScale = 100.0; + // Max squared distance for interact/attack when the target is visible (normal reach). + const double kInteractReachSq = 6.0 * 6.0; + // Stricter max squared distance used when LOS is blocked to reduce wall-hit abuse. + const double kInteractBlockedReachSq = 3.0 * 3.0; +} Random PlayerConnection::random; + PlayerConnection::PlayerConnection(MinecraftServer *server, Connection *connection, shared_ptr player) { // 4J - added initialisers @@ -66,6 +83,13 @@ PlayerConnection::PlayerConnection(MinecraftServer *server, Connection *connecti m_offlineXUID = INVALID_XUID; m_onlineXUID = INVALID_XUID; m_bHasClientTickedOnce = false; + m_logSmallId = 0; + + // Cache the first valid transport smallId because disconnect teardown can clear it before the server logger runs. + if (this->connection != NULL && this->connection->getSocket() != NULL) + { + m_logSmallId = this->connection->getSocket()->getSmallId(); + } setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); } @@ -76,6 +100,17 @@ PlayerConnection::~PlayerConnection() DeleteCriticalSection(&done_cs); } +unsigned char PlayerConnection::getLogSmallId() +{ + // Fall back to the live socket only while the cached value is still empty. + if (m_logSmallId == 0 && connection != NULL && connection->getSocket() != NULL) + { + m_logSmallId = connection->getSocket()->getSmallId(); + } + + return m_logSmallId; +} + void PlayerConnection::tick() { if( done ) return; @@ -96,7 +131,7 @@ void PlayerConnection::tick() lastKeepAliveTick = tickCount; lastKeepAliveTime = System::nanoTime() / 1000000; lastKeepAliveId = random.nextInt(); - send( shared_ptr( new KeepAlivePacket(lastKeepAliveId) ) ); + send(std::make_shared(lastKeepAliveId)); } if (chatSpamTickCount > 0) @@ -118,22 +153,29 @@ void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) return; } +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnPlayerDisconnected( + getLogSmallId(), + (player != NULL) ? player->name : std::wstring(), + reason, + true); +#endif app.DebugPrintf("PlayerConnection disconect reason: %d\n", reason ); player->disconnect(); // 4J Stu - Need to remove the player from the receiving list before their socket is NULLed so that we can find another player on their system server->getPlayers()->removePlayerFromReceiving( player ); - send( shared_ptr( new DisconnectPacket(reason) )); + send(std::make_shared(reason)); connection->sendAndQuit(); // 4J-PB - removed, since it needs to be localised in the language the client is in //server->players->broadcastAll( shared_ptr( new ChatPacket(L"�e" + player->name + L" left the game.") ) ); if(getWasKicked()) { - server->getPlayers()->broadcastAll( shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); + server->getPlayers()->broadcastAll(std::make_shared(player->name, ChatPacket::e_ChatPlayerKickedFromGame)); } else { - server->getPlayers()->broadcastAll( shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); + server->getPlayers()->broadcastAll(std::make_shared(player->name, ChatPacket::e_ChatPlayerLeftGame)); } server->getPlayers()->remove(player); @@ -166,7 +208,7 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) if (synched) { - if (player->riding != NULL) + if (player->riding != nullptr) { float yRotT = player->yRot; @@ -187,7 +229,7 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) player->doTick(false); player->ySlideOffset = 0; player->absMoveTo(xt, yt, zt, yRotT, xRotT); - if (player->riding != NULL) player->riding->positionRider(); + if (player->riding != nullptr) player->riding->positionRider(); server->getPlayers()->move(player); // player may have been kicked off the mount during the tick, so @@ -197,7 +239,7 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) yLastOk = player->y; zLastOk = player->z; } - ((Level *)level)->tick(player); + static_cast(level)->tick(player); return; } @@ -206,7 +248,7 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) { player->doTick(false); player->absMoveTo(xLastOk, yLastOk, zLastOk, player->yRot, player->xRot); - ((Level *)level)->tick(player); + static_cast(level)->tick(player); return; } @@ -271,16 +313,19 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) double dist = xDist * xDist + yDist * yDist + zDist * zDist; - // 4J-PB - removing this one for now - /*if (dist > 100.0f) + // Anti-cheat: reject movement packets that exceed server-authoritative bounds. + double velocitySq = player->xd * player->xd + player->yd * player->yd + player->zd * player->zd; + double maxAllowedSq = kMoveBaseAllowanceSq + (velocitySq * kMoveVelocityAllowanceScale); + if (player->isAllowedToFly() || player->gameMode->isCreative()) { - // logger.warning(player->name + " moved too quickly!"); - disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); - // System.out.println("Moved too quickly at " + xt + ", " + yt + ", " + zt); - // teleport(player->x, player->y, player->z, player->yRot, player->xRot); - return; + // Creative / flight-allowed players can move farther legitimately per tick. + maxAllowedSq *= 1.5; + } + if (dist > maxAllowedSq) + { + disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); + return; } - */ float r = 1 / 16.0f; bool oldOk = level->getCubes(player, player->bb->copy()->shrink(r, r, r))->empty(); @@ -308,8 +353,8 @@ void PlayerConnection::handleMovePlayer(shared_ptr packet) xDist = xt - player->x; yDist = yt - player->y; - // 4J-PB - line below will always be true! - if (yDist > -0.5 || yDist < 0.5) + // Clamp tiny Y drift noise to reduce false positives. + if (yDist > -0.5 && yDist < 0.5) { yDist = 0; } @@ -378,7 +423,7 @@ void PlayerConnection::teleport(double x, double y, double z, float yRot, float player->absMoveTo(x, y, z, yRot, xRot); // 4J - note that 1.62 is added to the height here as the client connection that receives this will presume it represents y + heightOffset at that end // This is different to the way that height is sent back to the server, where it represents the bottom of the player bounding volume - if(sendPacket) player->connection->send( shared_ptr( new MovePlayerPacket::PosRot(x, y + 1.62f, y, z, yRot, xRot, false, false) ) ); + if(sendPacket) player->connection->send(std::make_shared(x, y + 1.62f, y, z, yRot, xRot, false, false)); } void PlayerConnection::handlePlayerAction(shared_ptr packet) @@ -430,20 +475,21 @@ void PlayerConnection::handlePlayerAction(shared_ptr packet) if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) { - if (true) player->gameMode->startDestroyBlock(x, y, z, packet->face); // 4J - condition was !server->isUnderSpawnProtection(level, x, y, z, player) (from Java 1.6.4) but putting back to old behaviour - else player->connection->send( shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + // Anti-cheat: validate spawn protection on the server for mining start. + if (!server->isUnderSpawnProtection(level, x, y, z, player)) player->gameMode->startDestroyBlock(x, y, z, packet->face); + else player->connection->send(std::make_shared(x, y, z, level)); } else if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) { player->gameMode->stopDestroyBlock(x, y, z); server->getPlayers()->prioritiseTileChanges(x, y, z, level->dimension->id); // 4J added - make sure that the update packets for this get prioritised over other general world updates - if (level->getTile(x, y, z) != 0) player->connection->send( shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + if (level->getTile(x, y, z) != 0) player->connection->send(std::make_shared(x, y, z, level)); } else if (packet->action == PlayerActionPacket::ABORT_DESTROY_BLOCK) { player->gameMode->abortDestroyBlock(x, y, z); - if (level->getTile(x, y, z) != 0) player->connection->send(shared_ptr( new TileUpdatePacket(x, y, z, level))); + if (level->getTile(x, y, z) != 0) player->connection->send(std::make_shared(x, y, z, level)); } } @@ -458,18 +504,17 @@ void PlayerConnection::handleUseItem(shared_ptr packet) int face = packet->getFace(); player->resetLastActionTime(); - // 4J Stu - We don't have ops, so just use the levels setting - bool canEditSpawn = level->canEditSpawn; // = level->dimension->id != 0 || server->players->isOp(player->name); if (packet->getFace() == 255) { - if (item == NULL) return; + if (item == nullptr) return; player->gameMode->useItem(player, level, item); } else if ((packet->getY() < server->getMaxBuildHeight() - 1) || (packet->getFace() != Facing::UP && packet->getY() < server->getMaxBuildHeight())) { if (synched && player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) < 8 * 8) { - if (true) // 4J - condition was !server->isUnderSpawnProtection(level, x, y, z, player) (from java 1.6.4) but putting back to old behaviour + // Anti-cheat: block placement/use must pass server-side spawn protection. + if (!server->isUnderSpawnProtection(level, x, y, z, player)) { player->gameMode->useItemOn(player, level, item, x, y, z, face, packet->getClickX(), packet->getClickY(), packet->getClickZ()); } @@ -486,7 +531,7 @@ void PlayerConnection::handleUseItem(shared_ptr packet) if (informClient) { - player->connection->send( shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + player->connection->send(std::make_shared(x, y, z, level)); if (face == 0) y--; if (face == 1) y++; @@ -502,7 +547,7 @@ void PlayerConnection::handleUseItem(shared_ptr packet) // isn't what it is expecting. if( level->getTile(x,y,z) != Tile::pistonMovingPiece_Id ) { - player->connection->send( shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + player->connection->send(std::make_shared(x, y, z, level)); } } @@ -510,17 +555,17 @@ void PlayerConnection::handleUseItem(shared_ptr packet) item = player->inventory->getSelected(); bool forceClientUpdate = false; - if(item != NULL && packet->getItem() == NULL) + if(item != nullptr && packet->getItem() == nullptr) { forceClientUpdate = true; } - if (item != NULL && item->count == 0) + if (item != nullptr && item->count == 0) { player->inventory->items[player->inventory->selected] = nullptr; item = nullptr; } - if (item == NULL || item->getUseDuration() == 0) + if (item == nullptr || item->getUseDuration() == 0) { player->ignoreSlotUpdateHack = true; player->inventory->items[player->inventory->selected] = ItemInstance::clone(player->inventory->items[player->inventory->selected]); @@ -530,7 +575,7 @@ void PlayerConnection::handleUseItem(shared_ptr packet) if (forceClientUpdate || !ItemInstance::matches(player->inventory->getSelected(), packet->getItem())) { - send( shared_ptr( new ContainerSetSlotPacket(player->containerMenu->containerId, s->index, player->inventory->getSelected()) ) ); + send(std::make_shared(player->containerMenu->containerId, s->index, player->inventory->getSelected())); } } } @@ -538,17 +583,28 @@ void PlayerConnection::handleUseItem(shared_ptr packet) void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) { EnterCriticalSection(&done_cs); - if( done ) return; + if( done ) + { + LeaveCriticalSection(&done_cs); + return; + } +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + ServerRuntime::ServerLogManager::OnPlayerDisconnected( + getLogSmallId(), + (player != NULL) ? player->name : std::wstring(), + reason, + false); +#endif // 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( new ChatPacket(L"�e" + player->name + L" left the game.") ) ); if(getWasKicked()) { - server->getPlayers()->broadcastAll( shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); + server->getPlayers()->broadcastAll(std::make_shared(player->name, ChatPacket::e_ChatPlayerKickedFromGame)); } else { - server->getPlayers()->broadcastAll( shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); + server->getPlayers()->broadcastAll(std::make_shared(player->name, ChatPacket::e_ChatPlayerLeftGame)); } server->getPlayers()->remove(player); done = true; @@ -563,7 +619,7 @@ void PlayerConnection::onUnhandledPacket(shared_ptr packet) void PlayerConnection::send(shared_ptr packet) { - if( connection->getSocket() != NULL ) + if( connection->getSocket() != nullptr ) { if( !server->getPlayers()->canReceiveAllPackets( player ) ) { @@ -581,7 +637,7 @@ void PlayerConnection::send(shared_ptr packet) // 4J Added void PlayerConnection::queueSend(shared_ptr packet) { - if( connection->getSocket() != NULL ) + if( connection->getSocket() != nullptr ) { if( !server->getPlayers()->canReceiveAllPackets( player ) ) { @@ -675,7 +731,7 @@ void PlayerConnection::handlePlayerCommand(shared_ptr packe else if (packet->action == PlayerCommandPacket::RIDING_JUMP) { // currently only supported by horses... - if ( (player->riding != NULL) && player->riding->GetType() == eTYPE_HORSE) + if ( (player->riding != nullptr) && player->riding->GetType() == eTYPE_HORSE) { dynamic_pointer_cast(player->riding)->onPlayerJump(packet->data); } @@ -683,7 +739,7 @@ void PlayerConnection::handlePlayerCommand(shared_ptr packe else if (packet->action == PlayerCommandPacket::OPEN_INVENTORY) { // also only supported by horses... - if ( (player->riding != NULL) && player->riding->instanceof(eTYPE_HORSE) ) + if ( (player->riding != nullptr) && player->riding->instanceof(eTYPE_HORSE) ) { dynamic_pointer_cast(player->riding)->openInventory(player); } @@ -742,17 +798,16 @@ void PlayerConnection::handleInteract(shared_ptr packet) // 4J Stu - If the client says that we hit something, then agree with it. The canSee can fail here as it checks // a ray from head->head, but we may actually be looking at a different part of the entity that can be seen // even though the ray is blocked. - if (target != NULL) // && player->canSee(target) && player->distanceToSqr(target) < 6 * 6) + if (target != nullptr) { - //boole canSee = player->canSee(target); - //double maxDist = 6 * 6; - //if (!canSee) - //{ - // maxDist = 3 * 3; - //} + // Anti-cheat: enforce reach and LOS on the server to reject forged hits. + bool canSeeTarget = player->canSee(target); + double maxDistSq = canSeeTarget ? kInteractReachSq : kInteractBlockedReachSq; + if (player->distanceToSqr(target) > maxDistSq) + { + return; + } - //if (player->distanceToSqr(target) < maxDist) - //{ if (packet->action == InteractPacket::INTERACT) { player->interact(target); @@ -767,7 +822,6 @@ void PlayerConnection::handleInteract(shared_ptr packet) } player->attack(target); } - //} } } @@ -787,13 +841,13 @@ void PlayerConnection::handleTexture(shared_ptr packet) #ifndef _CONTENT_PACKAGE wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); #endif - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); if(dwBytes!=0) { - send( shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); + send(std::make_shared(packet->textureName, pbData, dwBytes)); } else { @@ -821,7 +875,7 @@ void PlayerConnection::handleTextureAndGeometry(shared_ptrtextureName.c_str()); #endif - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwTextureBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwTextureBytes); DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); @@ -833,11 +887,11 @@ void PlayerConnection::handleTextureAndGeometry(shared_ptrgetAdditionalBoxesCount()!=0) { - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); + send(std::make_shared(packet->textureName, pbData, dwTextureBytes, pDLCSkinFile)); } else { - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes) ) ); + send(std::make_shared(packet->textureName, pbData, dwTextureBytes)); } } else @@ -846,7 +900,7 @@ void PlayerConnection::handleTextureAndGeometry(shared_ptr *pvSkinBoxes = app.GetAdditionalSkinBoxes(packet->dwSkinID); unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); - send( shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pvSkinBoxes,uiAnimOverrideBitmask) ) ); + send(std::make_shared(packet->textureName, pbData, dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask)); } } else @@ -885,13 +939,13 @@ void PlayerConnection::handleTextureReceived(const wstring &textureName) auto it = find(m_texturesRequested.begin(), m_texturesRequested.end(), textureName); if( it != m_texturesRequested.end() ) { - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwBytes=0; app.GetMemFileDetails(textureName,&pbData,&dwBytes); if(dwBytes!=0) { - send( shared_ptr( new TexturePacket(textureName,pbData,dwBytes) ) ); + send(std::make_shared(textureName, pbData, dwBytes)); m_texturesRequested.erase(it); } } @@ -903,7 +957,7 @@ void PlayerConnection::handleTextureAndGeometryReceived(const wstring &textureNa auto it = find(m_texturesRequested.begin(), m_texturesRequested.end(), textureName); if( it != m_texturesRequested.end() ) { - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwTextureBytes=0; app.GetMemFileDetails(textureName,&pbData,&dwTextureBytes); DLCSkinFile *pDLCSkinFile=app.m_dlcManager.getSkinFile(textureName); @@ -912,7 +966,7 @@ void PlayerConnection::handleTextureAndGeometryReceived(const wstring &textureNa { if(pDLCSkinFile && (pDLCSkinFile->getAdditionalBoxesCount()!=0)) { - send( shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); + send(std::make_shared(textureName, pbData, dwTextureBytes, pDLCSkinFile)); } else { @@ -921,7 +975,7 @@ void PlayerConnection::handleTextureAndGeometryReceived(const wstring &textureNa vector *pvSkinBoxes = app.GetAdditionalSkinBoxes(dwSkinID); unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(dwSkinID); - send( shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask) ) ); + send(std::make_shared(textureName, pbData, dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask)); } m_texturesRequested.erase(it); } @@ -948,20 +1002,25 @@ void PlayerConnection::handleTextureChange(shared_ptr packe } if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) { - if( server->connection->addPendingTextureRequest(packet->path)) - { + if (server->connection->addPendingTextureRequest(packet->path)) + { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",packet->path.c_str(), player->name.c_str()); + wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n", packet->path.c_str(), player->name.c_str()); #endif - send(shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); - } - } + send(std::make_shared( + packet->path, + nullptr, + static_cast(0) + )); + + } + } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); + app.AddMemoryTextureFile(packet->path,nullptr,0); } - server->getPlayers()->broadcastAll( shared_ptr( new TextureChangePacket(player,packet->action,packet->path) ), player->dimension ); + server->getPlayers()->broadcastAll(std::make_shared(player, packet->action, packet->path), player->dimension ); } void PlayerConnection::handleTextureAndGeometryChange(shared_ptr packet) @@ -980,13 +1039,16 @@ void PlayerConnection::handleTextureAndGeometryChange(shared_ptrpath.c_str(), player->name.c_str()); #endif - send(shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); + send(std::make_shared( + packet->path, + nullptr, + static_cast(0))); } } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); + app.AddMemoryTextureFile(packet->path,nullptr,0); player->setCustomSkin(packet->dwSkinID); @@ -994,7 +1056,7 @@ void PlayerConnection::handleTextureAndGeometryChange(shared_ptrdwSkinID,) //DebugBreak(); } - server->getPlayers()->broadcastAll( shared_ptr( new TextureAndGeometryChangePacket(player,packet->path) ), player->dimension ); + server->getPlayers()->broadcastAll(std::make_shared(player, packet->path), player->dimension ); } void PlayerConnection::handleServerSettingsChanged(shared_ptr packet) @@ -1004,7 +1066,7 @@ void PlayerConnection::handleServerSettingsChanged(shared_ptrIsHost()) || player->isModerator()) + if( (networkPlayer != nullptr && networkPlayer->IsHost()) || player->isModerator()) { app.SetGameHostOption(eGameHostOption_FireSpreads, app.GetGameHostOption(packet->data,eGameHostOption_FireSpreads)); app.SetGameHostOption(eGameHostOption_TNT, app.GetGameHostOption(packet->data,eGameHostOption_TNT)); @@ -1016,7 +1078,7 @@ void PlayerConnection::handleServerSettingsChanged(shared_ptrdata, eGameHostOption_DoDaylightCycle)); app.SetGameHostOption(eGameHostOption_NaturalRegeneration, app.GetGameHostOption(packet->data, eGameHostOption_NaturalRegeneration)); - server->getPlayers()->broadcastAll( shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS,app.GetGameHostOption(eGameHostOption_All) ) ) ); + server->getPlayers()->broadcastAll(std::make_shared(ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, app.GetGameHostOption(eGameHostOption_All))); // Update the QoS data g_NetworkManager.UpdateAndSetGameSessionData(); @@ -1027,7 +1089,7 @@ void PlayerConnection::handleServerSettingsChanged(shared_ptr packet) { INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) + if( (networkPlayer != nullptr && networkPlayer->IsHost()) || player->isModerator()) { server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); } @@ -1096,9 +1158,9 @@ void PlayerConnection::handleContainerSetSlot(shared_ptr if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY && packet->slot >= 36 && packet->slot < 36 + 9) { shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) + if (packet->item != nullptr) { - if (lastItem == NULL || lastItem->count < packet->item->count) + if (lastItem == nullptr || lastItem->count < packet->item->count) { packet->item->popTime = Inventory::POP_TIME_DURATION; } @@ -1131,7 +1193,7 @@ void PlayerConnection::handleContainerClick(shared_ptr pac if (ItemInstance::matches(packet->item, clicked)) { // Yep, you sure did click what you claimed to click! - player->connection->send( shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) ) ); + player->connection->send(std::make_shared(packet->containerId, packet->uid, true)); player->ignoreSlotUpdateHack = true; player->containerMenu->broadcastChanges(); player->broadcastCarriedItem(); @@ -1141,7 +1203,7 @@ void PlayerConnection::handleContainerClick(shared_ptr pac { // No, you clicked the wrong thing! expectedAcks[player->containerMenu->containerId] = packet->uid; - player->connection->send( shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, false) ) ); + player->connection->send(std::make_shared(packet->containerId, packet->uid, false)); player->containerMenu->setSynched(player, false); vector > items; @@ -1174,13 +1236,13 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptrslotNum < 0; shared_ptr item = packet->item; - if(item != NULL && item->id == Item::map_Id) + if(item != nullptr && item->id == Item::map_Id) { int mapScale = 3; #ifdef _LARGE_WORLDS int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int centreXC = static_cast(Math::round(player->x / scale) * scale); + int centreZC = static_cast(Math::round(player->z / scale) * scale); #else // 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 int centreXC = 0; @@ -1194,9 +1256,9 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptrgetAuxValue()); std::wstring id = wstring(buf); - if( data == NULL ) + if( data == nullptr ) { - data = shared_ptr( new MapItemSavedData(id) ); + data = std::make_shared(id); } player->level->setSavedData(id, (shared_ptr ) data); @@ -1204,17 +1266,17 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptrx = centreXC; data->z = centreZC; - data->dimension = (byte) player->level->dimension->id; + data->dimension = static_cast(player->level->dimension->id); data->setDirty(); } bool validSlot = (packet->slotNum >= InventoryMenu::CRAFT_SLOT_START && packet->slotNum < (InventoryMenu::USE_ROW_SLOT_START + Inventory::getSelectionSize())); - bool validItem = item == NULL || (item->id < Item::items.length && item->id >= 0 && Item::items[item->id] != NULL); - bool validData = item == NULL || (item->getAuxValue() >= 0 && item->count > 0 && item->count <= 64); + bool validItem = item == nullptr || (item->id < Item::items.length && item->id >= 0 && Item::items[item->id] != nullptr); + bool validData = item == nullptr || (item->getAuxValue() >= 0 && item->count > 0 && item->count <= 64); if (validSlot && validItem && validData) { - if (item == NULL) + if (item == nullptr) { player->inventoryMenu->setItem(packet->slotNum, nullptr); } @@ -1232,14 +1294,14 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptr dropped = player->drop(item); - if (dropped != NULL) + if (dropped != nullptr) { dropped->setShortLifeTime(); } } } - if( item != NULL && item->id == Item::map_Id ) + if( item != nullptr && item->id == Item::map_Id ) { // 4J Stu - Maps need to have their aux value update, so the client should always be assumed to be wrong // This is how the Java works, as the client also incorrectly predicts the auxvalue of the mapItem @@ -1273,7 +1335,7 @@ void PlayerConnection::handleSignUpdate(shared_ptr packet) { shared_ptr te = level->getTileEntity(packet->x, packet->y, packet->z); - if (dynamic_pointer_cast(te) != NULL) + if (dynamic_pointer_cast(te) != nullptr) { shared_ptr ste = dynamic_pointer_cast(te); if (!ste->isEditable() || ste->getPlayerWhoMayEdit() != player) @@ -1284,7 +1346,7 @@ void PlayerConnection::handleSignUpdate(shared_ptr packet) } // 4J-JEV: Changed to allow characters to display as a []. - if (dynamic_pointer_cast(te) != NULL) + if (dynamic_pointer_cast(te) != nullptr) { int x = packet->x; int y = packet->y; @@ -1307,7 +1369,7 @@ void PlayerConnection::handleKeepAlive(shared_ptr packet) { if (packet->id == lastKeepAliveId) { - int time = (int) (System::nanoTime() / 1000000 - lastKeepAliveTime); + int time = static_cast(System::nanoTime() / 1000000 - lastKeepAliveTime); player->latency = (player->latency * 3 + time) / 4; } } @@ -1317,20 +1379,20 @@ void PlayerConnection::handlePlayerInfo(shared_ptr packet) // Need to check that this player has permission to change each individual setting? INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator() ) + if( (networkPlayer != nullptr && networkPlayer->IsHost()) || player->isModerator() ) { shared_ptr serverPlayer; // Find the player being edited for(auto& checkingPlayer : server->getPlayers()->players) { - if(checkingPlayer->connection->getNetworkPlayer() != NULL && checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == packet->m_networkSmallId) + if(checkingPlayer->connection->getNetworkPlayer() != nullptr && checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == packet->m_networkSmallId) { serverPlayer = checkingPlayer; break; } } - if(serverPlayer != NULL) + if(serverPlayer != nullptr) { unsigned int origPrivs = serverPlayer->getAllPlayerGamePrivileges(); @@ -1347,7 +1409,7 @@ void PlayerConnection::handlePlayerInfo(shared_ptr packet) #endif serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ); serverPlayer->gameMode->setGameModeForPlayer(gameType); - serverPlayer->connection->send( shared_ptr( new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, gameType->getId()) )); + serverPlayer->connection->send(std::make_shared(GameEventPacket::CHANGE_GAME_MODE, gameType->getId())); } else { @@ -1399,7 +1461,7 @@ void PlayerConnection::handlePlayerInfo(shared_ptr packet) } } - server->getPlayers()->broadcastAll( shared_ptr( new PlayerInfoPacket( serverPlayer ) ) ); + server->getPlayers()->broadcastAll(std::make_shared(serverPlayer)); } } } @@ -1483,7 +1545,7 @@ void PlayerConnection::handleCustomPayload(shared_ptr custo AbstractContainerMenu *menu = player->containerMenu; if (dynamic_cast(menu)) { - ((MerchantMenu *) menu)->setSelectionHint(selection); + static_cast(menu)->setSelectionHint(selection); } } else if (CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET.compare(customPayloadPacket->identifier) == 0) @@ -1504,7 +1566,7 @@ void PlayerConnection::handleCustomPayload(shared_ptr custo shared_ptr tileEntity = player->level->getTileEntity(x, y, z); shared_ptr cbe = dynamic_pointer_cast(tileEntity); - if (tileEntity != NULL && cbe != NULL) + if (tileEntity != nullptr && cbe != nullptr) { cbe->setCommand(command); player->level->sendTileUpdated(x, y, z); @@ -1518,14 +1580,14 @@ void PlayerConnection::handleCustomPayload(shared_ptr custo } else if (CustomPayloadPacket::SET_BEACON_PACKET.compare(customPayloadPacket->identifier) == 0) { - if ( dynamic_cast( player->containerMenu) != NULL) + if ( dynamic_cast( player->containerMenu) != nullptr) { ByteArrayInputStream bais(customPayloadPacket->data); DataInputStream input(&bais); int primary = input.readInt(); int secondary = input.readInt(); - BeaconMenu *beaconMenu = (BeaconMenu *) player->containerMenu; + BeaconMenu *beaconMenu = static_cast(player->containerMenu); Slot *slot = beaconMenu->getSlot(0); if (slot->hasItem()) { @@ -1542,7 +1604,7 @@ void PlayerConnection::handleCustomPayload(shared_ptr custo AnvilMenu *menu = dynamic_cast( player->containerMenu); if (menu) { - if (customPayloadPacket->data.data == NULL || customPayloadPacket->data.length < 1) + if (customPayloadPacket->data.data == nullptr || customPayloadPacket->data.length < 1) { menu->setItemName(L""); } @@ -1580,13 +1642,13 @@ void PlayerConnection::handleCraftItem(shared_ptr packet) if(iRecipe == -1) return; + int recipeCount = (int)Recipes::getInstance()->getRecipies()->size(); + if(iRecipe < 0 || iRecipe >= recipeCount) + return; + Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); shared_ptr pTempItemInst=pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); - size_t recipeCount = Recipes::getInstance()->getRecipies()->size(); - if (iRecipe < 0 || iRecipe >= (int)recipeCount) - return; - if(app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<onCraftedBy(player->level, dynamic_pointer_cast( player->shared_from_this() ), pTempItemInst->count ); @@ -1598,7 +1660,7 @@ void PlayerConnection::handleCraftItem(shared_ptr packet) } else if (pTempItemInst->id == Item::fireworksCharge_Id || pTempItemInst->id == Item::fireworks_Id) { - CraftingMenu *menu = (CraftingMenu *)player->containerMenu; + CraftingMenu *menu = static_cast(player->containerMenu); player->openFireworks(menu->getX(), menu->getY(), menu->getZ() ); } else @@ -1606,7 +1668,7 @@ void PlayerConnection::handleCraftItem(shared_ptr packet) Recipy::INGREDIENTS_REQUIRED &req = pRecipeIngredientsRequired[iRecipe]; - if (req.iType == RECIPE_TYPE_3x3 && dynamic_cast(player->containerMenu) == NULL) + if (req.iType == RECIPE_TYPE_3x3 && dynamic_cast(player->containerMenu) == nullptr) { server->warn(L"Player " + player->getName() + L" tried to craft a 3x3 recipe without a crafting bench"); return; @@ -1641,12 +1703,12 @@ void PlayerConnection::handleCraftItem(shared_ptr packet) } // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when crafting Cake - if (ingItemInst != NULL) + if (ingItemInst != nullptr) { if (ingItemInst->getItem()->hasCraftingRemainingItem()) { // replace item with remaining result - player->inventory->add( shared_ptr( new ItemInstance(ingItemInst->getItem()->getCraftingRemainingItem()) ) ); + player->inventory->add(std::make_shared(ingItemInst->getItem()->getCraftingRemainingItem())); } } @@ -1707,7 +1769,7 @@ void PlayerConnection::handleTradeItem(shared_ptr packet) { if (player->containerMenu->containerId == packet->containerId) { - MerchantMenu *menu = (MerchantMenu *)player->containerMenu; + MerchantMenu *menu = static_cast(player->containerMenu); MerchantRecipeList *offers = menu->getMerchant()->getOffers(player); @@ -1725,7 +1787,7 @@ void PlayerConnection::handleTradeItem(shared_ptr packet) int buyAMatches = player->inventory->countMatches(buyAItem); int buyBMatches = player->inventory->countMatches(buyBItem); - if( (buyAItem != NULL && buyAMatches >= buyAItem->count) && (buyBItem == NULL || buyBMatches >= buyBItem->count) ) + if( (buyAItem != nullptr && buyAMatches >= buyAItem->count) && (buyBItem == nullptr || buyBMatches >= buyBItem->count) ) { menu->getMerchant()->notifyTrade(activeRecipe); @@ -1759,13 +1821,13 @@ void PlayerConnection::handleTradeItem(shared_ptr packet) INetworkPlayer *PlayerConnection::getNetworkPlayer() { - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; + if( connection != nullptr && connection->getSocket() != nullptr) return connection->getSocket()->getPlayer(); + else return nullptr; } bool PlayerConnection::isLocal() { - if( connection->getSocket() == NULL ) + if( connection->getSocket() == nullptr ) { return false; } @@ -1778,7 +1840,7 @@ bool PlayerConnection::isLocal() bool PlayerConnection::isGuest() { - if( connection->getSocket() == NULL ) + if( connection->getSocket() == nullptr ) { return false; } @@ -1786,7 +1848,7 @@ bool PlayerConnection::isGuest() { INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); bool isGuest = false; - if(networkPlayer != NULL) + if(networkPlayer != nullptr) { isGuest = networkPlayer->IsGuest() == TRUE; } diff --git a/Minecraft.Client/PlayerConnection.h b/Minecraft.Client/PlayerConnection.h index ff6093a34..0284bc6a2 100644 --- a/Minecraft.Client/PlayerConnection.h +++ b/Minecraft.Client/PlayerConnection.h @@ -37,6 +37,7 @@ private: int dropSpamTickCount; bool m_bHasClientTickedOnce; + unsigned char m_logSmallId; public: PlayerConnection(MinecraftServer *server, Connection *connection, shared_ptr player); @@ -45,6 +46,10 @@ public: void disconnect(DisconnectPacket::eDisconnectReason reason); private: + /** + * Returns the stable network smallId used by dedicated-server logging and refreshes it from the live socket when possible + */ + unsigned char getLogSmallId(); double xLastOk, yLastOk, zLastOk; bool synched; diff --git a/Minecraft.Client/PlayerList.cpp b/Minecraft.Client/PlayerList.cpp index 1742756ec..ba82ec6ac 100644 --- a/Minecraft.Client/PlayerList.cpp +++ b/Minecraft.Client/PlayerList.cpp @@ -19,6 +19,9 @@ #include "..\Minecraft.World\net.minecraft.network.packet.h" #include "..\Minecraft.World\net.minecraft.network.h" #include "Windows64\Windows64_Xuid.h" +#ifdef _WINDOWS64 +#include "Windows64\Network\WinsockNetLayer.h" +#endif #include "..\Minecraft.World\Pos.h" #include "..\Minecraft.World\ProgressListener.h" #include "..\Minecraft.World\HellRandomLevelSource.h" @@ -34,16 +37,21 @@ #include "Common\Network\Sony\NetworkPlayerSony.h" #endif +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include "..\Minecraft.Server\Access\Access.h" +extern bool g_Win64DedicatedServer; +#endif + // 4J - this class is fairly substantially altered as there didn't seem any point in porting code for banning, whitelisting, ops etc. PlayerList::PlayerList(MinecraftServer *server) { - playerIo = NULL; + playerIo = nullptr; this->server = server; sendAllPlayerInfoIn = 0; - overrideGameMode = NULL; + overrideGameMode = nullptr; allowCheatsForAllPlayers = false; #ifdef __PSVITA__ @@ -57,7 +65,7 @@ PlayerList::PlayerList(MinecraftServer *server) //int viewDistance = server->settings->getInt(L"view-distance", 10); int rawMax = server->settings->getInt(L"max-players", 8); - maxPlayers = (unsigned int)Mth::clamp(rawMax, 1, MINECRAFT_NET_MAX_PLAYERS); + maxPlayers = static_cast(Mth::clamp(rawMax, 1, MINECRAFT_NET_MAX_PLAYERS)); doWhiteList = false; InitializeCriticalSection(&m_kickPlayersCS); InitializeCriticalSection(&m_closePlayersCS); @@ -80,14 +88,14 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr { CompoundTag *playerTag = load(player); - bool newPlayer = playerTag == NULL; + bool newPlayer = playerTag == nullptr; player->setLevel(server->getLevel(player->dimension)); - player->gameMode->setLevel((ServerLevel *)player->level); + player->gameMode->setLevel(static_cast(player->level)); // Make sure these privileges are always turned off for the host player INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && networkPlayer->IsHost()) + if(networkPlayer != nullptr && networkPlayer->IsHost()) { player->enableAllPlayerPrivileges(true); player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST,1); @@ -97,18 +105,18 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr // PS3 networking library doesn't automatically assign PlayerUIDs to the network players for anything remote, so need to tell it what to set from the data in this packet now if( !g_NetworkManager.IsLocalGame() ) { - if( networkPlayer != NULL ) + if( networkPlayer != nullptr ) { ((NetworkPlayerSony *)networkPlayer)->SetUID( packet->m_onlineXuid ); } } #endif #ifdef _WINDOWS64 - if (networkPlayer != NULL) + if (networkPlayer != nullptr) { - NetworkPlayerXbox* nxp = (NetworkPlayerXbox*)networkPlayer; + NetworkPlayerXbox* nxp = static_cast(networkPlayer); IQNetPlayer* qnp = nxp->GetQNetPlayer(); - if (qnp != NULL) + if (qnp != nullptr) { if (!networkPlayer->IsLocal()) { @@ -143,9 +151,9 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr } } } - if (playerIndex >= (unsigned int)MINECRAFT_NET_MAX_PLAYERS) + if (playerIndex >= static_cast(MINECRAFT_NET_MAX_PLAYERS)) { - connection->send(shared_ptr(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull))); + connection->send(std::make_shared(DisconnectPacket::eDisconnect_ServerFull)); connection->sendAndQuit(); return false; } @@ -154,7 +162,7 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr player->setCustomCape( packet->m_playerCapeId ); // 4J-JEV: Moved this here so we can send player-model texture and geometry data. - shared_ptr playerConnection = shared_ptr(new PlayerConnection(server, connection, player)); + shared_ptr playerConnection = std::make_shared(server, connection, player); //player->connection = playerConnection; // Used to be assigned in PlayerConnection ctor but moved out so we can use shared_ptr if(newPlayer) @@ -162,35 +170,39 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr int mapScale = 3; #ifdef _LARGE_WORLDS int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int centreXC = static_cast(Math::round(player->x / scale) * scale); + int centreZC = static_cast(Math::round(player->z / scale) * scale); #else // 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 int centreXC = 0; int centreZC = 0; #endif // 4J Added - Give every player a map the first time they join a server - player->inventory->setItem( 9, shared_ptr( new ItemInstance(Item::map_Id, 1, level->getAuxValueForMap(player->getXuid(),0,centreXC, centreZC, mapScale ) ) ) ); - if(app.getGameRuleDefinitions() != NULL) + player->inventory->setItem( 9, std::make_shared(Item::map_Id, 1, level->getAuxValueForMap(player->getXuid(), 0, centreXC, centreZC, mapScale))); + if(app.getGameRuleDefinitions() != nullptr) { app.getGameRuleDefinitions()->postProcessPlayer(player); } } if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) - { - if( server->getConnection()->addPendingTextureRequest(player->customTextureUrl)) - { + { + if (server->getConnection()->addPendingTextureRequest(player->customTextureUrl)) + { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n", player->customTextureUrl.c_str(), player->name.c_str()); #endif - playerConnection->send(shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); + playerConnection->send(std::make_shared( + player->customTextureUrl, + nullptr, + static_cast(0))); + } } else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); + app.AddMemoryTextureFile(player->customTextureUrl,nullptr,0); } if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) @@ -200,13 +212,17 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr #ifndef _CONTENT_PACKAGE wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); #endif - playerConnection->send(shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); + playerConnection->send(std::make_shared( + player->customTextureUrl, + nullptr, + static_cast(0) + )); } } else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) { // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); + app.AddMemoryTextureFile(player->customTextureUrl2,nullptr,0); } player->setIsGuest( packet->m_isGuest ); @@ -237,22 +253,37 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr addPlayerToReceiving( player ); int maxPlayersForPacket = getMaxPlayers() > 255 ? 255 : getMaxPlayers(); - playerConnection->send( shared_ptr( new LoginPacket(L"", player->entityId, level->getLevelData()->getGenerator(), level->getSeed(), player->gameMode->getGameModeForPlayer()->getId(), - (byte) level->dimension->id, (byte) level->getMaxBuildHeight(), (byte) maxPlayersForPacket, - level->difficulty, TelemetryManager->GetMultiplayerInstanceID(), (BYTE)playerIndex, level->useNewSeaLevel(), player->getAllPlayerGamePrivileges(), - level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale() ) ) ); - playerConnection->send( shared_ptr( new SetSpawnPositionPacket(spawnPos->x, spawnPos->y, spawnPos->z) ) ); - playerConnection->send( shared_ptr( new PlayerAbilitiesPacket(&player->abilities)) ); - playerConnection->send( shared_ptr( new SetCarriedItemPacket(player->inventory->selected))); + + BYTE newSmallId = 0; + Socket *sock = connection->getSocket(); + INetworkPlayer *np = sock ? sock->getPlayer() : nullptr; + if (np) newSmallId = np->GetSmallId(); + app.DebugPrintf("RECONNECT: placeNewPlayer smallId=%d entityId=%d dim=%d\n", + newSmallId, player->entityId, level->dimension->id); + + playerConnection->send(std::make_shared(L"", player->entityId, level->getLevelData()->getGenerator(), + level->getSeed(), + player->gameMode->getGameModeForPlayer()->getId(), + static_cast(level->dimension->id), static_cast(level->getMaxBuildHeight()), + static_cast(maxPlayersForPacket), + level->difficulty, + TelemetryManager->GetMultiplayerInstanceID(), + static_cast(playerIndex), level->useNewSeaLevel(), + player->getAllPlayerGamePrivileges(), + level->getLevelData()->getXZSize(), + level->getLevelData()->getHellScale())); + playerConnection->send(std::make_shared(spawnPos->x, spawnPos->y, spawnPos->z)); + playerConnection->send(std::make_shared(&player->abilities)); + playerConnection->send(std::make_shared(player->inventory->selected)); delete spawnPos; - updateEntireScoreboard((ServerScoreboard *) level->getScoreboard(), player); + updateEntireScoreboard(reinterpret_cast(level->getScoreboard()), player); sendLevelInfo(player, level); // 4J-PB - removed, since it needs to be localised in the language the client is in //server->players->broadcastAll( shared_ptr( new ChatPacket(L"�e" + playerEntity->name + L" joined the game.") ) ); - broadcastAll( shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame) ) ); + broadcastAll(std::make_shared(player->name, ChatPacket::e_ChatPlayerJoinedGame)); MemSect(14); add(player); @@ -262,21 +293,21 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr playerConnection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); server->getConnection()->addPlayerConnection(playerConnection); - playerConnection->send( shared_ptr( new SetTimePacket(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)) ) ); + playerConnection->send(std::make_shared(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT))); auto activeEffects = player->getActiveEffects(); for(MobEffectInstance *effect : *player->getActiveEffects()) { - playerConnection->send(shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); + playerConnection->send(std::make_shared(player->entityId, effect)); } player->initMenu(); - if (playerTag != NULL && playerTag->contains(Entity::RIDING_TAG)) + if (playerTag != nullptr && playerTag->contains(Entity::RIDING_TAG)) { // this player has been saved with a mount tag shared_ptr mount = EntityIO::loadStatic(playerTag->getCompound(Entity::RIDING_TAG), level); - if (mount != NULL) + if (mount != nullptr) { mount->forcedLoading = true; level->addEntity(mount); @@ -316,7 +347,7 @@ void PlayerList::updateEntireScoreboard(ServerScoreboard *scoreboard, shared_ptr //{ // Objective objective = scoreboard->getDisplayObjective(slot); - // if (objective != NULL && !objectives->contains(objective)) + // if (objective != nullptr && !objectives->contains(objective)) // { // vector > *packets = scoreboard->getStartTrackingPackets(objective); @@ -339,10 +370,10 @@ void PlayerList::changeDimension(shared_ptr player, ServerLevel *f { ServerLevel *to = player->getLevel(); - if (from != NULL) from->getChunkMap()->remove(player); + if (from != nullptr) from->getChunkMap()->remove(player); to->getChunkMap()->add(player); - to->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + to->cache->create(static_cast(player->x) >> 4, static_cast(player->z) >> 4); } int PlayerList::getMaxRange() @@ -411,10 +442,10 @@ void PlayerList::validatePlayerSpawnPosition(shared_ptr player) delete levelSpawn; Pos *bedPosition = player->getRespawnPosition(); - if (bedPosition != NULL) + if (bedPosition != nullptr) { Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(player->dimension), bedPosition, spawnForced); - if (respawnPosition != NULL) + if (respawnPosition != nullptr) { player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); player->setRespawnPosition(bedPosition, spawnForced); @@ -435,7 +466,7 @@ void PlayerList::add(shared_ptr player) //broadcastAll(shared_ptr( new PlayerInfoPacket(player->name, true, 1000) ) ); if( player->connection->getNetworkPlayer() ) { - broadcastAll(shared_ptr( new PlayerInfoPacket( player ) ) ); + broadcastAll(std::make_shared(player)); } players.push_back(player); @@ -452,16 +483,16 @@ void PlayerList::add(shared_ptr player) // 4J Stu - Swapped these lines about so that we get the chunk visiblity packet way ahead of all the add tracked entity packets // Fix for #9169 - ART : Sign text is replaced with the words �Awaiting approval�. - changeDimension(player, NULL); + changeDimension(player, nullptr); level->addEntity(player); - for (int i = 0; i < players.size(); i++) + for (size_t i = 0; i < players.size(); i++) { shared_ptr op = players.at(i); //player->connection->send(shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); if( op->connection->getNetworkPlayer() ) { - player->connection->send(shared_ptr( new PlayerInfoPacket( op ) ) ); + player->connection->send(std::make_shared(op)); } } @@ -473,11 +504,11 @@ void PlayerList::add(shared_ptr player) shared_ptr thisPlayer = players[i]; if(thisPlayer->isSleeping()) { - if(firstSleepingPlayer == NULL) firstSleepingPlayer = thisPlayer; - thisPlayer->connection->send(shared_ptr( new ChatPacket(thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); + if(firstSleepingPlayer == nullptr) firstSleepingPlayer = thisPlayer; + thisPlayer->connection->send(std::make_shared(thisPlayer->name, ChatPacket::e_ChatBedMeSleep)); } } - player->connection->send(shared_ptr( new ChatPacket(firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep))); + player->connection->send(std::make_shared(firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep)); } } @@ -492,7 +523,7 @@ void PlayerList::remove(shared_ptr player) //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map if(player->isGuest()) playerIo->deleteMapFilesForPlayer(player); ServerLevel *level = player->getLevel(); -if (player->riding != NULL) +if (player->riding != nullptr) { level->removeEntityImmediately(player->riding); app.DebugPrintf("removing player mount"); @@ -510,10 +541,10 @@ if (player->riding != NULL) removePlayerFromReceiving(player); 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 = NULL; + player->gameMode = nullptr; // 4J Stu - Save all the players currently in the game, which will also free up unused map id slots if required, and remove old players - saveAll(NULL,false); + saveAll(nullptr,false); } shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendingConnection, const wstring& userName, PlayerUID xuid, PlayerUID onlineXuid) @@ -523,7 +554,7 @@ shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendin pendingConnection->disconnect(DisconnectPacket::eDisconnect_ServerFull); return shared_ptr(); } - shared_ptr player = shared_ptr(new ServerPlayer(server, server->getLevel(0), userName, new ServerPlayerGameMode(server->getLevel(0)) )); + shared_ptr player = std::make_shared(server, server->getLevel(0), userName, new ServerPlayerGameMode(server->getLevel(0))); player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor player->setXuid( xuid ); // 4J Added player->setOnlineXuid( onlineXuid ); // 4J Added @@ -532,7 +563,7 @@ shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendin // Use packet-supplied identity from LoginPacket. // Do not recompute from name here: mixed-version clients must stay compatible. INetworkPlayer* np = pendingConnection->connection->getSocket()->getPlayer(); - if (np != NULL) + if (np != nullptr) { player->setOnlineXuid(np->GetUID()); @@ -548,14 +579,14 @@ shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendin #endif // Work out the base server player settings INetworkPlayer *networkPlayer = pendingConnection->connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && !networkPlayer->IsHost()) + if(networkPlayer != nullptr && !networkPlayer->IsHost()) { player->enableAllPlayerPrivileges( app.GetGameHostOption(eGameHostOption_TrustPlayers)>0 ); } // 4J Added LevelRuleset *serverRuleDefs = app.getGameRuleDefinitions(); - if(serverRuleDefs != NULL) + if(serverRuleDefs != nullptr) { player->gameMode->setGameRules( GameRuleDefinition::generateNewGameRulesInstance(GameRulesInstance::eGameRulesInstanceType_ServerPlayer, serverRuleDefs, pendingConnection->connection) ); } @@ -582,7 +613,7 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay if( ep->dimension != oldDimension ) continue; INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { // There's another player here in the same dimension - we're not the last one out isEmptying = false; @@ -635,7 +666,7 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay PlayerUID playerXuid = serverPlayer->getXuid(); PlayerUID playerOnlineXuid = serverPlayer->getOnlineXuid(); - shared_ptr player = shared_ptr(new ServerPlayer(server, server->getLevel(serverPlayer->dimension), serverPlayer->getName(), new ServerPlayerGameMode(server->getLevel(serverPlayer->dimension)))); + shared_ptr player = std::make_shared(server, server->getLevel(serverPlayer->dimension), serverPlayer->getName(), new ServerPlayerGameMode(server->getLevel(serverPlayer->dimension))); player->connection = serverPlayer->connection; player->restoreFrom(serverPlayer, keepAllPlayerData); if (keepAllPlayerData) @@ -675,7 +706,7 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay { // If the player is still alive and respawning to the same dimension, they are just being added back from someone else viewing the Win screen player->moveTo(serverPlayer->x, serverPlayer->y, serverPlayer->z, serverPlayer->yRot, serverPlayer->xRot); - if(bedPosition != NULL) + if(bedPosition != nullptr) { player->setRespawnPosition(bedPosition, spawnForced); delete bedPosition; @@ -683,30 +714,30 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar player->inventory->selected = serverPlayer->inventory->selected; } - else if (bedPosition != NULL) + else if (bedPosition != nullptr) { Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(serverPlayer->dimension), bedPosition, spawnForced); - if (respawnPosition != NULL) + if (respawnPosition != nullptr) { player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); player->setRespawnPosition(bedPosition, spawnForced); } else { - player->connection->send( shared_ptr( new GameEventPacket(GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0) ) ); + player->connection->send(std::make_shared(GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0)); } delete bedPosition; } // Ensure the area the player is spawning in is loaded! - level->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + level->cache->create(static_cast(player->x) >> 4, static_cast(player->z) >> 4); while (!level->getCubes(player, player->bb)->empty()) { player->setPos(player->x, player->y + 1, player->z); } - player->connection->send( std::make_shared( (char) player->dimension, player->level->getSeed(), player->level->getMaxBuildHeight(), + player->connection->send( std::make_shared( static_cast(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->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); @@ -766,7 +797,7 @@ void PlayerList::toggleDimension(shared_ptr player, int targetDime if( ep->dimension != lastDimension ) continue; INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { // There's another player here in the same dimension - we're not the last one out isEmptying = false; @@ -823,9 +854,9 @@ void PlayerList::toggleDimension(shared_ptr player, int targetDime // 4J Stu Added so that we remove entities from the correct level, after the respawn packet we will be in the wrong level player->flushEntitiesToRemove(); - player->connection->send( shared_ptr( new RespawnPacket((char) player->dimension, newLevel->getSeed(), newLevel->getMaxBuildHeight(), - player->gameMode->getGameModeForPlayer(), newLevel->difficulty, newLevel->getLevelData()->getGenerator(), - newLevel->useNewSeaLevel(), player->entityId, newLevel->getLevelData()->getXZSize(), newLevel->getLevelData()->getHellScale()) ) ); + player->connection->send(std::make_shared(static_cast(player->dimension), newLevel->getSeed(), newLevel->getMaxBuildHeight(), + player->gameMode->getGameModeForPlayer(), newLevel->difficulty, newLevel->getLevelData()->getGenerator(), + newLevel->useNewSeaLevel(), player->entityId, newLevel->getLevelData()->getXZSize(), newLevel->getLevelData()->getHellScale())); oldLevel->removeEntityImmediately(player); player->removed = false; @@ -922,8 +953,8 @@ void PlayerList::repositionAcrossDimension(shared_ptr entity, int lastDi if (lastDimension != 1) { - xt = (double) Mth::clamp((int) xt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); - zt = (double) Mth::clamp((int) zt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); + xt = static_cast(Mth::clamp(static_cast(xt), -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128)); + zt = static_cast(Mth::clamp(static_cast(zt), -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128)); if (entity->isAlive()) { newLevel->addEntity(entity); @@ -952,7 +983,7 @@ void PlayerList::tick() //broadcastAll(shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); if( op->connection->getNetworkPlayer() ) { - broadcastAll(shared_ptr( new PlayerInfoPacket( op ) ) ); + broadcastAll(std::make_shared(op)); } } @@ -967,18 +998,26 @@ void PlayerList::tick() for(unsigned int i = 0; i < players.size(); i++) { shared_ptr p = players.at(i); - // 4J Stu - May be being a bit overprotective with all the NULL checks, but adding late in TU7 so want to be safe - if (p != NULL && p->connection != NULL && p->connection->connection != NULL && p->connection->connection->getSocket() != NULL && p->connection->connection->getSocket()->getSmallId() == smallId ) + // 4J Stu - May be being a bit overprotective with all the nullptr checks, but adding late in TU7 so want to be safe + if (p != nullptr && p->connection != nullptr && p->connection->connection != nullptr && p->connection->connection->getSocket() != nullptr && p->connection->connection->getSocket()->getSmallId() == smallId ) { player = p; break; } } - if (player != NULL) + if (player != nullptr) { player->connection->disconnect( DisconnectPacket::eDisconnect_Closed ); } + +#ifdef _WINDOWS64 + // The old Connection's read/write threads are now dead (disconnect waits + // for them). Safe to recycle the smallId — no stale write thread can + // resolve getPlayer() to a new connection that reuses this slot. + WinsockNetLayer::PushFreeSmallId(smallId); + WinsockNetLayer::ClearSocketForSmallId(smallId); +#endif } LeaveCriticalSection(&m_closePlayersCS); @@ -988,7 +1027,7 @@ void PlayerList::tick() BYTE smallId = m_smallIdsToKick.front(); m_smallIdsToKick.pop_front(); INetworkPlayer *selectedPlayer = g_NetworkManager.GetPlayerBySmallId(smallId); - if( selectedPlayer != NULL ) + if( selectedPlayer != nullptr ) { if( selectedPlayer->IsLocal() != TRUE ) { @@ -1001,20 +1040,20 @@ void PlayerList::tick() { shared_ptr p = players.at(i); PlayerUID playersXuid = p->getOnlineXuid(); - if (p != NULL && ProfileManager.AreXUIDSEqual(playersXuid, xuid ) ) + if (p != nullptr && ProfileManager.AreXUIDSEqual(playersXuid, xuid ) ) { player = p; break; } } - if (player != NULL) + if (player != nullptr) { m_bannedXuids.push_back( player->getOnlineXuid() ); // 4J Stu - If we have kicked a player, make sure that they have no privileges if they later try to join the world when trust players is off player->enableAllPlayerPrivileges( false ); player->connection->setWasKicked(); - player->connection->send( shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Kicked) )); + player->connection->send(std::make_shared(DisconnectPacket::eDisconnect_Kicked)); } //#endif } @@ -1031,7 +1070,7 @@ void PlayerList::tick() if(currentPlayer->removed) { shared_ptr newPlayer = findAlivePlayerOnSystem(currentPlayer); - if(newPlayer != NULL) + if(newPlayer != nullptr) { receiveAllPlayers[dim][i] = newPlayer; app.DebugPrintf("Replacing primary player %ls with %ls in dimension %d\n", currentPlayer->name.c_str(), newPlayer->name.c_str(), dim); @@ -1098,7 +1137,7 @@ bool PlayerList::isOp(shared_ptr player) cheatsEnabled = cheatsEnabled || app.GetUseDPadForDebug(); #endif INetworkPlayer *networkPlayer = player->connection->getNetworkPlayer(); - bool isOp = cheatsEnabled && (player->isModerator() || (networkPlayer != NULL && networkPlayer->IsHost())); + bool isOp = cheatsEnabled && (player->isModerator() || (networkPlayer != nullptr && networkPlayer->IsHost())); return isOp; } @@ -1132,12 +1171,12 @@ shared_ptr PlayerList::getPlayer(PlayerUID uid) shared_ptr PlayerList::getNearestPlayer(Pos *position, int range) { if (players.empty()) return nullptr; - if (position == NULL) return players.at(0); + if (position == nullptr) return players.at(0); shared_ptr current = nullptr; double dist = -1; int rangeSqr = range * range; - for (int i = 0; i < players.size(); i++) + for (size_t i = 0; i < players.size(); i++) { shared_ptr next = players.at(i); double newDist = position->distSqr(next->getCommandSenderWorldPosition()); @@ -1155,9 +1194,9 @@ shared_ptr PlayerList::getNearestPlayer(Pos *position, int range) vector *PlayerList::getPlayers(Pos *position, int rangeMin, int rangeMax, int count, int mode, int levelMin, int levelMax, unordered_map *scoreRequirements, const wstring &playerName, const wstring &teamName, Level *level) { app.DebugPrintf("getPlayers NOT IMPLEMENTED!"); - return NULL; + return nullptr; - /*if (players.empty()) return NULL; + /*if (players.empty()) return nullptr; vector > result = new vector >(); bool reverse = count < 0; bool playerNameNot = !playerName.empty() && playerName.startsWith("!"); @@ -1169,7 +1208,7 @@ vector *PlayerList::getPlayers(Pos *position, int rangeMin, int ra if (playerNameNot) playerName = playerName.substring(1); if (teamNameNot) teamName = teamName.substring(1); - for (int i = 0; i < players.size(); i++) { + for (size_t i = 0; i < players.size(); i++) { ServerPlayer player = players.get(i); if (level != null && player.level != level) continue; @@ -1239,9 +1278,9 @@ bool PlayerList::meetsScoreRequirements(shared_ptr player, unordered_map void PlayerList::sendMessage(const wstring& name, const wstring& message) { shared_ptr player = getPlayer(name); - if (player != NULL) + if (player != nullptr) { - player->connection->send( shared_ptr( new ChatPacket(message) ) ); + player->connection->send(std::make_shared(message)); } } @@ -1255,7 +1294,7 @@ void PlayerList::broadcast(shared_ptr except, double x, double y, double // 4J - altered so that we don't send to the same machine more than once. Add the source player to the machines we have "sent" to as it doesn't need to go to that // machine either vector< shared_ptr > sentTo; - if( except != NULL ) + if( except != nullptr ) { sentTo.push_back(dynamic_pointer_cast(except)); } @@ -1271,7 +1310,7 @@ void PlayerList::broadcast(shared_ptr except, double x, double y, double if( sentTo.size() ) { INetworkPlayer *thisPlayer = p->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) + if( thisPlayer == nullptr ) { dontSend = true; } @@ -1281,7 +1320,7 @@ void PlayerList::broadcast(shared_ptr except, double x, double y, double { shared_ptr player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { dontSend = true; } @@ -1319,8 +1358,8 @@ void PlayerList::broadcast(shared_ptr except, double x, double y, double void PlayerList::saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps /*= false*/) { - if(progressListener != NULL) progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); - // 4J - playerIo can be NULL if we have have to exit a game really early on due to network failure + if(progressListener != nullptr) progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); + // 4J - playerIo can be nullptr if we have have to exit a game really early on due to network failure if(playerIo) { playerIo->saveAllCachedData(); @@ -1331,7 +1370,7 @@ void PlayerList::saveAll(ProgressListener *progressListener, bool bDeleteGuestMa //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map if(bDeleteGuestMaps && players[i]->isGuest()) playerIo->deleteMapFilesForPlayer(players[i]); - if(progressListener != NULL) progressListener->progressStagePercentage((i * 100)/ ((int)players.size())); + if(progressListener != nullptr) progressListener->progressStagePercentage((i * 100)/ static_cast(players.size())); } playerIo->clearOldPlayerFiles(); playerIo->saveMapIdLookup(); @@ -1352,22 +1391,22 @@ void PlayerList::reloadWhitelist() void PlayerList::sendLevelInfo(shared_ptr player, ServerLevel *level) { - player->connection->send( shared_ptr( new SetTimePacket(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)) ) ); + player->connection->send(std::make_shared(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT))); if (level->isRaining()) { - player->connection->send( shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + player->connection->send(std::make_shared(GameEventPacket::START_RAINING, 0)); } else { // 4J Stu - Fix for #44836 - Customer Encountered: Out of Sync Weather [A-10] // If it was raining when the player left the level, and is now not raining we need to make sure that state is updated - player->connection->send( shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); + player->connection->send(std::make_shared(GameEventPacket::STOP_RAINING, 0)); } // send the stronghold position if there is one if((level->dimension->id==0) && level->getLevelData()->getHasStronghold()) { - player->connection->send( shared_ptr( new XZPacket(XZPacket::STRONGHOLD,level->getLevelData()->getXStronghold(),level->getLevelData()->getZStronghold()) ) ); + player->connection->send(std::make_shared(XZPacket::STRONGHOLD, level->getLevelData()->getXStronghold(), level->getLevelData()->getZStronghold())); } } @@ -1375,12 +1414,12 @@ void PlayerList::sendAllPlayerInfo(shared_ptr player) { player->refreshContainer(player->inventoryMenu); player->resetSentInfo(); - player->connection->send( shared_ptr( new SetCarriedItemPacket(player->inventory->selected)) ); + player->connection->send(std::make_shared(player->inventory->selected)); } int PlayerList::getPlayerCount() { - return (int)players.size(); + return static_cast(players.size()); } int PlayerList::getPlayerCount(ServerLevel *level) @@ -1420,11 +1459,11 @@ void PlayerList::updatePlayerGameMode(shared_ptr newPlayer, shared // reset the player's game mode (first pick from old, then copy level if // necessary) - if (oldPlayer != NULL) + if (oldPlayer != nullptr) { newPlayer->gameMode->setGameModeForPlayer(oldPlayer->gameMode->getGameModeForPlayer()); } - else if (overrideGameMode != NULL) + else if (overrideGameMode != nullptr) { newPlayer->gameMode->setGameModeForPlayer(overrideGameMode); } @@ -1508,10 +1547,10 @@ void PlayerList::removePlayerFromReceiving(shared_ptr player, bool } } } - else if( thisPlayer == NULL ) + else if( thisPlayer == nullptr ) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Qnet player for %ls was NULL so re-checking all players\n", player->name.c_str() ); + app.DebugPrintf("Remove: Qnet player for %ls was nullptr so re-checking all players\n", player->name.c_str() ); #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 @@ -1528,7 +1567,7 @@ void PlayerList::removePlayerFromReceiving(shared_ptr player, bool for(auto& primaryPlayer : receiveAllPlayers[newPlayerDim]) { INetworkPlayer *primPlayer = primaryPlayer->connection->getNetworkPlayer(); - if(primPlayer != NULL && checkingPlayer->IsSameSystem( primPlayer ) ) + if(primPlayer != nullptr && checkingPlayer->IsSameSystem( primPlayer ) ) { foundPrimary = true; break; @@ -1560,10 +1599,10 @@ void PlayerList::addPlayerToReceiving(shared_ptr player) INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) + if( thisPlayer == nullptr ) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Add: Qnet player for player %ls is NULL so not adding them\n", player->name.c_str() ); + app.DebugPrintf("Add: Qnet player for player %ls is nullptr so not adding them\n", player->name.c_str() ); #endif shouldAddPlayer = false; } @@ -1572,7 +1611,7 @@ void PlayerList::addPlayerToReceiving(shared_ptr player) for(auto& oldPlayer : receiveAllPlayers[playerDim]) { INetworkPlayer *checkingPlayer = oldPlayer->connection->getNetworkPlayer(); - if(checkingPlayer != NULL && checkingPlayer->IsSameSystem( thisPlayer ) ) + if(checkingPlayer != nullptr && checkingPlayer->IsSameSystem( thisPlayer ) ) { shouldAddPlayer = false; break; @@ -1618,6 +1657,13 @@ void PlayerList::closePlayerConnectionBySmallId(BYTE networkSmallId) LeaveCriticalSection(&m_closePlayersCS); } +void PlayerList::queueSmallIdForRecycle(BYTE smallId) +{ + EnterCriticalSection(&m_closePlayersCS); + m_smallIdsToClose.push_back(smallId); + LeaveCriticalSection(&m_closePlayersCS); +} + bool PlayerList::isXuidBanned(PlayerUID xuid) { if( xuid == INVALID_XUID ) return false; @@ -1633,6 +1679,13 @@ bool PlayerList::isXuidBanned(PlayerUID xuid) } } +#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) + if (!banned && g_Win64DedicatedServer) + { + banned = ServerRuntime::Access::IsPlayerBanned(xuid); + } +#endif + return banned; } diff --git a/Minecraft.Client/PlayerList.h b/Minecraft.Client/PlayerList.h index 03ed2398b..a4ae9c5d7 100644 --- a/Minecraft.Client/PlayerList.h +++ b/Minecraft.Client/PlayerList.h @@ -133,6 +133,7 @@ public: // 4J Added void kickPlayerByShortId(BYTE networkSmallId); void closePlayerConnectionBySmallId(BYTE networkSmallId); + void queueSmallIdForRecycle(BYTE smallId); bool isXuidBanned(PlayerUID xuid); // AP added for Vita so the range can be increased once the level starts void setViewDistance(int newViewDistance); diff --git a/Minecraft.Client/PlayerRenderer.cpp b/Minecraft.Client/PlayerRenderer.cpp index ff930a133..a9b945440 100644 --- a/Minecraft.Client/PlayerRenderer.cpp +++ b/Minecraft.Client/PlayerRenderer.cpp @@ -57,7 +57,7 @@ ResourceLocation PlayerRenderer::DEFAULT_LOCATION = ResourceLocation(TN_MOB_CHAR PlayerRenderer::PlayerRenderer() : LivingEntityRenderer( new HumanoidModel(0), 0.5f ) { - humanoidModel = (HumanoidModel *) model; + humanoidModel = static_cast(model); armorParts1 = new HumanoidModel(1.0f); armorParts2 = new HumanoidModel(0.5f); @@ -83,7 +83,7 @@ int PlayerRenderer::prepareArmor(shared_ptr _player, int layer, fl } shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) + if (itemInstance != nullptr) { Item *item = itemInstance->getItem(); if (dynamic_cast(item)) @@ -102,17 +102,17 @@ int PlayerRenderer::prepareArmor(shared_ptr _player, int layer, fl armor->leg1->visible = layer == 2 || layer == 3; setArmor(armor); - if (armor != NULL) armor->attackTime = model->attackTime; - if (armor != NULL) armor->riding = model->riding; - if (armor != NULL) armor->young = model->young; + if (armor != nullptr) armor->attackTime = model->attackTime; + if (armor != nullptr) armor->riding = model->riding; + if (armor != nullptr) armor->young = model->young; float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) { int color = armorItem->getColor(itemInstance); - float red = (float) ((color >> 16) & 0xFF) / 0xFF; - float green = (float) ((color >> 8) & 0xFF) / 0xFF; - float blue = (float) (color & 0xFF) / 0xFF; + float red = static_cast((color >> 16) & 0xFF) / 0xFF; + float green = static_cast((color >> 8) & 0xFF) / 0xFF; + float blue = static_cast(color & 0xFF) / 0xFF; glColor3f(brightness * red, brightness * green, brightness * blue); if (itemInstance->isEnchanted()) return 0x1f; @@ -137,13 +137,13 @@ void PlayerRenderer::prepareSecondPassArmor(shared_ptr _player, in // 4J - dynamic cast required because we aren't using templates/generics in our version shared_ptr player = dynamic_pointer_cast(_player); shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) + if (itemInstance != nullptr) { Item *item = itemInstance->getItem(); if (dynamic_cast(item)) { ArmorItem *armorItem = dynamic_cast(item); - bindTexture(HumanoidMobRenderer::getArmorLocation((ArmorItem *)item, layer, true)); + bindTexture(HumanoidMobRenderer::getArmorLocation(static_cast(item), layer, true)); float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); glColor3f(brightness, brightness, brightness); @@ -153,14 +153,20 @@ void PlayerRenderer::prepareSecondPassArmor(shared_ptr _player, in void PlayerRenderer::render(shared_ptr _mob, double x, double y, double z, float rot, float a) { + if (_mob == nullptr) + { + return; + } + // 4J - dynamic cast required because we aren't using templates/generics in our version shared_ptr mob = dynamic_pointer_cast(_mob); + if(mob == nullptr) return; if(mob->hasInvisiblePrivilege()) return; shared_ptr item = mob->inventory->getSelected(); - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != NULL ? 1 : 0; - if (item != NULL) + armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != nullptr ? 1 : 0; + if (item != nullptr) { if (mob->getUseItemDuration() > 0) { @@ -176,7 +182,7 @@ void PlayerRenderer::render(shared_ptr _mob, double x, double y, double } } // 4J added, for 3rd person view of eating - if( item != NULL && mob->getUseItemDuration() > 0 && item->getUseAnimation() == UseAnim_eat ) + if( item != nullptr && mob->getUseItemDuration() > 0 && item->getUseAnimation() == UseAnim_eat ) { // These factors are largely lifted from ItemInHandRenderer to try and keep the 3rd person eating animation as similar as possible float t = (mob->getUseItemDuration() - a + 1); @@ -260,7 +266,7 @@ void PlayerRenderer::additionalRendering(shared_ptr _mob, float a) shared_ptr mob = dynamic_pointer_cast(_mob); shared_ptr headGear = mob->inventory->getArmor(3); - if (headGear != NULL) + if (headGear != nullptr) { // don't render the pumpkin for the skins unsigned int uiAnimOverrideBitmask = mob->getSkinAnimOverrideBitmask( mob->getCustomSkin()); @@ -300,7 +306,7 @@ void PlayerRenderer::additionalRendering(shared_ptr _mob, float a) } // need to add a custom texture for deadmau5 - if (mob != NULL && app.isXuidDeadmau5( mob->getXuid() ) && bindTexture(mob->customTextureUrl, L"" )) + if (mob != nullptr && app.isXuidDeadmau5( mob->getXuid() ) && bindTexture(mob->customTextureUrl, L"" )) { for (int i = 0; i < 2; i++) { @@ -339,11 +345,11 @@ void PlayerRenderer::additionalRendering(shared_ptr _mob, float a) double xa = Mth::sin(yr * PI / 180); double za = -Mth::cos(yr * PI / 180); - float flap = (float) yd * 10; + float flap = static_cast(yd) * 10; if (flap < -6) flap = -6; if (flap > 32) flap = 32; - float lean = (float) (xd * xa + zd * za) * 100; - float lean2 = (float) (xd * za - zd * xa) * 100; + float lean = static_cast(xd * xa + zd * za) * 100; + float lean2 = static_cast(xd * za - zd * xa) * 100; if (lean < 0) lean = 0; float pow = mob->oBob + (mob->bob - mob->oBob) * a; @@ -368,15 +374,15 @@ void PlayerRenderer::additionalRendering(shared_ptr _mob, float a) shared_ptr item = mob->inventory->getSelected(); - if (item != NULL) + if (item != nullptr) { glPushMatrix(); humanoidModel->arm0->translateTo(1 / 16.0f); glTranslatef(-1 / 16.0f, 7 / 16.0f, 1 / 16.0f); - if (mob->fishing != NULL) + if (mob->fishing != nullptr) { - item = shared_ptr( new ItemInstance(Item::stick) ); + item = std::make_shared(Item::stick); } UseAnim anim = UseAnim_none;//null; @@ -472,7 +478,7 @@ void PlayerRenderer::renderNameTags(shared_ptr player, double x, d Scoreboard *scoreboard = player->getScoreboard(); Objective *objective = scoreboard->getDisplayObjective(Scoreboard::DISPLAY_SLOT_BELOW_NAME); - if (objective != NULL) + if (objective != nullptr) { Score *score = scoreboard->getPlayerScore(player->getAName(), objective); @@ -558,7 +564,7 @@ void PlayerRenderer::renderShadow(shared_ptr e, double x, double y, doub if(app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) > 0) { shared_ptr player = dynamic_pointer_cast(e); - if(player != NULL && player->hasInvisiblePrivilege()) return; + if(player != nullptr && player->hasInvisiblePrivilege()) return; } EntityRenderer::renderShadow(e,x,y,z,pow,a); } @@ -573,5 +579,5 @@ void PlayerRenderer::bindTexture(shared_ptr entity) ResourceLocation *PlayerRenderer::getTextureLocation(shared_ptr entity) { shared_ptr player = dynamic_pointer_cast(entity); - return new ResourceLocation((_TEXTURE_NAME)player->getTexture()); + return new ResourceLocation(static_cast<_TEXTURE_NAME>(player->getTexture())); } \ No newline at end of file diff --git a/Minecraft.Client/Polygon.cpp b/Minecraft.Client/Polygon.cpp index 00176511f..05cf9b077 100644 --- a/Minecraft.Client/Polygon.cpp +++ b/Minecraft.Client/Polygon.cpp @@ -58,17 +58,17 @@ void _Polygon::render(Tesselator *t, float scale) t->begin(); if (_flipNormal) { - t->normal(-(float)n->x, -(float)n->y, -(float)n->z); + t->normal(-static_cast(n->x), -static_cast(n->y), -static_cast(n->z)); } else { - t->normal((float)n->x, (float)n->y, (float)n->z); + t->normal(static_cast(n->x), static_cast(n->y), static_cast(n->z)); } for (int i = 0; i < 4; i++) { Vertex *v = vertices[i]; - t->vertexUV((float)(v->pos->x * scale), (float)( v->pos->y * scale), (float)( v->pos->z * scale), (float)( v->u), (float)( v->v)); + t->vertexUV(static_cast(v->pos->x * scale), static_cast(v->pos->y * scale), static_cast(v->pos->z * scale), (float)( v->u), (float)( v->v)); } t->end(); } diff --git a/Minecraft.Client/PreStitchedTextureMap.cpp b/Minecraft.Client/PreStitchedTextureMap.cpp index eeccb6285..33e0b59ec 100644 --- a/Minecraft.Client/PreStitchedTextureMap.cpp +++ b/Minecraft.Client/PreStitchedTextureMap.cpp @@ -26,11 +26,11 @@ PreStitchedTextureMap::PreStitchedTextureMap(int type, const wstring &name, cons this->missingTexture = missingTexture; // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + missingPosition = nullptr; + stitchResult = nullptr; m_mipMap = mipmap; - missingPosition = (StitchedTexture *)(new SimpleIcon(NAME_MISSING_TEXTURE,NAME_MISSING_TEXTURE,0,0,1,1)); + missingPosition = static_cast(new SimpleIcon(NAME_MISSING_TEXTURE, NAME_MISSING_TEXTURE, 0, 0, 1, 1)); } void PreStitchedTextureMap::stitch() @@ -48,7 +48,7 @@ void PreStitchedTextureMap::stitch() //for (Tile tile : Tile.tiles) for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { - if (Tile::tiles[i] != NULL) + if (Tile::tiles[i] != nullptr) { Tile::tiles[i]->registerIcons(this); } @@ -62,7 +62,7 @@ void PreStitchedTextureMap::stitch() for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) + if (item != nullptr && item->getIconType() == iconType) { item->registerIcons(this); } @@ -121,7 +121,7 @@ void PreStitchedTextureMap::stitch() int height = image->getHeight(); int width = image->getWidth(); - if(stitchResult != NULL) + if(stitchResult != nullptr) { TextureManager::getInstance()->unregisterTexture(name, stitchResult); delete stitchResult; @@ -216,7 +216,7 @@ void PreStitchedTextureMap::makeTextureAnimated(TexturePack *texturePack, Stitch // TODO: [EB] Put the frames into a proper object, not this inside out hack vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); - if (frames == NULL || frames->empty()) + if (frames == nullptr || frames->empty()) { return; // Couldn't load a texture, skip it } @@ -248,10 +248,10 @@ StitchedTexture *PreStitchedTextureMap::getTexture(const wstring &name) app.DebugPrintf("Not implemented!\n"); __debugbreak(); #endif - return NULL; + return nullptr; #if 0 StitchedTexture *result = texturesByName.find(name)->second; - if (result == NULL) result = missingPosition; + if (result == nullptr) result = missingPosition; return result; #endif } @@ -272,10 +272,10 @@ Texture *PreStitchedTextureMap::getStitchedTexture() // 4J Stu - register is a reserved keyword in C++ Icon *PreStitchedTextureMap::registerIcon(const wstring &name) { - Icon *result = NULL; + Icon *result = nullptr; if (name.empty()) { - app.DebugPrintf("Don't register NULL\n"); + app.DebugPrintf("Don't register nullptr\n"); #ifndef _CONTENT_PACKAGE __debugbreak(); #endif diff --git a/Minecraft.Client/QuadrupedModel.cpp b/Minecraft.Client/QuadrupedModel.cpp index ea0419104..23d1758b4 100644 --- a/Minecraft.Client/QuadrupedModel.cpp +++ b/Minecraft.Client/QuadrupedModel.cpp @@ -10,27 +10,27 @@ QuadrupedModel::QuadrupedModel(int legSize, float g) : Model() head = new ModelPart(this, 0, 0); head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(12 + 6 - legSize), -6); + head->setPos(0, static_cast(12 + 6 - legSize), -6); body = new ModelPart(this, 28, 8); body->addBox(-5, -10, -7, 10, 16, 8, g); // Body - body->setPos(0, (float)(11 + 6 - legSize), 2); + body->setPos(0, static_cast(11 + 6 - legSize), 2); leg0 = new ModelPart(this, 0, 16); leg0->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg0 - leg0->setPos(-3, (float)(18 + 6 - legSize), 7); + leg0->setPos(-3, static_cast(18 + 6 - legSize), 7); leg1 = new ModelPart(this, 0, 16); leg1->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg1 - leg1->setPos(3, (float)(18 + 6 - legSize), 7); + leg1->setPos(3, static_cast(18 + 6 - legSize), 7); leg2 = new ModelPart(this, 0, 16); leg2->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg2 - leg2->setPos(-3, (float)(18 + 6 - legSize), -5); + leg2->setPos(-3, static_cast(18 + 6 - legSize), -5); leg3 = new ModelPart(this, 0, 16); leg3->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg3 - leg3->setPos(3, (float)(18 + 6 - legSize), -5); + leg3->setPos(3, static_cast(18 + 6 - legSize), -5); // 4J added - compile now to avoid random performance hit first time cubes are rendered head->compile(1.0f/16.0f); diff --git a/Minecraft.Client/ReceivingLevelScreen.cpp b/Minecraft.Client/ReceivingLevelScreen.cpp index 0e9fe3ec0..2969b0539 100644 --- a/Minecraft.Client/ReceivingLevelScreen.cpp +++ b/Minecraft.Client/ReceivingLevelScreen.cpp @@ -23,9 +23,9 @@ void ReceivingLevelScreen::tick() tickCount++; if (tickCount % 20 == 0) { - connection->send( shared_ptr( new KeepAlivePacket() ) ); + connection->send(std::make_shared()); } - if (connection != NULL) + if (connection != nullptr) { connection->tick(); } diff --git a/Minecraft.Client/RedDustParticle.cpp b/Minecraft.Client/RedDustParticle.cpp index 6a6ad1e1b..69eb225a0 100644 --- a/Minecraft.Client/RedDustParticle.cpp +++ b/Minecraft.Client/RedDustParticle.cpp @@ -14,16 +14,16 @@ void RedDustParticle::init(Level *level, double x, double y, double z, float sca { rCol = 1; } - float brr = (float) Math::random() * 0.4f + 0.6f; - this->rCol = ((float) (Math::random() * 0.2f) + 0.8f) * rCol * brr; - this->gCol = ((float) (Math::random() * 0.2f) + 0.8f) * gCol * brr; - this->bCol = ((float) (Math::random() * 0.2f) + 0.8f) * bCol * brr; + float brr = static_cast(Math::random()) * 0.4f + 0.6f; + this->rCol = (static_cast(Math::random() * 0.2f) + 0.8f) * rCol * brr; + this->gCol = (static_cast(Math::random() * 0.2f) + 0.8f) * gCol * brr; + this->bCol = (static_cast(Math::random() * 0.2f) + 0.8f) * bCol * brr; size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int)(lifetime * scale); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(lifetime * scale); noPhysics = false; } diff --git a/Minecraft.Client/RemotePlayer.cpp b/Minecraft.Client/RemotePlayer.cpp index bea128428..dcfd69926 100644 --- a/Minecraft.Client/RemotePlayer.cpp +++ b/Minecraft.Client/RemotePlayer.cpp @@ -58,7 +58,7 @@ void RemotePlayer::tick() walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; walkAnimPos += walkAnimSpeed; - if (!hasStartedUsingItem && isUsingItemFlag() && inventory->items[inventory->selected] != NULL) + if (!hasStartedUsingItem && isUsingItemFlag() && inventory->items[inventory->selected] != nullptr) { shared_ptr item = inventory->items[inventory->selected]; startUsingItem(inventory->items[inventory->selected], Item::items[item->id]->getUseDuration(item)); @@ -103,8 +103,8 @@ void RemotePlayer::aiStep() while (yrd >= 180) yrd -= 360; - yRot += (float)((yrd) / lSteps); - xRot += (float)((lxr - xRot) / lSteps); + yRot += static_cast((yrd) / lSteps); + xRot += static_cast((lxr - xRot) / lSteps); lSteps--; setPos(xt, yt, zt); @@ -113,7 +113,7 @@ void RemotePlayer::aiStep() oBob = bob; float tBob = (float) Mth::sqrt(xd * xd + zd * zd); - float tTilt = (float) atan(-yd * 0.2f) * 15.0f; + float tTilt = static_cast(atan(-yd * 0.2f)) * 15.0f; if (tBob > 0.1f) tBob = 0.1f; if (!onGround || getHealth() <= 0) tBob = 0; if (onGround || getHealth() <= 0) tTilt = 0; diff --git a/Minecraft.Client/RenameWorldScreen.cpp b/Minecraft.Client/RenameWorldScreen.cpp index ea05039af..4255201ca 100644 --- a/Minecraft.Client/RenameWorldScreen.cpp +++ b/Minecraft.Client/RenameWorldScreen.cpp @@ -8,7 +8,7 @@ RenameWorldScreen::RenameWorldScreen(Screen *lastScreen, const wstring& levelId) { - nameEdit = NULL; + nameEdit = nullptr; this->lastScreen = lastScreen; this->levelId = levelId; } diff --git a/Minecraft.Client/ResourceLocation.h b/Minecraft.Client/ResourceLocation.h index f53c46c87..1274b25ab 100644 --- a/Minecraft.Client/ResourceLocation.h +++ b/Minecraft.Client/ResourceLocation.h @@ -34,7 +34,7 @@ public: m_texture = textureNameArray(textures.length); for(unsigned int i = 0; i < textures.length; ++i) { - m_texture[i] = (_TEXTURE_NAME)textures[i]; + m_texture[i] = static_cast<_TEXTURE_NAME>(textures[i]); } m_preloaded = true; } diff --git a/Minecraft.Client/Screen.cpp b/Minecraft.Client/Screen.cpp index 9b7531460..7966c5c96 100644 --- a/Minecraft.Client/Screen.cpp +++ b/Minecraft.Client/Screen.cpp @@ -14,13 +14,13 @@ Screen::Screen() // 4J added { - minecraft = NULL; + minecraft = nullptr; width = 0; height = 0; passEvents = false; - font = NULL; - particles = NULL; - clickedButton = NULL; + font = nullptr; + particles = nullptr; + clickedButton = nullptr; } void Screen::render(int xm, int ym, float a) @@ -36,7 +36,7 @@ void Screen::keyPressed(wchar_t eventCharacter, int eventKey) { if (eventKey == Keyboard::KEY_ESCAPE) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); // minecraft->grabMouse(); // 4J - removed } } @@ -44,12 +44,12 @@ void Screen::keyPressed(wchar_t eventCharacter, int eventKey) wstring Screen::getClipboard() { #ifdef _WINDOWS64 - if (!OpenClipboard(NULL)) return wstring(); + if (!OpenClipboard(nullptr)) return wstring(); HANDLE h = GetClipboardData(CF_UNICODETEXT); wstring out; if (h) { - const wchar_t *p = reinterpret_cast(GlobalLock(h)); + const wchar_t *p = static_cast(GlobalLock(h)); if (p) { out = p; GlobalUnlock(h); } } CloseClipboard(); @@ -62,7 +62,7 @@ wstring Screen::getClipboard() void Screen::setClipboard(const wstring& str) { #ifdef _WINDOWS64 - if (!OpenClipboard(NULL)) return; + if (!OpenClipboard(nullptr)) return; EmptyClipboard(); size_t len = (str.length() + 1) * sizeof(wchar_t); HGLOBAL h = GlobalAlloc(GMEM_MOVEABLE, len); @@ -89,10 +89,10 @@ void Screen::mouseClicked(int x, int y, int buttonNum) void Screen::mouseReleased(int x, int y, int buttonNum) { - if (clickedButton!=NULL && buttonNum==0) + if (clickedButton!=nullptr && buttonNum==0) { clickedButton->released(x, y); - clickedButton = NULL; + clickedButton = nullptr; } } @@ -204,7 +204,7 @@ void Screen::updateEvents() // Map to Screen::keyPressed int mappedKey = -1; wchar_t ch = 0; - if (vk == VK_ESCAPE) mappedKey = Keyboard::KEY_ESCAPE; + if (vk == VK_ESCAPE) mappedKey = Keyboard::KEY_ESCAPE; else if (vk == VK_RETURN) mappedKey = Keyboard::KEY_RETURN; else if (vk == VK_BACK) mappedKey = Keyboard::KEY_BACK; else if (vk == VK_UP) mappedKey = Keyboard::KEY_UP; @@ -284,7 +284,7 @@ void Screen::renderBackground() void Screen::renderBackground(int vo) { - if (minecraft->level != NULL) + if (minecraft->level != nullptr) { fillGradient(0, 0, width, height, 0xc0101010, 0xd0101010); } diff --git a/Minecraft.Client/ScreenSizeCalculator.cpp b/Minecraft.Client/ScreenSizeCalculator.cpp index 32e942a79..38aa75a83 100644 --- a/Minecraft.Client/ScreenSizeCalculator.cpp +++ b/Minecraft.Client/ScreenSizeCalculator.cpp @@ -21,10 +21,10 @@ ScreenSizeCalculator::ScreenSizeCalculator(Options *options, int width, int heig { scale = forceScale; } - rawWidth = w / (double) scale; - rawHeight = h / (double) scale; - w = (int) ceil(rawWidth); - h = (int) ceil(rawHeight); + rawWidth = w / static_cast(scale); + rawHeight = h / static_cast(scale); + w = static_cast(ceil(rawWidth)); + h = static_cast(ceil(rawHeight)); } int ScreenSizeCalculator::getWidth() diff --git a/Minecraft.Client/ScrolledSelectionList.cpp b/Minecraft.Client/ScrolledSelectionList.cpp index 9b7367ce0..953695ab9 100644 --- a/Minecraft.Client/ScrolledSelectionList.cpp +++ b/Minecraft.Client/ScrolledSelectionList.cpp @@ -72,7 +72,7 @@ void ScrolledSelectionList::renderDecorations(int mouseX, int mouseY) int x0 = width / 2 - (92 + 16 + 2); int x1 = width / 2 + (92 + 16 + 2); - int clickSlotPos = (y - y0 - headerHeight + (int) yo - 4); + int clickSlotPos = (y - y0 - headerHeight + static_cast(yo) - 4); int slot = clickSlotPos / itemHeight; if (x >= x0 && x <= x1 && slot >= 0 && clickSlotPos >= 0 && slot < getNumberOfItems()) { @@ -92,7 +92,7 @@ void ScrolledSelectionList::capYPosition() int max = getMaxPosition() - (y1 - y0 - 4); if (max < 0) max /= 2; if (yo < 0) yo = 0; - if (yo > max) yo = (float)max; + if (yo > max) yo = static_cast(max); } void ScrolledSelectionList::buttonClicked(Button *button) diff --git a/Minecraft.Client/SelectWorldScreen.cpp b/Minecraft.Client/SelectWorldScreen.cpp index ebae8c83d..c6d417c56 100644 --- a/Minecraft.Client/SelectWorldScreen.cpp +++ b/Minecraft.Client/SelectWorldScreen.cpp @@ -16,11 +16,11 @@ SelectWorldScreen::SelectWorldScreen(Screen *lastScreen) title = L"Select world"; done = false; selectedWorld = 0; - worldSelectionList = NULL; + worldSelectionList = nullptr; isDeleting = false; - deleteButton = NULL; - selectButton = NULL; - renameButton = NULL; + deleteButton = nullptr; + selectButton = nullptr; + renameButton = nullptr; this->lastScreen = lastScreen; } @@ -115,14 +115,14 @@ void SelectWorldScreen::buttonClicked(Button *button) else { // create demo world - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); if (done) return; done = true; // 4J Stu - Not used, so commenting to stop the build failing #if 0 minecraft->gameMode = new DemoMode(minecraft); minecraft->selectLevel(CreateWorldScreen::findAvailableFolderName(minecraft->getLevelSource(), L"Demo"), L"Demo World", 0L); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); #endif } } @@ -142,20 +142,20 @@ void SelectWorldScreen::buttonClicked(Button *button) void SelectWorldScreen::worldSelected(int id) { - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); if (done) return; done = true; - minecraft->gameMode = NULL; //new SurvivalMode(minecraft); + minecraft->gameMode = nullptr; //new SurvivalMode(minecraft); wstring worldFolderName = getWorldId(id); - if (worldFolderName == L"") // 4J - was NULL comparison + if (worldFolderName == L"") // 4J - was nullptr comparison { worldFolderName = L"World" + std::to_wstring(id); } // 4J Stu - Not used, so commenting to stop the build failing #if 0 minecraft->selectLevel(worldFolderName, getWorldName(id), 0); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); #endif } @@ -235,7 +235,7 @@ SelectWorldScreen::WorldSelectionList::WorldSelectionList(SelectWorldScreen *sws int SelectWorldScreen::WorldSelectionList::getNumberOfItems() { - return (int)this->parent->levelList->size(); + return static_cast(this->parent->levelList->size()); } void SelectWorldScreen::WorldSelectionList::selectItem(int item, bool doubleClick) @@ -259,7 +259,7 @@ bool SelectWorldScreen::WorldSelectionList::isSelectedItem(int item) int SelectWorldScreen::WorldSelectionList::getMaxPosition() { - return (int)parent->levelList->size() * 36; + return static_cast(parent->levelList->size()) * 36; } void SelectWorldScreen::WorldSelectionList::renderBackground() diff --git a/Minecraft.Client/ServerChunkCache.cpp b/Minecraft.Client/ServerChunkCache.cpp index 3af98ca66..c7d70c7d3 100644 --- a/Minecraft.Client/ServerChunkCache.cpp +++ b/Minecraft.Client/ServerChunkCache.cpp @@ -71,7 +71,7 @@ bool ServerChunkCache::hasChunk(int x, int z) if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; int idx = ix * XZSIZE + iz; LevelChunk *lc = cache[idx]; - if( lc == NULL ) return false; + if( lc == nullptr ) return false; return true; } @@ -148,13 +148,13 @@ LevelChunk *ServerChunkCache::create(int x, int z, bool asyncPostProcess) // 4J LevelChunk *chunk = cache[idx]; LevelChunk *lastChunk = chunk; - if( ( chunk == NULL ) || ( chunk->x != x ) || ( chunk->z != z ) ) + if( ( chunk == nullptr ) || ( chunk->x != x ) || ( chunk->z != z ) ) { EnterCriticalSection(&m_csLoadCreate); chunk = load(x, z); - if (chunk == NULL) + if (chunk == nullptr) { - if (source == NULL) + if (source == nullptr) { chunk = emptyChunk; } @@ -163,7 +163,7 @@ LevelChunk *ServerChunkCache::create(int x, int z, bool asyncPostProcess) // 4J chunk = source->getChunk(x, z); } } - if (chunk != NULL) + if (chunk != nullptr) { chunk->load(); } @@ -320,7 +320,7 @@ void ServerChunkCache::overwriteLevelChunkFromSource(int x, int z) if( ( iz < 0 ) || ( iz >= XZSIZE ) ) assert(0); int idx = ix * XZSIZE + iz; - LevelChunk *chunk = NULL; + LevelChunk *chunk = nullptr; chunk = source->getChunk(x, z); assert(chunk); if(chunk) @@ -389,22 +389,22 @@ void ServerChunkCache::dontDrop(int x, int z) LevelChunk *ServerChunkCache::load(int x, int z) { - if (storage == NULL) return NULL; + if (storage == nullptr) return nullptr; - LevelChunk *levelChunk = NULL; + LevelChunk *levelChunk = nullptr; #ifdef _LARGE_WORLDS int ix = x + XZOFFSET; int iz = z + XZOFFSET; int idx = ix * XZSIZE + iz; levelChunk = m_unloadedCache[idx]; - m_unloadedCache[idx] = NULL; - if(levelChunk == NULL) + m_unloadedCache[idx] = nullptr; + if(levelChunk == nullptr) #endif { levelChunk = storage->load(level, x, z); } - if (levelChunk != NULL) + if (levelChunk != nullptr) { levelChunk->lastSaveTime = level->getGameTime(); } @@ -413,14 +413,14 @@ LevelChunk *ServerChunkCache::load(int x, int z) void ServerChunkCache::saveEntities(LevelChunk *levelChunk) { - if (storage == NULL) return; + if (storage == nullptr) return; storage->saveEntities(level, levelChunk); } void ServerChunkCache::save(LevelChunk *levelChunk) { - if (storage == NULL) return; + if (storage == nullptr) return; levelChunk->lastSaveTime = level->getGameTime(); storage->save(level, levelChunk); @@ -542,7 +542,7 @@ void ServerChunkCache::postProcess(ChunkSource *parent, int x, int z ) LevelChunk *chunk = getChunk(x, z); if ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0 ) { - if (source != NULL) + if (source != nullptr) { PIXBeginNamedEvent(0,"Main post processing"); source->postProcess(parent, x, z); @@ -659,7 +659,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) } // 4J - added this to support progressListener - if (progressListener != NULL) + if (progressListener != nullptr) { if (++cc % 10 == 0) { @@ -679,19 +679,19 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) vector sortedChunkList; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } @@ -712,7 +712,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) } // 4J - added this to support progressListener - if (progressListener != NULL) + if (progressListener != nullptr) { if (++cc % 10 == 0) { @@ -741,21 +741,21 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) for(unsigned int i = 0; i < 3; ++i) { - saveThreads[i] = NULL; + saveThreads[i] = nullptr; threadData[i].cache = this; - wakeEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); + wakeEvent[i] = new C4JThread::Event(); //CreateEvent(nullptr,FALSE,FALSE,nullptr); threadData[i].wakeEvent = wakeEvent[i]; - notificationEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); + notificationEvent[i] = new C4JThread::Event(); //CreateEvent(nullptr,FALSE,FALSE,nullptr); threadData[i].notificationEvent = notificationEvent[i]; if(i==0) threadData[i].useSharedThreadStorage = true; else threadData[i].useSharedThreadStorage = false; } - LevelChunk *chunk = NULL; + LevelChunk *chunk = nullptr; byte workingThreads; bool chunkSet = false; @@ -764,19 +764,19 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) vector sortedChunkList; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) + for( size_t i = 0; i < m_loadedChunkList.size(); i++ ) { if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } @@ -804,13 +804,13 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) //app.DebugPrintf("Chunk to save set for thread %d\n", j); - if(saveThreads[j] == NULL) + if(saveThreads[j] == nullptr) { char threadName[256]; sprintf(threadName,"Save thread %d\n",j); SetThreadName(threadId[j], threadName); - //saveThreads[j] = CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); + //saveThreads[j] = CreateThread(nullptr,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); saveThreads[j] = new C4JThread(runSaveThreadProc,(void *)&threadData[j],threadName); @@ -836,7 +836,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) } // 4J - added this to support progressListener - if (progressListener != NULL) + if (progressListener != nullptr) { if (count > 0 && ++cc % 10 == 0) { @@ -850,7 +850,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) if( !chunkSet ) { - threadData[j].chunkToSave = NULL; + threadData[j].chunkToSave = nullptr; //app.DebugPrintf("No chunk to save set for thread %d\n",j); } } @@ -882,13 +882,13 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) unsigned char validThreads = 0; for(unsigned int i = 0; i < 3; ++i) { - //app.DebugPrintf("Settings chunk to NULL for save thread %d\n", i); - threadData[i].chunkToSave = NULL; + //app.DebugPrintf("Settings chunk to nullptr for save thread %d\n", i); + threadData[i].chunkToSave = nullptr; //app.DebugPrintf("Setting wake event for save thread %d\n",i); threadData[i].wakeEvent->Set(); //SetEvent(threadData[i].wakeEvent); - if(saveThreads[i] != NULL) ++validThreads; + if(saveThreads[i] != nullptr) ++validThreads; } //WaitForMultipleObjects(validThreads,saveThreads,TRUE,INFINITE); @@ -910,7 +910,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) if (force) { - if (storage == NULL) + if (storage == nullptr) { LeaveCriticalSection(&m_csLoadCreate); return true; @@ -955,14 +955,14 @@ bool ServerChunkCache::tick() int iz = chunk->z + XZOFFSET; int idx = ix * XZSIZE + iz; m_unloadedCache[idx] = chunk; - cache[idx] = NULL; + cache[idx] = nullptr; } } m_toDrop.pop_front(); } } #endif - if (storage != NULL) storage->tick(); + if (storage != nullptr) storage->tick(); } return source->tick(); @@ -995,7 +995,7 @@ void ServerChunkCache::recreateLogicStructuresForChunk(int chunkX, int chunkZ) int ServerChunkCache::runSaveThreadProc(LPVOID lpParam) { - SaveThreadData *params = (SaveThreadData *)lpParam; + SaveThreadData *params = static_cast(lpParam); if(params->useSharedThreadStorage) { @@ -1013,7 +1013,7 @@ int ServerChunkCache::runSaveThreadProc(LPVOID lpParam) //app.DebugPrintf("Save thread has started\n"); - while(params->chunkToSave != NULL) + while(params->chunkToSave != nullptr) { PIXBeginNamedEvent(0,"Saving entities"); //app.DebugPrintf("Save thread has started processing a chunk\n"); diff --git a/Minecraft.Client/ServerConnection.cpp b/Minecraft.Client/ServerConnection.cpp index 07616aa47..0f96e0325 100644 --- a/Minecraft.Client/ServerConnection.cpp +++ b/Minecraft.Client/ServerConnection.cpp @@ -46,19 +46,30 @@ void ServerConnection::handleConnection(shared_ptr uc) void ServerConnection::stop() { + std::vector > pendingSnapshot; EnterCriticalSection(&pending_cs); - for (unsigned int i = 0; i < pending.size(); i++) - { - shared_ptr uc = pending[i]; - uc->connection->close(DisconnectPacket::eDisconnect_Closed); - } + pendingSnapshot = pending; LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < players.size(); i++) + for (unsigned int i = 0; i < pendingSnapshot.size(); i++) { - shared_ptr player = players[i]; - player->connection->close(DisconnectPacket::eDisconnect_Closed); - } + shared_ptr uc = pendingSnapshot[i]; + if (uc != NULL && !uc->done) + { + uc->disconnect(DisconnectPacket::eDisconnect_Closed); + } + } + + // Snapshot to avoid iterator invalidation if disconnect modifies the vector. + std::vector > playerSnapshot = players; + for (unsigned int i = 0; i < playerSnapshot.size(); i++) + { + shared_ptr player = playerSnapshot[i]; + if (player != NULL && !player->done) + { + player->disconnect(DisconnectPacket::eDisconnect_Quitting); + } + } } void ServerConnection::tick() @@ -78,7 +89,7 @@ void ServerConnection::tick() // uc.disconnect("Internal server error"); // logger.log(Level.WARNING, "Failed to handle packet: " + e, e); // } - if(uc->connection != NULL) uc->connection->flush(); + if(uc->connection != nullptr) uc->connection->flush(); } } @@ -107,7 +118,10 @@ void ServerConnection::tick() players.erase(players.begin()+i); i--; } - player->connection->flush(); + else + { + player->connection->flush(); + } } } @@ -167,7 +181,7 @@ void ServerConnection::handleServerSettingsChanged(shared_ptrlevels.length; ++i) { - if( pMinecraft->levels[i] != NULL ) + if( pMinecraft->levels[i] != nullptr ) { app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); pMinecraft->levels[i]->difficulty = packet->data; diff --git a/Minecraft.Client/ServerLevel.cpp b/Minecraft.Client/ServerLevel.cpp index 242a0df91..a2596911d 100644 --- a/Minecraft.Client/ServerLevel.cpp +++ b/Minecraft.Client/ServerLevel.cpp @@ -42,7 +42,7 @@ WeighedTreasureArray ServerLevel::RANDOM_BONUS_ITEMS; -C4JThread* ServerLevel::m_updateThread = NULL; +C4JThread* ServerLevel::m_updateThread = nullptr; C4JThread::EventArray* ServerLevel::m_updateTrigger; CRITICAL_SECTION ServerLevel::m_updateCS[3]; @@ -63,7 +63,7 @@ void ServerLevel::staticCtor() InitializeCriticalSection(&m_updateCS[1]); InitializeCriticalSection(&m_updateCS[2]); - m_updateThread = new C4JThread(runUpdate, NULL, "Tile update"); + m_updateThread = new C4JThread(runUpdate, nullptr, "Tile update"); m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE); #ifdef __ORBIS__ m_updateThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. @@ -123,7 +123,7 @@ ServerLevel::ServerLevel(MinecraftServer *server, shared_ptrlevelS scoreboard = new ServerScoreboard(server); //shared_ptr scoreboardSaveData = dynamic_pointer_cast( savedDataStorage->get(typeid(ScoreboardSaveData), ScoreboardSaveData::FILE_ID) ); - //if (scoreboardSaveData == NULL) + //if (scoreboardSaveData == nullptr) //{ // scoreboardSaveData = shared_ptr( new ScoreboardSaveData() ); // savedDataStorage->set(ScoreboardSaveData::FILE_ID, scoreboardSaveData); @@ -256,9 +256,8 @@ void ServerLevel::tick() if (time % (saveInterval) == (dimension->id * dimension->id * (saveInterval/2))) #endif { - //app.DebugPrintf("Incremental save\n"); PIXBeginNamedEvent(0,"Incremental save"); - save(false, NULL); + save(false, nullptr); PIXEndNamedEvent(); } @@ -313,9 +312,9 @@ void ServerLevel::tick() Biome::MobSpawnerData *ServerLevel::getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z) { vector *mobList = getChunkSource()->getMobsAt(mobCategory, x, y, z); - if (mobList == NULL || mobList->empty()) return NULL; + if (mobList == nullptr || mobList->empty()) return nullptr; - return (Biome::MobSpawnerData *) WeighedRandom::getRandomItem(random, (vector *)mobList); + return static_cast(WeighedRandom::getRandomItem(random, (vector *)mobList)); } void ServerLevel::updateSleepingPlayerList() @@ -433,7 +432,7 @@ void ServerLevel::tickTiles() if( hasChunkAt(x,y,z) ) { int id = getTile(x,y,z); - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking()) + if (Tile::tiles[id] != nullptr && Tile::tiles[id]->isTicking()) { /*if(id == 2) ++grassTicks; else if(id == 11) ++lavaTicks; @@ -497,7 +496,7 @@ void ServerLevel::tickTiles() if (isRainingAt(x, y, z)) { - addGlobalEntity( shared_ptr( new LightningBolt(this, x, y, z) ) ); + addGlobalEntity(std::make_shared(this, x, y, z)); } } @@ -640,8 +639,8 @@ void ServerLevel::resetEmptyTime() bool ServerLevel::tickPendingTicks(bool force) { EnterCriticalSection(&m_tickNextTickCS); - int count = (int)tickNextTickList.size(); - int count2 = (int)tickNextTickSet.size(); + int count = static_cast(tickNextTickList.size()); + int count2 = static_cast(tickNextTickSet.size()); if (count != tickNextTickSet.size()) { // TODO 4J Stu - Add new exception types @@ -685,8 +684,8 @@ bool ServerLevel::tickPendingTicks(bool force) toBeTicked.clear(); - int count3 = (int)tickNextTickList.size(); - int count4 = (int)tickNextTickSet.size(); + int count3 = static_cast(tickNextTickList.size()); + int count4 = static_cast(tickNextTickSet.size()); bool retval = tickNextTickList.size() != 0; LeaveCriticalSection(&m_tickNextTickCS); @@ -776,7 +775,7 @@ void ServerLevel::tick(shared_ptr e, bool actual) { e->remove(); } - if (!server->isNpcsEnabled() && (dynamic_pointer_cast(e) != NULL)) + if (!server->isNpcsEnabled() && (dynamic_pointer_cast(e) != nullptr)) { e->remove(); } @@ -860,7 +859,7 @@ void ServerLevel::setInitialSpawn(LevelSettings *levelSettings) int minXZ = - (dimension->getXZSize() * 16 ) / 2; int maxXZ = (dimension->getXZSize() * 16 ) / 2 - 1; - if (findBiome != NULL) + if (findBiome != nullptr) { xSpawn = findBiome->x; zSpawn = findBiome->z; @@ -914,7 +913,7 @@ void ServerLevel::generateBonusItemsNearSpawn() if( getTile( x, y, z ) == Tile::chest_Id ) { shared_ptr chest = dynamic_pointer_cast(getTileEntity(x, y, z)); - if (chest != NULL) + if (chest != nullptr) { if( chest->isBonusChest ) { @@ -960,7 +959,7 @@ void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAut if(StorageManager.GetSaveDisabled()) return; - if (progressListener != NULL) + if (progressListener != nullptr) { if(bAutosave) { @@ -976,7 +975,7 @@ void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAut saveLevelData(); PIXEndNamedEvent(); - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); + if (progressListener != nullptr) progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); #if defined(_XBOX_ONE) || defined(__ORBIS__) // Our autosave is a minimal save. All the chunks are saves by the constant save process @@ -1009,7 +1008,7 @@ void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAut //if( force && !isClientSide ) //{ - // if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + // if (progressListener != nullptr) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); // levelStorage->flushSaveFile(); //} } @@ -1024,7 +1023,7 @@ void ServerLevel::saveToDisc(ProgressListener *progressListener, bool autosave) if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + DLCTexturePack *pDLCTexPack=static_cast(tPack); DLCPack * pDLCPack=pDLCTexPack->getDLCInfoParentPack(); @@ -1034,7 +1033,7 @@ void ServerLevel::saveToDisc(ProgressListener *progressListener, bool autosave) } } - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + if (progressListener != nullptr) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); levelStorage->flushSaveFile(autosave); } @@ -1078,14 +1077,19 @@ void ServerLevel::entityRemoved(shared_ptr e) shared_ptr ServerLevel::getEntity(int id) { - return entitiesById[id]; + auto it = entitiesById.find(id); + if (it != entitiesById.end()) + { + return it->second; + } + return nullptr; } bool ServerLevel::addGlobalEntity(shared_ptr e) { if (Level::addGlobalEntity(e)) { - server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, shared_ptr( new AddGlobalEntityPacket(e) ) ); + server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, std::make_shared(e)); return true; } return false; @@ -1093,7 +1097,7 @@ bool ServerLevel::addGlobalEntity(shared_ptr e) void ServerLevel::broadcastEntityEvent(shared_ptr e, byte event) { - shared_ptr p = shared_ptr( new EntityEventPacket(e->entityId, event) ); + shared_ptr p = std::make_shared(e->entityId, event); server->getLevel(dimension->id)->getTracker()->broadcastAndSend(e, p); } @@ -1101,7 +1105,7 @@ shared_ptr ServerLevel::explode(shared_ptr source, double x, { // instead of calling super, we run the same explosion code here except // we don't generate any particles - shared_ptr explosion = shared_ptr( new Explosion(this, source, x, y, z, r) ); + shared_ptr explosion = std::make_shared(this, source, x, y, z, r); explosion->fire = fire; explosion->destroyBlocks = destroyBlocks; explosion->explode(); @@ -1122,7 +1126,7 @@ shared_ptr ServerLevel::explode(shared_ptr source, double x, if( sentTo.size() ) { INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) + if( thisPlayer == nullptr ) { continue; } @@ -1131,7 +1135,7 @@ shared_ptr ServerLevel::explode(shared_ptr source, double x, for(auto& player2 : sentTo) { INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { knockbackOnly = true; } @@ -1144,7 +1148,7 @@ shared_ptr ServerLevel::explode(shared_ptr source, double x, Vec3 *knockbackVec = explosion->getHitPlayerKnockback(player); //app.DebugPrintf("Sending %s with knockback (%f,%f,%f)\n", knockbackOnly?"knockbackOnly":"allExplosion",knockbackVec->x,knockbackVec->y,knockbackVec->z); // If the player is not the primary on the system, then we only want to send info for the knockback - player->connection->send( shared_ptr( new ExplodePacket(x, y, z, r, &explosion->toBlow, knockbackVec, knockbackOnly))); + player->connection->send(std::make_shared(x, y, z, r, &explosion->toBlow, knockbackVec, knockbackOnly)); sentTo.push_back( player ); } } @@ -1182,7 +1186,7 @@ void ServerLevel::runTileEvents() if (doTileEvent(&it)) { TileEventData te = it; - server->getPlayers()->broadcast(te.getX(), te.getY(), te.getZ(), 64, dimension->id, shared_ptr( new TileEventPacket(te.getX(), te.getY(), te.getZ(), te.getTile(), te.getParamA(), te.getParamB()))); + server->getPlayers()->broadcast(te.getX(), te.getY(), te.getZ(), 64, dimension->id, std::make_shared(te.getX(), te.getY(), te.getZ(), te.getTile(), te.getParamA(), te.getParamB())); } } tileEvents[runList].clear(); @@ -1212,11 +1216,11 @@ void ServerLevel::tickWeather() { if (wasRaining) { - server->getPlayers()->broadcastAll( shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); + server->getPlayers()->broadcastAll(std::make_shared(GameEventPacket::STOP_RAINING, 0)); } else { - server->getPlayers()->broadcastAll( shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + server->getPlayers()->broadcastAll(std::make_shared(GameEventPacket::START_RAINING, 0)); } } @@ -1268,7 +1272,7 @@ 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 = std::make_shared( name, (float) x, (float) y, (float) z, (float) xDist, (float) yDist, (float) zDist, (float) speed, count ); + shared_ptr packet = std::make_shared( name, static_cast(x), static_cast(y), static_cast(z), static_cast(xDist), static_cast(yDist), static_cast(zDist), static_cast(speed), count ); for(auto& it : players) { @@ -1578,7 +1582,7 @@ int ServerLevel::runUpdate(void* lpParam) if( (id == Tile::grass_Id && grassTicks >= MAX_GRASS_TICKS) || (id == Tile::calmLava_Id && lavaTicks >= MAX_LAVA_TICKS) ) continue; // 4J Stu - Added shouldTileTick as some tiles won't even do anything if they are set to tick and use up one of our updates - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking() && Tile::tiles[id]->shouldTileTick(m_level[iLev],x + (cx * 16), y, z + (cz * 16) ) ) + if (Tile::tiles[id] != nullptr && Tile::tiles[id]->isTicking() && Tile::tiles[id]->shouldTileTick(m_level[iLev],x + (cx * 16), y, z + (cz * 16) ) ) { if(id == Tile::grass_Id) ++grassTicks; else if(id == Tile::calmLava_Id) ++lavaTicks; diff --git a/Minecraft.Client/ServerLevelListener.cpp b/Minecraft.Client/ServerLevelListener.cpp index c191b1a95..3884b4696 100644 --- a/Minecraft.Client/ServerLevelListener.cpp +++ b/Minecraft.Client/ServerLevelListener.cpp @@ -117,9 +117,9 @@ void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, int p for(auto& p : server->getPlayers()->players) { 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; + double xd = static_cast(x) - p->x; + double yd = static_cast(y) - p->y; + double zd = static_cast(z) - p->z; if (xd * xd + yd * yd + zd * zd < 32 * 32) { diff --git a/Minecraft.Client/ServerPlayer.cpp b/Minecraft.Client/ServerPlayer.cpp index 789b31766..f57e8a3c9 100644 --- a/Minecraft.Client/ServerPlayer.cpp +++ b/Minecraft.Client/ServerPlayer.cpp @@ -101,7 +101,7 @@ ServerPlayer::ServerPlayer(MinecraftServer *server, Level *level, const wstring& waterDepth++; } attemptCount++; - playerNear = ( level->getNearestPlayer(xx + 0.5, yy, zz + 0.5,3) != NULL ); + playerNear = ( level->getNearestPlayer(xx + 0.5, yy, zz + 0.5,3) != nullptr ); } while ( ( waterDepth > 1 ) && (!playerNear) && ( attemptCount < 20 ) ); xx = xx2; yy = yy2; @@ -146,7 +146,8 @@ void ServerPlayer::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFou if( ( *removedFound ) == false ) { *removedFound = true; - memset(flags, 0, 2048/32); + // before this left 192 bytes uninitialized!!!!! + memset(flags, 0, (2048 / 32) * sizeof(unsigned int)); } for(int index : entitiesToRemove) @@ -180,7 +181,7 @@ void ServerPlayer::readAdditionalSaveData(CompoundTag *entityTag) } GameRulesInstance *grs = gameMode->getGameRules(); - if (entityTag->contains(L"GameRules") && grs != NULL) + if (entityTag->contains(L"GameRules") && grs != nullptr) { byteArray ba = entityTag->getByteArray(L"GameRules"); ByteArrayInputStream bais(ba); @@ -197,13 +198,13 @@ void ServerPlayer::addAdditonalSaveData(CompoundTag *entityTag) Player::addAdditonalSaveData(entityTag); GameRulesInstance *grs = gameMode->getGameRules(); - if (grs != NULL) + if (grs != nullptr) { ByteArrayOutputStream baos; DataOutputStream dos(&baos); grs->write(&dos); entityTag->putByteArray(L"GameRules", baos.buf); - baos.buf.data = NULL; + baos.buf.data = nullptr; dos.close(); baos.close(); } @@ -280,7 +281,7 @@ void ServerPlayer::flushEntitiesToRemove() it = entitiesToRemove.erase(it); } - connection->send(shared_ptr(new RemoveEntitiesPacket(ids))); + connection->send(std::make_shared(ids)); } } @@ -308,14 +309,14 @@ void ServerPlayer::doTickA() for (unsigned int i = 0; i < inventory->getContainerSize(); i++) { shared_ptr ie = inventory->getItem(i); - if (ie != NULL) + if (ie != nullptr) { // 4J - removed condition. These were getting lower priority than tile update packets etc. on the slow outbound queue, and so were extremely slow to send sometimes, // particularly at the start of a game. They don't typically seem to be massive and shouldn't be send when there isn't actually any updating to do. if (Item::items[ie->id]->isComplex() ) // && connection->countDelayedPackets() <= 2) { shared_ptr packet = (dynamic_cast(Item::items[ie->id])->getUpdatePacket(ie, level, dynamic_pointer_cast( shared_from_this() ) ) ); - if (packet != NULL) + if (packet != nullptr) { connection->send(packet); } @@ -352,7 +353,7 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) } } - // if (nearest != NULL) // 4J - removed as we don't have references here + // if (nearest != nullptr) // 4J - removed as we don't have references here if( nearestValid ) { bool okToSend = false; @@ -372,39 +373,43 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) // app.DebugPrintf("%d: canSendToPlayer %d, countDelayedPackets %d GetSendQueueSizeBytes %d done: %d\n", // connection->getNetworkPlayer()->GetSmallId(), // canSendToPlayer, connection->countDelayedPackets(), -// g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ), +// g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( nullptr, true ), // connection->done); // } +#ifdef MINECRAFT_SERVER_BUILD + if (dontDelayChunks || (canSendToPlayer && !connection->done)) +#else 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 // both together then bytes provides a better metric than count of data items to determine if we should avoid queueing too much up - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( NULL, true ) < 8192 )&& + (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( nullptr, true ) < 8192 )&& #elif defined _XBOX - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ) < 4 )&& + (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( nullptr, true ) < 4 )&& #else (connection->countDelayedPackets() < 4 )&& - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ) < 4 )&& + (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( nullptr, true ) < 4 )&& #endif //(tickCount - lastBrupSendTickCount) > (connection->getNetworkPlayer()->GetCurrentRtt()>>4) && !connection->done) ) - { - lastBrupSendTickCount = tickCount; - okToSend = true; - MinecraftServer::chunkPacketManagement_DidSendTo(connection->getNetworkPlayer()); +#endif + { + lastBrupSendTickCount = tickCount; + okToSend = true; + MinecraftServer::chunkPacketManagement_DidSendTo(connection->getNetworkPlayer()); -// static unordered_map mapLastTime; -// int64_t thisTime = System::currentTimeMillis(); -// int64_t lastTime = mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; -// app.DebugPrintf(" - OK to send (%d ms since last)\n", thisTime - lastTime); -// mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] = thisTime; - } - else - { - // app.DebugPrintf(" - \n"); - } + // static unordered_map mapLastTime; + // int64_t thisTime = System::currentTimeMillis(); + // int64_t lastTime = mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; + // app.DebugPrintf(" - OK to send (%d ms since last)\n", thisTime - lastTime); + // mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] = thisTime; + } + else + { + // app.DebugPrintf(" - \n"); + } } if (okToSend) @@ -426,10 +431,9 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) // unloaded on the client and so just gradually build up more and more of the finite set of chunks as the player moves if( !g_NetworkManager.SystemFlagGet(connection->getNetworkPlayer(),flagIndex) ) { - // app.DebugPrintf("Creating BRUP for %d %d\n",nearest.x, nearest.z); PIXBeginNamedEvent(0,"Creation BRUP for sending\n"); int64_t before = System::currentTimeMillis(); - shared_ptr packet = shared_ptr( new BlockRegionUpdatePacket(nearest.x * 16, 0, nearest.z * 16, 16, Level::maxBuildHeight, 16, level) ); + const auto packet = std::make_shared(nearest.x * 16, 0, nearest.z * 16, 16, Level::maxBuildHeight, 16, level); int64_t after = System::currentTimeMillis(); // app.DebugPrintf(">>><<< %d ms\n",after-before); PIXEndNamedEvent(); @@ -523,7 +527,7 @@ void ServerPlayer::doTickB() if (getHealth() != lastSentHealth || lastSentFood != foodData.getFoodLevel() || ((foodData.getSaturationLevel() == 0) != lastFoodSaturationZero)) { // 4J Stu - Added m_lastDamageSource for telemetry - connection->send( shared_ptr( new SetHealthPacket(getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), m_lastDamageSource) ) ); + connection->send(std::make_shared(getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), m_lastDamageSource)); lastSentHealth = getHealth(); lastSentFood = foodData.getFoodLevel(); lastFoodSaturationZero = foodData.getSaturationLevel() == 0; @@ -550,7 +554,7 @@ void ServerPlayer::doTickB() if (totalExperience != lastSentExp) { lastSentExp = totalExperience; - connection->send( shared_ptr( new SetExperiencePacket(experienceProgress, totalExperience, experienceLevel) ) ); + connection->send(std::make_shared(experienceProgress, totalExperience, experienceLevel)); } } @@ -584,7 +588,7 @@ void ServerPlayer::die(DamageSource *source) } shared_ptr killer = getKillCredit(); - if (killer != NULL) killer->awardKillScore(shared_from_this(), deathScore); + if (killer != nullptr) killer->awardKillScore(shared_from_this(), deathScore); //awardStat(Stats::deaths, 1); } @@ -597,10 +601,10 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) //bool allowFallDamage = server->isPvpAllowed() && server->isDedicatedServer() && server->isPvpAllowed() && (dmgSource->msgId.compare(L"fall") == 0); if (!server->isPvpAllowed() && invulnerableTime > 0 && dmgSource != DamageSource::outOfWorld) return false; - if (dynamic_cast(dmgSource) != NULL) + if (dynamic_cast(dmgSource) != nullptr) { // 4J Stu - Fix for #46422 - TU5: Crash: Gameplay: Crash when being hit by a trap using a dispenser - // getEntity returns the owner of projectiles, and this would never be the arrow. The owner is sometimes NULL. + // getEntity returns the owner of projectiles, and this would never be the arrow. The owner is sometimes nullptr. shared_ptr source = dmgSource->getDirectEntity(); if (source->instanceof(eTYPE_PLAYER) && !dynamic_pointer_cast(source)->canHarmPlayer(dynamic_pointer_cast(shared_from_this()))) @@ -608,10 +612,10 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) return false; } - if ( (source != NULL) && source->instanceof(eTYPE_ARROW) ) + if ( (source != nullptr) && source->instanceof(eTYPE_ARROW) ) { shared_ptr arrow = dynamic_pointer_cast(source); - if ( (arrow->owner != NULL) && arrow->owner->instanceof(eTYPE_PLAYER) && !canHarmPlayer(dynamic_pointer_cast(arrow->owner)) ) + if ( (arrow->owner != nullptr) && arrow->owner->instanceof(eTYPE_PLAYER) && !canHarmPlayer(dynamic_pointer_cast(arrow->owner)) ) { return false; } @@ -634,7 +638,7 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) else { shared_ptr source = dmgSource->getEntity(); - if( source != NULL ) + if( source != nullptr ) { switch(source->GetType()) { @@ -670,10 +674,10 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) m_lastDamageSource = eTelemetryPlayerDeathSource_Explosion_Tnt; break; case eTYPE_ARROW: - if ((dynamic_pointer_cast(source))->owner != NULL) + if ((dynamic_pointer_cast(source))->owner != nullptr) { shared_ptr attacker = (dynamic_pointer_cast(source))->owner; - if (attacker != NULL) + if (attacker != nullptr) { switch(attacker->GetType()) { @@ -712,7 +716,7 @@ bool ServerPlayer::canHarmPlayer(wstring targetName) bool canHarm = true; shared_ptr owner = server->getPlayers()->getPlayer(targetName); - if (owner != NULL) + if (owner != nullptr) { if ((shared_from_this() != owner) && canHarmPlayer(owner)) canHarm = false; } @@ -741,7 +745,7 @@ void ServerPlayer::changeDimension(int i) level->removeEntity(shared_from_this()); wonGame = true; m_enteredEndExitPortal = true; // We only flag this for the player in the portal - connection->send( shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()) ) ); + connection->send(std::make_shared(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex())); app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); } if(thisPlayer) @@ -749,10 +753,10 @@ void ServerPlayer::changeDimension(int i) for(auto& servPlayer : MinecraftServer::getInstance()->getPlayers()->players) { INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && !servPlayer->wonGame ) + if(thisPlayer != checkPlayer && checkPlayer != nullptr && thisPlayer->IsSameSystem( checkPlayer ) && !servPlayer->wonGame ) { servPlayer->wonGame = true; - servPlayer->connection->send( shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex() ) ) ); + servPlayer->connection->send(std::make_shared(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex())); app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); } } @@ -766,7 +770,7 @@ void ServerPlayer::changeDimension(int i) awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); Pos *pos = server->getLevel(i)->getDimensionSpecificSpawn(); - if (pos != NULL) + if (pos != nullptr) { connection->teleport(pos->x, pos->y, pos->z, 0, 0); delete pos; @@ -789,10 +793,10 @@ void ServerPlayer::changeDimension(int i) // 4J Added delay param void ServerPlayer::broadcast(shared_ptr te, bool delay /*= false*/) { - if (te != NULL) + if (te != nullptr) { shared_ptr p = te->getUpdatePacket(); - if (p != NULL) + if (p != nullptr) { p->shouldDelay = delay; if(delay) connection->queueSend(p); @@ -812,7 +816,7 @@ Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, boo BedSleepingResult result = Player::startSleepInBed(x, y, z, bTestUse); if (result == OK) { - shared_ptr p = shared_ptr( new EntityActionAtPositionPacket(shared_from_this(), EntityActionAtPositionPacket::START_SLEEP, x, y, z) ); + shared_ptr p = std::make_shared(shared_from_this(), EntityActionAtPositionPacket::START_SLEEP, x, y, z); getLevel()->getTracker()->broadcast(shared_from_this(), p); connection->teleport(this->x, this->y, this->z, yRot, xRot); connection->send(p); @@ -824,16 +828,16 @@ void ServerPlayer::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, boo { if (isSleeping()) { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::WAKE_UP) ) ); + getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::make_shared(shared_from_this(), AnimatePacket::WAKE_UP)); } Player::stopSleepInBed(forcefulWakeUp, updateLevelList, saveRespawnPoint); - if (connection != NULL) connection->teleport(x, y, z, yRot, xRot); + if (connection != nullptr) connection->teleport(x, y, z, yRot, xRot); } void ServerPlayer::ride(shared_ptr e) { Player::ride(e); - connection->send( shared_ptr( new SetEntityLinkPacket(SetEntityLinkPacket::RIDING, shared_from_this(), riding) ) ); + connection->send(std::make_shared(SetEntityLinkPacket::RIDING, shared_from_this(), riding)); // 4J Removed this - The act of riding will be handled on the client and will change the position // of the player. If we also teleport it then we can end up with a repeating movements, e.g. bouncing @@ -853,10 +857,10 @@ void ServerPlayer::doCheckFallDamage(double ya, bool onGround) void ServerPlayer::openTextEdit(shared_ptr sign) { shared_ptr signTE = dynamic_pointer_cast(sign); - if (signTE != NULL) + if (signTE != nullptr) { signTE->setAllowedPlayerEditor(dynamic_pointer_cast(shared_from_this())); - connection->send( shared_ptr( new TileEditorOpenPacket(TileEditorOpenPacket::SIGN, sign->x, sign->y, sign->z)) ); + connection->send(std::make_shared(TileEditorOpenPacket::SIGN, sign->x, sign->y, sign->z)); } } @@ -870,7 +874,7 @@ bool ServerPlayer::startCrafting(int x, int y, int z) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::WORKBENCH, L"", 9, false) ) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::WORKBENCH, L"", 9, false)); containerMenu = new CraftingMenu(inventory, level, x, y, z); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -888,17 +892,17 @@ bool ServerPlayer::openFireworks(int x, int y, int z) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::FIREWORKS, L"", 9, false) ) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::FIREWORKS, L"", 9, false)); containerMenu = new FireworksMenu(inventory, level, x, y, z); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); } - else if(dynamic_cast(containerMenu) != NULL) + else if(dynamic_cast(containerMenu) != nullptr) { closeContainer(); nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::FIREWORKS, L"", 9, false) ) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::FIREWORKS, L"", 9, false)); containerMenu = new FireworksMenu(inventory, level, x, y, z); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -916,7 +920,7 @@ bool ServerPlayer::startEnchanting(int x, int y, int z, const wstring &name) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send(shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::ENCHANTMENT, name.empty()? L"" : name, 9, !name.empty() ) )); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::ENCHANTMENT, name.empty() ? L"" : name, 9, !name.empty())); containerMenu = new EnchantmentMenu(inventory, level, x, y, z); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -934,7 +938,7 @@ bool ServerPlayer::startRepairing(int x, int y, int z) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send(shared_ptr ( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::REPAIR_TABLE, L"", 9, false)) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::REPAIR_TABLE, L"", 9, false)); containerMenu = new AnvilMenu(inventory, level, x, y, z, dynamic_pointer_cast(shared_from_this())); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -957,7 +961,7 @@ bool ServerPlayer::openContainer(shared_ptr container) int containerType = container->getContainerType(); assert(containerType >= 0); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, containerType, container->getCustomName(), container->getContainerSize(), container->hasCustomName()) ) ); + connection->send(std::make_shared(containerCounter, containerType, container->getCustomName(), container->getContainerSize(), container->hasCustomName())); containerMenu = new ContainerMenu(inventory, container); containerMenu->containerId = containerCounter; @@ -976,7 +980,7 @@ bool ServerPlayer::openHopper(shared_ptr container) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::HOPPER, container->getCustomName(), container->getContainerSize(), container->hasCustomName())) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::HOPPER, container->getCustomName(), container->getContainerSize(), container->hasCustomName())); containerMenu = new HopperMenu(inventory, container); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -994,7 +998,7 @@ bool ServerPlayer::openHopper(shared_ptr container) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::HOPPER, container->getCustomName(), container->getContainerSize(), container->hasCustomName())) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::HOPPER, container->getCustomName(), container->getContainerSize(), container->hasCustomName())); containerMenu = new HopperMenu(inventory, container); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1012,7 +1016,7 @@ bool ServerPlayer::openFurnace(shared_ptr furnace) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::FURNACE, furnace->getCustomName(), furnace->getContainerSize(), furnace->hasCustomName()) ) ); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::FURNACE, furnace->getCustomName(), furnace->getContainerSize(), furnace->hasCustomName())); containerMenu = new FurnaceMenu(inventory, furnace); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1030,7 +1034,7 @@ bool ServerPlayer::openTrap(shared_ptr trap) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send( shared_ptr( new ContainerOpenPacket(containerCounter, trap->GetType() == eTYPE_DROPPERTILEENTITY ? ContainerOpenPacket::DROPPER : ContainerOpenPacket::TRAP, trap->getCustomName(), trap->getContainerSize(), trap->hasCustomName() ) ) ); + connection->send(std::make_shared(containerCounter, trap->GetType() == eTYPE_DROPPERTILEENTITY ? ContainerOpenPacket::DROPPER : ContainerOpenPacket::TRAP, trap->getCustomName(), trap->getContainerSize(), trap->hasCustomName())); containerMenu = new TrapMenu(inventory, trap); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1048,7 +1052,7 @@ bool ServerPlayer::openBrewingStand(shared_ptr brewingSt if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send(shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::BREWING_STAND, brewingStand->getCustomName(), brewingStand->getContainerSize(), brewingStand->hasCustomName() ))); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::BREWING_STAND, brewingStand->getCustomName(), brewingStand->getContainerSize(), brewingStand->hasCustomName())); containerMenu = new BrewingStandMenu(inventory, brewingStand); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1066,7 +1070,7 @@ bool ServerPlayer::openBeacon(shared_ptr beacon) if(containerMenu == inventoryMenu) { nextContainerCounter(); - connection->send(shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::BEACON, beacon->getCustomName(), beacon->getContainerSize(), beacon->hasCustomName() ))); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::BEACON, beacon->getCustomName(), beacon->getContainerSize(), beacon->hasCustomName())); containerMenu = new BeaconMenu(inventory, beacon); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1087,12 +1091,12 @@ bool ServerPlayer::openTrading(shared_ptr traderTarget, const wstring containerMenu = new MerchantMenu(inventory, traderTarget, level); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); - shared_ptr container = ((MerchantMenu *) containerMenu)->getTradeContainer(); + shared_ptr container = static_cast(containerMenu)->getTradeContainer(); - connection->send(shared_ptr(new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRADER_NPC, name.empty()?L"":name, container->getContainerSize(), !name.empty()))); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::TRADER_NPC, name.empty() ? L"" : name, container->getContainerSize(), !name.empty())); MerchantRecipeList *offers = traderTarget->getOffers(dynamic_pointer_cast(shared_from_this())); - if (offers != NULL) + if (offers != nullptr) { ByteArrayOutputStream rawOutput; DataOutputStream output(&rawOutput); @@ -1101,7 +1105,7 @@ bool ServerPlayer::openTrading(shared_ptr traderTarget, const wstring output.writeInt(containerCounter); offers->writeToStream(&output); - connection->send(shared_ptr( new CustomPayloadPacket(CustomPayloadPacket::TRADER_LIST_PACKET, rawOutput.toByteArray()))); + connection->send(std::make_shared(CustomPayloadPacket::TRADER_LIST_PACKET, rawOutput.toByteArray())); } } else @@ -1119,7 +1123,7 @@ bool ServerPlayer::openHorseInventory(shared_ptr horse, shared_ptr< closeContainer(); } nextContainerCounter(); - connection->send(shared_ptr(new ContainerOpenPacket(containerCounter, ContainerOpenPacket::HORSE, horse->getCustomName(), container->getContainerSize(), container->hasCustomName(), horse->entityId ))); + connection->send(std::make_shared(containerCounter, ContainerOpenPacket::HORSE, horse->getCustomName(), container->getContainerSize(), container->hasCustomName(), horse->entityId)); containerMenu = new HorseInventoryMenu(inventory, container, horse); containerMenu->containerId = containerCounter; containerMenu->addSlotListener(this); @@ -1144,7 +1148,7 @@ void ServerPlayer::slotChanged(AbstractContainerMenu *container, int slotIndex, return; } - connection->send( shared_ptr( new ContainerSetSlotPacket(container->containerId, slotIndex, item) ) ); + connection->send(std::make_shared(container->containerId, slotIndex, item)); } @@ -1157,8 +1161,8 @@ void ServerPlayer::refreshContainer(AbstractContainerMenu *menu) void ServerPlayer::refreshContainer(AbstractContainerMenu *container, vector > *items) { - connection->send( shared_ptr( new ContainerSetContentPacket(container->containerId, items) ) ); - connection->send( shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); + connection->send(std::make_shared(container->containerId, items)); + connection->send(std::make_shared(-1, -1, inventory->getCarried())); } void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, int value) @@ -1173,12 +1177,12 @@ void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, in // client again. return; } - connection->send( shared_ptr( new ContainerSetDataPacket(container->containerId, id, value) ) ); + connection->send(std::make_shared(container->containerId, id, value)); } void ServerPlayer::closeContainer() { - connection->send( shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); + connection->send(std::make_shared(containerMenu->containerId)); doCloseContainer(); } @@ -1192,7 +1196,7 @@ void ServerPlayer::broadcastCarriedItem() // client again. return; } - connection->send( shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); + connection->send(std::make_shared(-1, -1, inventory->getCarried())); } void ServerPlayer::doCloseContainer() @@ -1203,7 +1207,7 @@ void ServerPlayer::doCloseContainer() void ServerPlayer::setPlayerInput(float xxa, float yya, bool jumping, bool sneaking) { - if(riding != NULL) + if(riding != nullptr) { if (xxa >= -1 && xxa <= 1) this->xxa = xxa; if (yya >= -1 && yya <= 1) this->yya = yya; @@ -1214,7 +1218,7 @@ void ServerPlayer::setPlayerInput(float xxa, float yya, bool jumping, bool sneak void ServerPlayer::awardStat(Stat *stat, byteArray param) { - if (stat == NULL) + if (stat == nullptr) { delete [] param.data; return; @@ -1226,7 +1230,7 @@ void ServerPlayer::awardStat(Stat *stat, byteArray param) int count = *((int*)param.data); delete [] param.data; - connection->send( shared_ptr( new AwardStatPacket(stat->id, count) ) ); + connection->send(std::make_shared(stat->id, count)); #else connection->send( shared_ptr( new AwardStatPacket(stat->id, param) ) ); // byteArray deleted in AwardStatPacket destructor. @@ -1237,7 +1241,7 @@ void ServerPlayer::awardStat(Stat *stat, byteArray param) void ServerPlayer::disconnect() { - if (rider.lock() != NULL) rider.lock()->ride(shared_from_this() ); + if (rider.lock() != nullptr) rider.lock()->ride(shared_from_this() ); if (m_isSleeping) { stopSleepInBed(true, false, false); @@ -1257,19 +1261,19 @@ void ServerPlayer::displayClientMessage(int messageId) { case IDS_TILE_BED_OCCUPIED: messageType = ChatPacket::e_ChatBedOccupied; - connection->send( shared_ptr( new ChatPacket(L"", messageType) ) ); + connection->send(std::make_shared(L"", messageType)); break; case IDS_TILE_BED_NO_SLEEP: messageType = ChatPacket::e_ChatBedNoSleep; - connection->send( shared_ptr( new ChatPacket(L"", messageType) ) ); + connection->send(std::make_shared(L"", messageType)); break; case IDS_TILE_BED_NOT_VALID: messageType = ChatPacket::e_ChatBedNotValid; - connection->send( shared_ptr( new ChatPacket(L"", messageType) ) ); + connection->send(std::make_shared(L"", messageType)); break; case IDS_TILE_BED_NOTSAFE: messageType = ChatPacket::e_ChatBedNotSafe; - connection->send( shared_ptr( new ChatPacket(L"", messageType) ) ); + connection->send(std::make_shared(L"", messageType)); break; case IDS_TILE_BED_PLAYERSLEEP: messageType = ChatPacket::e_ChatBedPlayerSleep; @@ -1279,11 +1283,11 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()!=player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedPlayerSleep))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatBedPlayerSleep)); } else { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedMeSleep))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatBedMeSleep)); } } return; @@ -1294,7 +1298,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()!=player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerEnteredEnd))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerEnteredEnd)); } } break; @@ -1304,13 +1308,13 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()!=player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerLeftEnd))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerLeftEnd)); } } break; case IDS_TILE_BED_MESLEEP: messageType = ChatPacket::e_ChatBedMeSleep; - connection->send( shared_ptr( new ChatPacket(L"", messageType) ) ); + connection->send(std::make_shared(L"", messageType)); break; case IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED: @@ -1319,7 +1323,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxPigsSheepCows))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxPigsSheepCows)); } } break; @@ -1329,7 +1333,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxChickens))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxChickens)); } } break; @@ -1339,7 +1343,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxSquid))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxSquid)); } } break; @@ -1349,7 +1353,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBats))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBats)); } } break; @@ -1359,7 +1363,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxWolves))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxWolves)); } } break; @@ -1369,7 +1373,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxMooshrooms))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxMooshrooms)); } } break; @@ -1379,7 +1383,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxEnemies))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxEnemies)); } } break; @@ -1390,7 +1394,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxVillagers))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxVillagers)); } } break; @@ -1400,7 +1404,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows)); } } break; @@ -1410,7 +1414,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredChickens))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBredChickens)); } } break; @@ -1420,7 +1424,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms)); } } break; @@ -1431,7 +1435,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredWolves))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBredWolves)); } } break; @@ -1442,7 +1446,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantShearMooshroom))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerCantShearMooshroom)); } } break; @@ -1454,7 +1458,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxHangingEntities))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxHangingEntities)); } } break; @@ -1464,7 +1468,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerCantSpawnInPeaceful)); } } break; @@ -1475,7 +1479,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBoats))); + player->connection->send(std::make_shared(name, ChatPacket::e_ChatPlayerMaxBoats)); } } break; @@ -1493,7 +1497,7 @@ void ServerPlayer::displayClientMessage(int messageId) void ServerPlayer::completeUsingItem() { - connection->send(shared_ptr( new EntityEventPacket(entityId, EntityEvent::USE_ITEM_COMPLETE) ) ); + connection->send(std::make_shared(entityId, EntityEvent::USE_ITEM_COMPLETE)); Player::completeUsingItem(); } @@ -1501,9 +1505,9 @@ void ServerPlayer::startUsingItem(shared_ptr instance, int duratio { Player::startUsingItem(instance, duration); - if (instance != NULL && instance->getItem() != NULL && instance->getItem()->getUseAnimation(instance) == UseAnim_eat) + if (instance != nullptr && instance->getItem() != nullptr && instance->getItem()->getUseAnimation(instance) == UseAnim_eat) { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::EAT) ) ); + getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::make_shared(shared_from_this(), AnimatePacket::EAT)); } } @@ -1519,21 +1523,21 @@ void ServerPlayer::restoreFrom(shared_ptr oldPlayer, bool restoreAll) void ServerPlayer::onEffectAdded(MobEffectInstance *effect) { Player::onEffectAdded(effect); - connection->send(shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); + connection->send(std::make_shared(entityId, effect)); } void ServerPlayer::onEffectUpdated(MobEffectInstance *effect, bool doRefreshAttributes) { Player::onEffectUpdated(effect, doRefreshAttributes); - connection->send(shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); + connection->send(std::make_shared(entityId, effect)); } void ServerPlayer::onEffectRemoved(MobEffectInstance *effect) { Player::onEffectRemoved(effect); - connection->send(shared_ptr( new RemoveMobEffectPacket(entityId, effect) ) ); + connection->send(std::make_shared(entityId, effect)); } void ServerPlayer::teleportTo(double x, double y, double z) @@ -1543,34 +1547,34 @@ void ServerPlayer::teleportTo(double x, double y, double z) void ServerPlayer::crit(shared_ptr entity) { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), shared_ptr( new AnimatePacket(entity, AnimatePacket::CRITICAL_HIT) )); + getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::make_shared(entity, AnimatePacket::CRITICAL_HIT)); } void ServerPlayer::magicCrit(shared_ptr entity) { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), shared_ptr( new AnimatePacket(entity, AnimatePacket::MAGIC_CRITICAL_HIT) )); + getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::make_shared(entity, AnimatePacket::MAGIC_CRITICAL_HIT)); } void ServerPlayer::onUpdateAbilities() { - if (connection == NULL) return; - connection->send(shared_ptr(new PlayerAbilitiesPacket(&abilities))); + if (connection == nullptr) return; + connection->send(std::make_shared(&abilities)); } ServerLevel *ServerPlayer::getLevel() { - return (ServerLevel *) level; + return static_cast(level); } void ServerPlayer::setGameMode(GameType *mode) { gameMode->setGameModeForPlayer(mode); - connection->send(shared_ptr(new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, mode->getId()))); + connection->send(std::make_shared(GameEventPacket::CHANGE_GAME_MODE, mode->getId())); } void ServerPlayer::sendMessage(const wstring& message, ChatPacket::EChatPacketMessage type /*= e_ChatCustom*/, int customData /*= -1*/, const wstring& additionalMessage /*= L""*/) { - connection->send(shared_ptr(new ChatPacket(message,type,customData,additionalMessage))); + connection->send(std::make_shared(message, type, customData, additionalMessage)); } bool ServerPlayer::hasPermission(EGameCommand command) @@ -1651,7 +1655,7 @@ int ServerPlayer::getPlayerViewDistanceModifier() { INetworkPlayer *player = connection->getNetworkPlayer(); - if( player != NULL ) + if( player != nullptr ) { DWORD rtt = player->GetCurrentRtt(); @@ -1666,7 +1670,7 @@ int ServerPlayer::getPlayerViewDistanceModifier() void ServerPlayer::handleCollectItem(shared_ptr item) { - if(gameMode->getGameRules() != NULL) gameMode->getGameRules()->onCollectItem(item); + if(gameMode->getGameRules() != nullptr) gameMode->getGameRules()->onCollectItem(item); } #ifndef _CONTENT_PACKAGE diff --git a/Minecraft.Client/ServerPlayerGameMode.cpp b/Minecraft.Client/ServerPlayerGameMode.cpp index 2e6bca35e..041487f5d 100644 --- a/Minecraft.Client/ServerPlayerGameMode.cpp +++ b/Minecraft.Client/ServerPlayerGameMode.cpp @@ -29,12 +29,12 @@ ServerPlayerGameMode::ServerPlayerGameMode(Level *level) this->level = level; // 4J Added - m_gameRules = NULL; + m_gameRules = nullptr; } ServerPlayerGameMode::~ServerPlayerGameMode() { - if(m_gameRules!=NULL) delete m_gameRules; + if(m_gameRules!=nullptr) delete m_gameRules; } void ServerPlayerGameMode::setGameModeForPlayer(GameType *gameModeForPlayer) @@ -86,7 +86,7 @@ void ServerPlayerGameMode::tick() { Tile *tile = Tile::tiles[t]; float destroyProgress = tile->getDestroyProgress(player, player->level, delayedDestroyX, delayedDestroyY, delayedDestroyZ) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); + int state = static_cast(destroyProgress * 10); if (state != lastSentState) { @@ -105,7 +105,7 @@ void ServerPlayerGameMode::tick() int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock); Tile *tile = Tile::tiles[t]; - if (tile == NULL) + if (tile == nullptr) { level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); lastSentState = -1; @@ -115,7 +115,7 @@ void ServerPlayerGameMode::tick() { int ticksSpentDestroying = gameTicks - destroyProgressStart; float destroyProgress = tile->getDestroyProgress(player, player->level, xDestroyBlock, yDestroyBlock, zDestroyBlock) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); + int state = static_cast(destroyProgress * 10); if (state != lastSentState) { @@ -166,7 +166,7 @@ void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) xDestroyBlock = x; yDestroyBlock = y; zDestroyBlock = z; - int state = (int) (progress * 10); + int state = static_cast(progress * 10); level->destroyTileProgress(player->entityId, x, y, z, state); lastSentState = state; } @@ -176,31 +176,29 @@ void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) { if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { - // int ticksSpentDestroying = gameTicks - destroyProgressStart; - int t = level->getTile(x, y, z); if (t != 0) { Tile *tile = Tile::tiles[t]; - - // MGH - removed checking for the destroy progress here, it has already been checked on the client before it sent the packet. - // fixes issues with this failing to destroy because of packets bunching up - // float destroyProgress = tile->getDestroyProgress(player, player->level, x, y, z) * (ticksSpentDestroying + 1); - // if (destroyProgress >= .7f || bIgnoreDestroyProgress) + // Anti-cheat: re-check destroy progress on the server for STOP_DESTROY. + int ticksSpentDestroying = gameTicks - destroyProgressStart; + float destroyProgress = tile->getDestroyProgress(player, player->level, x, y, z) * (ticksSpentDestroying + 1); + if (destroyProgress >= 1.0f) { isDestroyingBlock = false; level->destroyTileProgress(player->entityId, x, y, z, -1); destroyBlock(x, y, z); } - // else if (!hasDelayedDestroy) - // { - // isDestroyingBlock = false; - // hasDelayedDestroy = true; - // delayedDestroyX = x; - // delayedDestroyY = y; - // delayedDestroyZ = z; - // delayedTickStart = destroyProgressStart; - // } + else if (!hasDelayedDestroy) + { + // Keep server-authoritative mining while allowing legit latency to finish via delayed tick progression. + isDestroyingBlock = false; + hasDelayedDestroy = true; + delayedDestroyX = x; + delayedDestroyY = y; + delayedDestroyZ = z; + delayedTickStart = destroyProgressStart; + } } } } @@ -216,13 +214,13 @@ bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; int data = level->getData(x, y, z); - if (oldTile != NULL) + if (oldTile != nullptr) { oldTile->playerWillDestroy(level, x, y, z, data, player); } bool changed = level->removeTile(x, y, z); - if (oldTile != NULL && changed) + if (oldTile != nullptr && changed) { oldTile->destroy(level, x, y, z, data); } @@ -241,7 +239,7 @@ bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) if (gameModeForPlayer->isCreative()) { - if (player->getCarriedItem() != NULL && dynamic_cast(player->getCarriedItem()->getItem()) != NULL) + if (player->getCarriedItem() != nullptr && dynamic_cast(player->getCarriedItem()->getItem()) != nullptr) { return false; } @@ -286,7 +284,7 @@ bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) if (isCreative()) { - shared_ptr tup = shared_ptr( new TileUpdatePacket(x, y, z, level) ); + shared_ptr tup = std::make_shared(x, y, z, level); // 4J - a bit of a hack here, but if we want to tell the client that it needs to inform the renderer of a block being destroyed, then send a block 255 instead of a 0. This is handled in ClientConnection::handleTileUpdate if( tup->block == 0 ) { @@ -298,7 +296,7 @@ bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) { shared_ptr item = player->getSelectedItem(); bool canDestroy = player->canDestroy(Tile::tiles[t]); - if (item != NULL) + if (item != nullptr) { item->mineBlock(level, t, x, y, z, player); if (item->count == 0) @@ -322,7 +320,7 @@ bool ServerPlayerGameMode::useItem(shared_ptr player, Level *level, shar int oldCount = item->count; int oldAux = item->getAuxValue(); shared_ptr itemInstance = item->use(level, player); - if (itemInstance != item || (itemInstance != NULL && (itemInstance->count != oldCount || itemInstance->getUseDuration() > 0 || itemInstance->getAuxValue() != oldAux))) + if (itemInstance != item || (itemInstance != nullptr && (itemInstance->count != oldCount || itemInstance->getUseDuration() > 0 || itemInstance->getAuxValue() != oldAux))) { player->inventory->items[player->inventory->selected] = itemInstance; if (isCreative()) @@ -348,7 +346,7 @@ bool ServerPlayerGameMode::useItemOn(shared_ptr player, Level *level, sh { // 4J-PB - Adding a test only version to allow tooltips to be displayed int t = level->getTile(x, y, z); - if (!player->isSneaking() || player->getCarriedItem() == NULL) + if (!player->isSneaking() || player->getCarriedItem() == nullptr) { if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) { @@ -360,14 +358,14 @@ bool ServerPlayerGameMode::useItemOn(shared_ptr player, Level *level, sh { if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) { - if(m_gameRules != NULL) m_gameRules->onUseTile(t,x,y,z); + if(m_gameRules != nullptr) m_gameRules->onUseTile(t,x,y,z); return true; } } } } - if (item == NULL || !player->isAllowedToUse(item)) return false; + if (item == nullptr || !player->isAllowedToUse(item)) return false; if (isCreative()) { int aux = item->getAuxValue(); @@ -391,6 +389,6 @@ void ServerPlayerGameMode::setLevel(ServerLevel *newLevel) // 4J Added void ServerPlayerGameMode::setGameRules(GameRulesInstance *rules) { - if(m_gameRules != NULL) delete m_gameRules; + if(m_gameRules != nullptr) delete m_gameRules; m_gameRules = rules; -} \ No newline at end of file +} diff --git a/Minecraft.Client/ServerPlayerGameMode.h b/Minecraft.Client/ServerPlayerGameMode.h index 89b9e9b44..509e16763 100644 --- a/Minecraft.Client/ServerPlayerGameMode.h +++ b/Minecraft.Client/ServerPlayerGameMode.h @@ -54,7 +54,7 @@ private: public: bool destroyBlock(int x, int y, int z); bool useItem(shared_ptr player, Level *level, shared_ptr item, bool bTestUseOnly=false); - bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); + bool useItemOn(shared_ptr player, Level *level, shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false, bool *pbUsedItem=nullptr); void setLevel(ServerLevel *newLevel); }; \ No newline at end of file diff --git a/Minecraft.Client/ServerScoreboard.cpp b/Minecraft.Client/ServerScoreboard.cpp index 738a29c92..9a0443245 100644 --- a/Minecraft.Client/ServerScoreboard.cpp +++ b/Minecraft.Client/ServerScoreboard.cpp @@ -37,7 +37,7 @@ void ServerScoreboard::setDisplayObjective(int slot, Objective *objective) //Scoreboard::setDisplayObjective(slot, objective); - //if (old != objective && old != NULL) + //if (old != objective && old != nullptr) //{ // if (getObjectiveDisplaySlotCount(old) > 0) // { @@ -49,7 +49,7 @@ void ServerScoreboard::setDisplayObjective(int slot, Objective *objective) // } //} - //if (objective != NULL) + //if (objective != nullptr) //{ // if (trackedObjectives.contains(objective)) // { @@ -146,7 +146,7 @@ void ServerScoreboard::setSaveData(ScoreboardSaveData *data) void ServerScoreboard::setDirty() { - //if (saveData != NULL) + //if (saveData != nullptr) //{ // saveData->setDirty(); //} @@ -154,7 +154,7 @@ void ServerScoreboard::setDirty() vector > *ServerScoreboard::getStartTrackingPackets(Objective *objective) { - return NULL; + return nullptr; //vector > *packets = new vector >(); //packets.push_back( shared_ptr( new SetObjectivePacket(objective, SetObjectivePacket::METHOD_ADD))); @@ -189,7 +189,7 @@ void ServerScoreboard::startTrackingObjective(Objective *objective) vector > *ServerScoreboard::getStopTrackingPackets(Objective *objective) { - return NULL; + return nullptr; //vector > *packets = new ArrayList(); //packets->push_back( shared_ptrgetPath(); } @@ -40,9 +40,9 @@ Settings::Settings(File *file) line.erase(line.size() - 1); if (line.size() >= 3 && - (unsigned char)line[0] == 0xEF && - (unsigned char)line[1] == 0xBB && - (unsigned char)line[2] == 0xBF) + static_cast(line[0]) == 0xEF && + static_cast(line[1]) == 0xBB && + static_cast(line[2]) == 0xBF) { line.erase(0, 3); } diff --git a/Minecraft.Client/SheepRenderer.cpp b/Minecraft.Client/SheepRenderer.cpp index 5a3580bce..434505781 100644 --- a/Minecraft.Client/SheepRenderer.cpp +++ b/Minecraft.Client/SheepRenderer.cpp @@ -30,7 +30,7 @@ int SheepRenderer::prepareArmor(shared_ptr _sheep, int layer, floa int value = (sheep->tickCount / colorDuration) + sheep->entityId; int c1 = value % Sheep::COLOR_LENGTH; int c2 = (value + 1) % Sheep::COLOR_LENGTH; - float subStep = ((sheep->tickCount % colorDuration) + a) / (float) colorDuration; + float subStep = ((sheep->tickCount % colorDuration) + a) / static_cast(colorDuration); glColor3f(Sheep::COLOR[c1][0] * (1.0f - subStep) + Sheep::COLOR[c2][0] * subStep, Sheep::COLOR[c1][1] * (1.0f - subStep) + Sheep::COLOR[c2][1] * subStep, Sheep::COLOR[c1][2] * (1.0f - subStep) + Sheep::COLOR[c2][2] * subStep); diff --git a/Minecraft.Client/SignRenderer.cpp b/Minecraft.Client/SignRenderer.cpp index 5f764a92a..3f0b21757 100644 --- a/Minecraft.Client/SignRenderer.cpp +++ b/Minecraft.Client/SignRenderer.cpp @@ -25,7 +25,7 @@ void SignRenderer::render(shared_ptr _sign, double x, double y, doub float size = 16 / 24.0f; if (tile == Tile::sign) { - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + glTranslatef(static_cast(x) + 0.5f, static_cast(y) + 0.75f * size, static_cast(z) + 0.5f); float rot = sign->getData() * 360 / 16.0f; glRotatef(-rot, 0, 1, 0); signModel->cube2->visible = true; @@ -39,7 +39,7 @@ void SignRenderer::render(shared_ptr _sign, double x, double y, doub if (face == 4) rot = 90; if (face == 5) rot = -90; - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + glTranslatef(static_cast(x) + 0.5f, static_cast(y) + 0.75f * size, static_cast(z) + 0.5f); glRotatef(-rot, 0, 1, 0); glTranslatef(0, -5 / 16.0f, -7 / 16.0f); diff --git a/Minecraft.Client/SilverfishModel.cpp b/Minecraft.Client/SilverfishModel.cpp index ce8b8254a..7058d1870 100644 --- a/Minecraft.Client/SilverfishModel.cpp +++ b/Minecraft.Client/SilverfishModel.cpp @@ -48,7 +48,7 @@ SilverfishModel::SilverfishModel() { bodyParts[i] = new ModelPart(this, BODY_TEXS[i][0], BODY_TEXS[i][1]); bodyParts[i]->addBox(BODY_SIZES[i][0] * -0.5f, 0, BODY_SIZES[i][2] * -0.5f, BODY_SIZES[i][0], BODY_SIZES[i][1], BODY_SIZES[i][2]); - bodyParts[i]->setPos(0.0f, 24.0f - (float)BODY_SIZES[i][1], placement); + bodyParts[i]->setPos(0.0f, 24.0f - static_cast(BODY_SIZES[i][1]), placement); zPlacement[i] = placement; if (i < bodyParts.length - 1) { @@ -100,8 +100,8 @@ void SilverfishModel::setupAnim(float time, float r, float bob, float yRot, floa { for (unsigned int i = 0; i < bodyParts.length; i++) { - bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * (1 + abs((int)i - 2)); - bodyParts[i]->x = Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs((int)i - 2); + bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * (1 + abs(static_cast(i) - 2)); + bodyParts[i]->x = Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs(static_cast(i) - 2); } bodyLayers[0]->yRot = bodyParts[2]->yRot; diff --git a/Minecraft.Client/SkullTileRenderer.cpp b/Minecraft.Client/SkullTileRenderer.cpp index 32d216cd6..7862043b2 100644 --- a/Minecraft.Client/SkullTileRenderer.cpp +++ b/Minecraft.Client/SkullTileRenderer.cpp @@ -6,7 +6,7 @@ #include "..\Minecraft.World\net.minecraft.h" #include "..\Minecraft.World\net.minecraft.world.level.tile.h" -SkullTileRenderer *SkullTileRenderer::instance = NULL; +SkullTileRenderer *SkullTileRenderer::instance = nullptr; ResourceLocation SkullTileRenderer::SKELETON_LOCATION = ResourceLocation(TN_MOB_SKELETON); ResourceLocation SkullTileRenderer::WITHER_SKELETON_LOCATION = ResourceLocation(TN_MOB_WITHER_SKELETON); @@ -28,7 +28,7 @@ SkullTileRenderer::~SkullTileRenderer() void SkullTileRenderer::render(shared_ptr _skull, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) { shared_ptr skull = dynamic_pointer_cast(_skull); - renderSkull((float) x, (float) y, (float) z, skull->getData() & SkullTile::PLACEMENT_MASK, skull->getRotation() * 360 / 16.0f, skull->getSkullType(), skull->getExtraType()); + renderSkull(static_cast(x), static_cast(y), static_cast(z), skull->getData() & SkullTile::PLACEMENT_MASK, skull->getRotation() * 360 / 16.0f, skull->getSkullType(), skull->getExtraType()); } void SkullTileRenderer::init(TileEntityRenderDispatcher *tileEntityRenderDispatcher) diff --git a/Minecraft.Client/SlideButton.cpp b/Minecraft.Client/SlideButton.cpp index 0da24515a..0c7735af6 100644 --- a/Minecraft.Client/SlideButton.cpp +++ b/Minecraft.Client/SlideButton.cpp @@ -18,22 +18,22 @@ void SlideButton::renderBg(Minecraft *minecraft, int xm, int ym) if (!visible) return; if (sliding) { - value = (xm - (x + 4)) / (float) (w - 8); + value = (xm - (x + 4)) / static_cast(w - 8); if (value < 0) value = 0; if (value > 1) value = 1; minecraft->options->set(option, value); msg = minecraft->options->getMessage(option); } glColor4f(1, 1, 1, 1); - blit(x + (int) (value * (w - 8)), y, 0, 46 + 1 * 20, 4, 20); - blit(x + (int) (value * (w - 8)) + 4, y, 196, 46 + 1 * 20, 4, 20); + blit(x + static_cast(value * (w - 8)), y, 0, 46 + 1 * 20, 4, 20); + blit(x + static_cast(value * (w - 8)) + 4, y, 196, 46 + 1 * 20, 4, 20); } bool SlideButton::clicked(Minecraft *minecraft, int mx, int my) { if (Button::clicked(minecraft, mx, my)) { - value = (mx - (x + 4)) / (float) (w - 8); + value = (mx - (x + 4)) / static_cast(w - 8); if (value < 0) value = 0; if (value > 1) value = 1; minecraft->options->set(option, value); diff --git a/Minecraft.Client/SlimeModel.cpp b/Minecraft.Client/SlimeModel.cpp index 834847f80..7d30ce663 100644 --- a/Minecraft.Client/SlimeModel.cpp +++ b/Minecraft.Client/SlimeModel.cpp @@ -27,9 +27,9 @@ SlimeModel::SlimeModel(int vOffs) } else { - eye0 = NULL; - eye1 = NULL; - mouth = NULL; + eye0 = nullptr; + eye1 = nullptr; + mouth = nullptr; } cube->compile(1.0f/16.0f); } @@ -39,7 +39,7 @@ void SlimeModel::render(shared_ptr entity, float time, float r, float bo setupAnim(time, r, bob, yRot, xRot, scale, entity); cube->render(scale,usecompiled); - if (eye0!=NULL) + if (eye0!=nullptr) { eye0->render(scale,usecompiled); eye1->render(scale,usecompiled); diff --git a/Minecraft.Client/SlimeRenderer.cpp b/Minecraft.Client/SlimeRenderer.cpp index f3f64aed4..ca5e51916 100644 --- a/Minecraft.Client/SlimeRenderer.cpp +++ b/Minecraft.Client/SlimeRenderer.cpp @@ -41,7 +41,7 @@ void SlimeRenderer::scale(shared_ptr _slime, float a) // 4J - dynamic cast required because we aren't using templates/generics in our version shared_ptr slime = dynamic_pointer_cast(_slime); - float size = (float) slime->getSize(); + float size = static_cast(slime->getSize()); float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / (size * 0.5f + 1); float w = 1 / (ss + 1); glScalef(w * size, 1 / w * size, w * size); diff --git a/Minecraft.Client/SmallButton.cpp b/Minecraft.Client/SmallButton.cpp index 6bb3cd1fb..731f5f141 100644 --- a/Minecraft.Client/SmallButton.cpp +++ b/Minecraft.Client/SmallButton.cpp @@ -3,12 +3,12 @@ SmallButton::SmallButton(int id, int x, int y, const wstring& msg) : Button(id, x, y, 150, 20, msg) { - this->option = NULL; + this->option = nullptr; } SmallButton::SmallButton(int id, int x, int y, int width, int height, const wstring& msg) : Button(id, x, y, width, height, msg) { - this->option = NULL; + this->option = nullptr; } SmallButton::SmallButton(int id, int x, int y, const Options::Option *item, const wstring& msg) : Button(id, x, y, 150, 20, msg) diff --git a/Minecraft.Client/SmokeParticle.cpp b/Minecraft.Client/SmokeParticle.cpp index a88558851..b48978f09 100644 --- a/Minecraft.Client/SmokeParticle.cpp +++ b/Minecraft.Client/SmokeParticle.cpp @@ -26,8 +26,8 @@ void SmokeParticle::init(Level *level, double x, double y, double z, double xa, size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(lifetime * scale); noPhysics = false; } diff --git a/Minecraft.Client/SnowManRenderer.cpp b/Minecraft.Client/SnowManRenderer.cpp index 1e258f3c6..1ab1d4023 100644 --- a/Minecraft.Client/SnowManRenderer.cpp +++ b/Minecraft.Client/SnowManRenderer.cpp @@ -11,7 +11,7 @@ ResourceLocation SnowManRenderer::SNOWMAN_LOCATION = ResourceLocation(TN_MOB_SNO SnowManRenderer::SnowManRenderer() : MobRenderer(new SnowManModel(), 0.5f) { - model = (SnowManModel *) MobRenderer::model; + model = static_cast(MobRenderer::model); this->setArmor(model); } @@ -22,8 +22,8 @@ void SnowManRenderer::additionalRendering(shared_ptr _mob, float a shared_ptr mob = dynamic_pointer_cast(_mob); MobRenderer::additionalRendering(mob, a); - shared_ptr headGear = shared_ptr( new ItemInstance(Tile::pumpkin, 1) ); - if (headGear != NULL && headGear->getItem()->id < 256) + shared_ptr headGear = std::make_shared(Tile::pumpkin, 1); + if (headGear != nullptr && headGear->getItem()->id < 256) { glPushMatrix(); model->head->translateTo(1 / 16.0f); diff --git a/Minecraft.Client/SnowShovelParticle.cpp b/Minecraft.Client/SnowShovelParticle.cpp index 4417cb5d8..cf63a7309 100644 --- a/Minecraft.Client/SnowShovelParticle.cpp +++ b/Minecraft.Client/SnowShovelParticle.cpp @@ -11,13 +11,13 @@ void SnowShovelParticle::init(Level *level, double x, double y, double z, double yd += ya; zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); + rCol = gCol = bCol = 1 - static_cast(Math::random() * 0.3f); size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) ( lifetime * scale ); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(lifetime * scale); noPhysics = false; } diff --git a/Minecraft.Client/SpellParticle.cpp b/Minecraft.Client/SpellParticle.cpp index ce8b975f1..cd0797ace 100644 --- a/Minecraft.Client/SpellParticle.cpp +++ b/Minecraft.Client/SpellParticle.cpp @@ -13,7 +13,7 @@ SpellParticle::SpellParticle(Level *level, double x, double y, double z, double size *= 0.75f; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); noPhysics = false; baseTex = 8 * 16; diff --git a/Minecraft.Client/SpiderModel.cpp b/Minecraft.Client/SpiderModel.cpp index 739677e43..0cdc14cae 100644 --- a/Minecraft.Client/SpiderModel.cpp +++ b/Minecraft.Client/SpiderModel.cpp @@ -11,48 +11,48 @@ SpiderModel::SpiderModel() : Model() head = new ModelPart(this, 32, 4); head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(0+yo), -3); + head->setPos(0, static_cast(0 + yo), -3); body0 = new ModelPart(this, 0, 0); body0->addBox(-3, -3, -3, 6, 6, 6, g); // Body - body0->setPos(0,(float)(yo), 0); + body0->setPos(0,static_cast(yo), 0); body1 = new ModelPart(this, 0, 12); body1->addBox(-5, -4, -6, 10, 8, 12, g); // Body - body1->setPos(0, (float)(0+yo), 3 + 6); + body1->setPos(0, static_cast(0 + yo), 3 + 6); leg0 = new ModelPart(this, 18, 0); leg0->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg0->setPos(-4, (float)(0+yo), 2); + leg0->setPos(-4, static_cast(0 + yo), 2); leg1 = new ModelPart(this, 18, 0); leg1->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg1->setPos(4, (float)(0+yo), 2); + leg1->setPos(4, static_cast(0 + yo), 2); leg2 = new ModelPart(this, 18, 0); leg2->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg2->setPos(-4, (float)(0+yo), 1); + leg2->setPos(-4, static_cast(0 + yo), 1); leg3 = new ModelPart(this, 18, 0); leg3->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg3->setPos(4, (float)(0+yo), 1); + leg3->setPos(4, static_cast(0 + yo), 1); leg4 = new ModelPart(this, 18, 0); leg4->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg4->setPos(-4, (float)(0+yo), 0); + leg4->setPos(-4, static_cast(0 + yo), 0); leg5 = new ModelPart(this, 18, 0); leg5->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg5->setPos(4, (float)(0+yo), 0); + leg5->setPos(4, static_cast(0 + yo), 0); leg6 = new ModelPart(this, 18, 0); leg6->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg6->setPos(-4, (float)(0+yo), -1); + leg6->setPos(-4, static_cast(0 + yo), -1); leg7 = new ModelPart(this, 18, 0); leg7->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg7->setPos(4, (float)(0+yo), -1); + leg7->setPos(4, static_cast(0 + yo), -1); // 4J added - compile now to avoid random performance hit first time cubes are rendered head->compile(1.0f/16.0f); diff --git a/Minecraft.Client/SquidModel.cpp b/Minecraft.Client/SquidModel.cpp index 0152418f2..0ee2501d6 100644 --- a/Minecraft.Client/SquidModel.cpp +++ b/Minecraft.Client/SquidModel.cpp @@ -14,17 +14,17 @@ SquidModel::SquidModel() : Model() { tentacles[i] = new ModelPart(this, 48, 0); - double angle = i * PI * 2.0 / (double) TENTACLES_LENGTH; // 4J - 8 was tentacles.length - float xo = Mth::cos((float)angle) * 5; - float yo = Mth::sin((float)angle) * 5; + double angle = i * PI * 2.0 / static_cast(TENTACLES_LENGTH); // 4J - 8 was tentacles.length + float xo = Mth::cos(static_cast(angle)) * 5; + float yo = Mth::sin(static_cast(angle)) * 5; tentacles[i]->addBox(-1, 0, -1, 2, 18, 2); tentacles[i]->x = xo; tentacles[i]->z = yo; - tentacles[i]->y = (float)(31 + yoffs); + tentacles[i]->y = static_cast(31 + yoffs); - angle = i * PI * -2.0 / (double) TENTACLES_LENGTH + PI * .5; // 4J - 8 was tentacles.length - tentacles[i]->yRot = (float) angle; + angle = i * PI * -2.0 / static_cast(TENTACLES_LENGTH) + PI * .5; // 4J - 8 was tentacles.length + tentacles[i]->yRot = static_cast(angle); // 4J added - compile now to avoid random performance hit first time cubes are rendered tentacles[i]->compile(1.0f/16.0f); diff --git a/Minecraft.Client/StatsCounter.cpp b/Minecraft.Client/StatsCounter.cpp index b75625e9d..e92c43c0c 100644 --- a/Minecraft.Client/StatsCounter.cpp +++ b/Minecraft.Client/StatsCounter.cpp @@ -142,7 +142,7 @@ void StatsCounter::parse(void* data) assert( stats.size() == 0 ); //Pointer to current position in stat array - PBYTE pbData=(PBYTE)data; + PBYTE pbData=static_cast(data); pbData+=sizeof(GAME_SETTINGS); unsigned short* statData = (unsigned short*)pbData;//data + (STAT_DATA_OFFSET/sizeof(unsigned short)); @@ -217,7 +217,7 @@ void StatsCounter::save(int player, bool force) #if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__ ) PBYTE pbData = (PBYTE)StorageManager.GetGameDefinedProfileData(player); #else - PBYTE pbData = (PBYTE)ProfileManager.GetGameDefinedProfileData(player); + PBYTE pbData = static_cast(ProfileManager.GetGameDefinedProfileData(player)); #endif pbData+=sizeof(GAME_SETTINGS); @@ -1314,30 +1314,30 @@ void StatsCounter::WipeLeaderboards() #if defined DEBUG_ENABLE_CLEAR_LEADERBOARDS && defined _XBOX - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, NULL); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, nullptr); +// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, nullptr); + if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, nullptr); if( LeaderboardManager::Instance()->OpenSession() ) { writeStats(); diff --git a/Minecraft.Client/StatsScreen.cpp b/Minecraft.Client/StatsScreen.cpp index 01d041f0e..c618a30f2 100644 --- a/Minecraft.Client/StatsScreen.cpp +++ b/Minecraft.Client/StatsScreen.cpp @@ -10,15 +10,15 @@ #include "..\Minecraft.World\net.minecraft.world.item.h" const float StatsScreen::SLOT_TEX_SIZE = 128.0f; -ItemRenderer *StatsScreen::itemRenderer = NULL; +ItemRenderer *StatsScreen::itemRenderer = nullptr; StatsScreen::StatsScreen(Screen *lastScreen, StatsCounter *stats) { // 4J - added initialisers itemRenderer = new ItemRenderer(); - statsList = NULL; - itemStatsList = NULL; - blockStatsList = NULL; + statsList = nullptr; + itemStatsList = nullptr; + blockStatsList = nullptr; this->lastScreen = lastScreen; this->stats = stats; } @@ -107,7 +107,7 @@ StatsScreen::GeneralStatisticsList::GeneralStatisticsList(StatsScreen *ss) : Scr int StatsScreen::GeneralStatisticsList::getNumberOfItems() { - return (int)Stats::generalStats->size(); + return static_cast(Stats::generalStats->size()); } void StatsScreen::GeneralStatisticsList::selectItem(int item, bool doubleClick) @@ -293,7 +293,7 @@ void StatsScreen::StatisticsList::clickedHeader(int headerMouseX, int headerMous int StatsScreen::StatisticsList::getNumberOfItems() { - return (int)statItemList.size(); + return static_cast(statItemList.size()); } ItemStat *StatsScreen::StatisticsList::getSlotStat(int slot) @@ -303,7 +303,7 @@ ItemStat *StatsScreen::StatisticsList::getSlotStat(int slot) void StatsScreen::StatisticsList::renderStat(ItemStat *stat, int x, int y, bool shaded) { - if (stat != NULL) + if (stat != nullptr) { wstring msg = stat->format(parent->stats->getTotalValue(stat)); parent->drawString(parent->font, msg, x - parent->font->width(msg), y + SLOT_TEXT_OFFSET, shaded ? 0xffffff : 0x909090); @@ -373,7 +373,7 @@ void StatsScreen::StatisticsList::renderMousehoverTooltip(ItemStat *stat, int x, { // 4J Stu - Unused #if 0 - if (stat == NULL) + if (stat == nullptr) { return; } @@ -429,11 +429,11 @@ StatsScreen::ItemStatisticsList::ItemStatisticsList(StatsScreen *ss) : StatsScre { addToList = true; } - else if (Stats::itemBroke[id] != NULL && parent->stats->getTotalValue(Stats::itemBroke[id]) > 0) + else if (Stats::itemBroke[id] != nullptr && parent->stats->getTotalValue(Stats::itemBroke[id]) > 0) { addToList = true; } - else if (Stats::itemCrafted[id] != NULL && parent->stats->getTotalValue(Stats::itemCrafted[id]) > 0) + else if (Stats::itemCrafted[id] != nullptr && parent->stats->getTotalValue(Stats::itemCrafted[id]) > 0) { addToList = true; } @@ -556,11 +556,11 @@ StatsScreen::BlockStatisticsList::BlockStatisticsList(StatsScreen *ss) : Statist { addToList = true; } - else if (Stats::itemUsed[id] != NULL && parent->stats->getTotalValue(Stats::itemUsed[id]) > 0) + else if (Stats::itemUsed[id] != nullptr && parent->stats->getTotalValue(Stats::itemUsed[id]) > 0) { addToList = true; } - else if (Stats::itemCrafted[id] != NULL && parent->stats->getTotalValue(Stats::itemCrafted[id]) > 0) + else if (Stats::itemCrafted[id] != nullptr && parent->stats->getTotalValue(Stats::itemCrafted[id]) > 0) { addToList = true; } diff --git a/Minecraft.Client/StitchSlot.cpp b/Minecraft.Client/StitchSlot.cpp index cdce61281..8de443ed4 100644 --- a/Minecraft.Client/StitchSlot.cpp +++ b/Minecraft.Client/StitchSlot.cpp @@ -5,8 +5,8 @@ StitchSlot::StitchSlot(int originX, int originY, int width, int height) : originX(originX), originY(originY), width(width), height(height) { - subSlots = NULL; - textureHolder = NULL; + subSlots = nullptr; + textureHolder = nullptr; } TextureHolder *StitchSlot::getHolder() @@ -27,7 +27,7 @@ int StitchSlot::getY() bool StitchSlot::add(TextureHolder *textureHolder) { // Already holding a texture -- doesn't account for subslots. - if (this->textureHolder != NULL) + if (this->textureHolder != nullptr) { return false; } @@ -42,7 +42,7 @@ bool StitchSlot::add(TextureHolder *textureHolder) } // Exact fit! best-case-solution - if (textureWidth == width && textureHeight == height && subSlots == NULL) + if (textureWidth == width && textureHeight == height && subSlots == nullptr) { // Store somehow this->textureHolder = textureHolder; @@ -50,7 +50,7 @@ bool StitchSlot::add(TextureHolder *textureHolder) } // See if we're already divided before, if not, setup subSlots - if (subSlots == NULL) + if (subSlots == nullptr) { subSlots = new vector(); diff --git a/Minecraft.Client/StitchedTexture.cpp b/Minecraft.Client/StitchedTexture.cpp index 64ab2f365..b9693f3da 100644 --- a/Minecraft.Client/StitchedTexture.cpp +++ b/Minecraft.Client/StitchedTexture.cpp @@ -26,7 +26,7 @@ StitchedTexture *StitchedTexture::create(const wstring &name) StitchedTexture::StitchedTexture(const wstring &name, const wstring &filename) : name(name) { // 4J Initialisers - source = NULL; + source = nullptr; rotated = false; x = 0; y = 0; @@ -40,9 +40,9 @@ StitchedTexture::StitchedTexture(const wstring &name, const wstring &filename) : heightTranslation = 0.0f; frame = 0; subFrame = 0; - frameOverride = NULL; + frameOverride = nullptr; flags = 0; - frames = NULL; + frames = nullptr; m_fileName = filename; } @@ -94,10 +94,10 @@ void StitchedTexture::init(Texture *source, vector *frames, int x, in float marginX = 0.0f; //0.01f / source->getWidth(); float marginY = 0.0f; //0.01f / source->getHeight(); - this->u0 = x / (float) source->getWidth() + marginX; - this->u1 = (x + width) / (float) source->getWidth() - marginX; - this->v0 = y / (float) source->getHeight() + marginY; - this->v1 = (y + height) / (float) source->getHeight() - marginY; + this->u0 = x / static_cast(source->getWidth()) + marginX; + this->u1 = (x + width) / static_cast(source->getWidth()) - marginX; + this->v0 = y / static_cast(source->getHeight()) + marginY; + this->v1 = (y + height) / static_cast(source->getHeight()) - marginY; #ifndef _CONTENT_PACKAGE bool addBreakpoint = false; @@ -112,8 +112,8 @@ void StitchedTexture::init(Texture *source, vector *frames, int x, in } #endif - this->widthTranslation = width / (float) SharedConstants::WORLD_RESOLUTION; - this->heightTranslation = height / (float) SharedConstants::WORLD_RESOLUTION; + this->widthTranslation = width / static_cast(SharedConstants::WORLD_RESOLUTION); + this->heightTranslation = height / static_cast(SharedConstants::WORLD_RESOLUTION); } void StitchedTexture::replaceWith(StitchedTexture *texture) @@ -156,7 +156,7 @@ float StitchedTexture::getU1(bool adjust/*=false*/) const float StitchedTexture::getU(double offset, bool adjust/*=false*/) const { float diff = getU1(adjust) - getU0(adjust); - return getU0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); + return getU0(adjust) + (diff * (static_cast(offset) / SharedConstants::WORLD_RESOLUTION)); } float StitchedTexture::getV0(bool adjust/*=false*/) const @@ -172,7 +172,7 @@ float StitchedTexture::getV1(bool adjust/*=false*/) const float StitchedTexture::getV(double offset, bool adjust/*=false*/) const { float diff = getV1(adjust) - getV0(adjust); - return getV0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); + return getV0(adjust) + (diff * (static_cast(offset) / SharedConstants::WORLD_RESOLUTION)); } wstring StitchedTexture::getName() const @@ -192,7 +192,7 @@ int StitchedTexture::getSourceHeight() const void StitchedTexture::cycleFrames() { - if (frameOverride != NULL) + if (frameOverride != nullptr) { pair current = frameOverride->at(frame); subFrame++; @@ -250,10 +250,10 @@ int StitchedTexture::getFrames() */ void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) { - if(frameOverride != NULL) + if(frameOverride != nullptr) { delete frameOverride; - frameOverride = NULL; + frameOverride = nullptr; } frame = 0; subFrame = 0; @@ -303,10 +303,10 @@ void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) void StitchedTexture::loadAnimationFrames(const wstring &string) { - if(frameOverride != NULL) + if(frameOverride != nullptr) { delete frameOverride; - frameOverride = NULL; + frameOverride = nullptr; } frame = 0; subFrame = 0; diff --git a/Minecraft.Client/Stitcher.cpp b/Minecraft.Client/Stitcher.cpp index d52954c44..450c80264 100644 --- a/Minecraft.Client/Stitcher.cpp +++ b/Minecraft.Client/Stitcher.cpp @@ -17,7 +17,7 @@ void Stitcher::_init(const wstring &name, int maxWidth, int maxHeight, bool forc // 4J init storageX = 0; storageY = 0; - stitchedTexture = NULL; + stitchedTexture = nullptr; } Stitcher::Stitcher(const wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo) @@ -78,7 +78,7 @@ void Stitcher::stitch() //TextureHolder[] textureHolders = texturesToBeStitched.toArray(new TextureHolder[texturesToBeStitched.size()]); //Arrays.sort(textureHolders); - stitchedTexture = NULL; + stitchedTexture = nullptr; //for (int i = 0; i < textureHolders.length; i++) for( TextureHolder *textureHolder : texturesToBeStitched ) @@ -122,7 +122,7 @@ int Stitcher::smallestEncompassingPowerOfTwo(int input) bool Stitcher::addToStorage(TextureHolder *textureHolder) { - for (int i = 0; i < storage.size(); i++) + for (size_t i = 0; i < storage.size(); i++) { if (storage.at(i)->add(textureHolder)) { diff --git a/Minecraft.Client/StringTable.cpp b/Minecraft.Client/StringTable.cpp index 234a8943b..bdee2ca91 100644 --- a/Minecraft.Client/StringTable.cpp +++ b/Minecraft.Client/StringTable.cpp @@ -118,9 +118,7 @@ void StringTable::ProcessStringTableData(void) else { app.DebugPrintf("Failed to get language\n"); -#ifdef _DEBUG - __debugbreak(); -#endif + isStatic = false; } diff --git a/Minecraft.Client/SuspendedParticle.cpp b/Minecraft.Client/SuspendedParticle.cpp index 70702de0f..b7305207a 100644 --- a/Minecraft.Client/SuspendedParticle.cpp +++ b/Minecraft.Client/SuspendedParticle.cpp @@ -25,7 +25,7 @@ SuspendedParticle::SuspendedParticle(Level *level, double x, double y, double z, yd = ya * 0.0f; zd = za * 0.0f; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(16 / (Math::random() * 0.8 + 0.2)); } void SuspendedParticle::tick() diff --git a/Minecraft.Client/SuspendedTownParticle.cpp b/Minecraft.Client/SuspendedTownParticle.cpp index a24bbc42a..4c31b0c0b 100644 --- a/Minecraft.Client/SuspendedTownParticle.cpp +++ b/Minecraft.Client/SuspendedTownParticle.cpp @@ -18,7 +18,7 @@ SuspendedTownParticle::SuspendedTownParticle(Level *level, double x, double y, d yd *= 0.02f; zd *= 0.02f; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(20 / (Math::random() * 0.8 + 0.2)); this->noPhysics = true; } diff --git a/Minecraft.Client/TakeAnimationParticle.cpp b/Minecraft.Client/TakeAnimationParticle.cpp index c9530b0a0..f629363e1 100644 --- a/Minecraft.Client/TakeAnimationParticle.cpp +++ b/Minecraft.Client/TakeAnimationParticle.cpp @@ -64,7 +64,7 @@ void TakeAnimationParticle::render(Tesselator *t, float a, float xa, float ya, f zz-=zOff; - EntityRenderDispatcher::instance->render(item, (float)xx, (float)yy, (float)zz, item->yRot, a); + EntityRenderDispatcher::instance->render(item, static_cast(xx), static_cast(yy), static_cast(zz), item->yRot, a); } diff --git a/Minecraft.Client/TeleportCommand.cpp b/Minecraft.Client/TeleportCommand.cpp index 2132cfd4b..9dd29ff08 100644 --- a/Minecraft.Client/TeleportCommand.cpp +++ b/Minecraft.Client/TeleportCommand.cpp @@ -29,7 +29,7 @@ void TeleportCommand::execute(shared_ptr source, byteArray comman shared_ptr subject = players->getPlayer(subjectID); shared_ptr destination = players->getPlayer(destinationID); - if(subject != NULL && destination != NULL && subject->level->dimension->id == destination->level->dimension->id && subject->isAlive() ) + if(subject != nullptr && destination != nullptr && subject->level->dimension->id == destination->level->dimension->id && subject->isAlive() ) { subject->ride(nullptr); subject->connection->teleport(destination->x, destination->y, destination->z, destination->yRot, destination->xRot); @@ -86,5 +86,5 @@ shared_ptr TeleportCommand::preparePacket(PlayerUID subject, dos.writePlayerUID(subject); dos.writePlayerUID(destination); - return shared_ptr( new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray() )); + return std::make_shared(eGameCommand_Teleport, baos.toByteArray()); } \ No newline at end of file diff --git a/Minecraft.Client/TerrainParticle.cpp b/Minecraft.Client/TerrainParticle.cpp index 811ba840b..fb29118b8 100644 --- a/Minecraft.Client/TerrainParticle.cpp +++ b/Minecraft.Client/TerrainParticle.cpp @@ -47,7 +47,7 @@ void TerrainParticle::render(Tesselator *t, float a, float xa, float ya, float z float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) + if (tex != nullptr) { u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); @@ -55,9 +55,9 @@ void TerrainParticle::render(Tesselator *t, float a, float xa, float ya, float z v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = static_cast(xo + (this->x - xo) * a - xOff); + float y = static_cast(yo + (this->y - yo) * a - yOff); + float z = static_cast(zo + (this->z - zo) * a - zOff); // 4J - don't render terrain particles that are less than a metre away, to try and avoid large particles that are causing us problems with // photosensitivity testing diff --git a/Minecraft.Client/Tesselator.cpp b/Minecraft.Client/Tesselator.cpp index 7bae7aca9..b70ec983e 100644 --- a/Minecraft.Client/Tesselator.cpp +++ b/Minecraft.Client/Tesselator.cpp @@ -28,7 +28,7 @@ DWORD Tesselator::tlsIdx = TlsAlloc(); Tesselator *Tesselator::getInstance() { - return (Tesselator *)TlsGetValue(tlsIdx); + return static_cast(TlsGetValue(tlsIdx)); } void Tesselator::CreateNewThreadStorage(int bytes) @@ -179,18 +179,18 @@ void Tesselator::end() } #else - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); + RenderManager.DrawVertices(static_cast(mode),vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); #endif } else { if( useProjectedTexturePixelShader ) { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); + RenderManager.DrawVertices(static_cast(mode),vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); } else { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); + RenderManager.DrawVertices(static_cast(mode),vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); } } #endif @@ -295,12 +295,12 @@ void Tesselator::tex2(int tex2) void Tesselator::color(float r, float g, float b) { - color((int) (r * 255), (int) (g * 255), (int) (b * 255)); + color(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255)); } void Tesselator::color(float r, float g, float b, float a) { - color((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); + color(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255), static_cast(a * 255)); } void Tesselator::color(int r, int g, int b) @@ -749,7 +749,7 @@ void Tesselator::vertex(float x, float y, float z) // see comments in packCompactQuad() for exact format if( useCompactFormat360 ) { - unsigned int ucol = (unsigned int)col; + unsigned int ucol = static_cast(col); #ifdef _XBOX // Pack as 4:4:4 RGB_ @@ -774,7 +774,7 @@ void Tesselator::vertex(float x, float y, float z) unsigned short packedcol = ((col & 0xf8000000 ) >> 16 ) | ((col & 0x00fc0000 ) >> 13 ) | ((col & 0x0000f800 ) >> 11 ); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + int ipackedcol = static_cast(packedcol) & 0xffff; // 0 to 65535 range ipackedcol -= 32768; // -32768 to 32767 range ipackedcol &= 0xffff; @@ -824,12 +824,12 @@ void Tesselator::vertex(float x, float y, float z) p += 4; #else - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); + pShortData[0] = (static_cast((x + xo) * 1024.0f)&0xffff); + pShortData[1] = (static_cast((y + yo) * 1024.0f)&0xffff); + pShortData[2] = (static_cast((z + zo) * 1024.0f)&0xffff); pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); + pShortData[4] = (static_cast(uu * 8192.0f)&0xffff); + pShortData[5] = (static_cast(v * 8192.0f)&0xffff); int16_t u2 = ((int16_t*)&_tex2)[0]; int16_t v2 = ((int16_t*)&_tex2)[1]; #if defined _XBOX_ONE || defined __ORBIS__ @@ -1040,9 +1040,9 @@ void Tesselator::normal(float x, float y, float z) int8_t zz = (int8_t) (z * 127); _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #else - byte xx = (byte) (x * 127); - byte yy = (byte) (y * 127); - byte zz = (byte) (z * 127); + byte xx = static_cast(x * 127); + byte yy = static_cast(y * 127); + byte zz = static_cast(z * 127); _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #endif } diff --git a/Minecraft.Client/TextEditScreen.cpp b/Minecraft.Client/TextEditScreen.cpp index 9537b969c..4b32d1392 100644 --- a/Minecraft.Client/TextEditScreen.cpp +++ b/Minecraft.Client/TextEditScreen.cpp @@ -35,7 +35,7 @@ void TextEditScreen::removed() Keyboard::enableRepeatEvents(false); if (minecraft->level->isClientSide) { - minecraft->getConnection(0)->send( shared_ptr( new SignUpdatePacket(sign->x, sign->y, sign->z, sign->IsVerified(), sign->IsCensored(), sign->GetMessages()) ) ); + minecraft->getConnection(0)->send(std::make_shared(sign->x, sign->y, sign->z, sign->IsVerified(), sign->IsCensored(), sign->GetMessages())); } } @@ -52,7 +52,7 @@ void TextEditScreen::buttonClicked(Button *button) if (button->id == 0) { sign->setChanged(); - minecraft->setScreen(NULL); + minecraft->setScreen(nullptr); } } @@ -82,7 +82,7 @@ void TextEditScreen::render(int xm, int ym, float a) drawCenteredString(font, title, width / 2, 40, 0xffffff); glPushMatrix(); - glTranslatef((float)width / 2, (float)height / 2, 50); + glTranslatef(static_cast(width) / 2, static_cast(height) / 2, 50); float ss = 60 / (16 / 25.0f); glScalef(-ss, -ss, -ss); glRotatef(180, 0, 1, 0); diff --git a/Minecraft.Client/Texture.cpp b/Minecraft.Client/Texture.cpp index 809f606aa..b7e58d5fa 100644 --- a/Minecraft.Client/Texture.cpp +++ b/Minecraft.Client/Texture.cpp @@ -24,7 +24,7 @@ Texture::Texture(const wstring &name, int mode, int width, int height, int depth void Texture::_init(const wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap) { #ifdef __PS3__ - if(g_texBlitJobQueuePort == NULL) + if(g_texBlitJobQueuePort == nullptr) g_texBlitJobQueuePort = new C4JSpursJobQueue::Port("C4JSpursJob_Texture_blit"); #endif this->name = name; @@ -40,7 +40,7 @@ void Texture::_init(const wstring &name, int mode, int width, int height, int de m_bInitialised = false; for( int i = 0 ; i < 10; i++ ) { - data[i] = NULL; + data[i] = nullptr; } rect = new Rect2i(0, 0, width, height); @@ -105,7 +105,7 @@ void Texture::_init(const wstring &name, int mode, int width, int height, int de void Texture::_init(const wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) { _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, mipMap); - if (image == NULL) + if (image == nullptr) { if (width == -1 || height == -1) { @@ -195,7 +195,7 @@ Texture::~Texture() for(int i = 0; i < 10; i++ ) { - if(data[i] != NULL) delete data[i]; + if(data[i] != nullptr) delete data[i]; } if(glId >= 0) @@ -225,10 +225,10 @@ void Texture::fill(const Rect2i *rect, int color) int line = y * width * 4; for (int x = myRect->getX(); x < (myRect->getX() + myRect->getWidth()); x++) { - data[0]->put(line + x * 4 + 0, (BYTE)((color >> 24) & 0x000000ff)); - data[0]->put(line + x * 4 + 1, (BYTE)((color >> 16) & 0x000000ff)); - data[0]->put(line + x * 4 + 2, (BYTE)((color >> 8) & 0x000000ff)); - data[0]->put(line + x * 4 + 3, (BYTE)((color >> 0) & 0x000000ff)); + data[0]->put(line + x * 4 + 0, static_cast((color >> 24) & 0x000000ff)); + data[0]->put(line + x * 4 + 1, static_cast((color >> 16) & 0x000000ff)); + data[0]->put(line + x * 4 + 2, static_cast((color >> 8) & 0x000000ff)); + data[0]->put(line + x * 4 + 3, static_cast((color >> 0) & 0x000000ff)); } } delete myRect; @@ -258,7 +258,7 @@ void Texture::writeAsBMP(const wstring &name) outFile.delete(); } - DataOutputStream *outStream = NULL; + DataOutputStream *outStream = nullptr; //try { outStream = new DataOutputStream(new FileOutputStream(outFile)); //} catch (IOException e) { @@ -384,7 +384,7 @@ void Texture::blit(int x, int y, Texture *source, bool rotated) { ByteBuffer *srcBuffer = source->getData(level); - if(srcBuffer == NULL) break; + if(srcBuffer == nullptr) break; int yy = y >> level; int xx = x >> level; @@ -530,10 +530,10 @@ void Texture::transferFromBuffer(intArray buffer) { int texel = column + x * 4; data[0]->position(0); - data[0]->put(texel + byteRemap[0], (byte)((buffer[texel >> 2] >> 24) & 0xff)); - data[0]->put(texel + byteRemap[1], (byte)((buffer[texel >> 2] >> 16) & 0xff)); - data[0]->put(texel + byteRemap[2], (byte)((buffer[texel >> 2] >> 8) & 0xff)); - data[0]->put(texel + byteRemap[3], (byte)((buffer[texel >> 2] >> 0) & 0xff)); + data[0]->put(texel + byteRemap[0], static_cast((buffer[texel >> 2] >> 24) & 0xff)); + data[0]->put(texel + byteRemap[1], static_cast((buffer[texel >> 2] >> 16) & 0xff)); + data[0]->put(texel + byteRemap[2], static_cast((buffer[texel >> 2] >> 8) & 0xff)); + data[0]->put(texel + byteRemap[3], static_cast((buffer[texel >> 2] >> 0) & 0xff)); } } } @@ -589,19 +589,19 @@ void Texture::transferFromImage(BufferedImage *image) // Pull ARGB bytes into either RGBA or BGRA depending on format - tempBytes[byteIndex + byteRemap[0]] = (byte)((tempPixels[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (byte)((tempPixels[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (byte)((tempPixels[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (byte)((tempPixels[intIndex] >> 0) & 0xff); + tempBytes[byteIndex + byteRemap[0]] = static_cast((tempPixels[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = static_cast((tempPixels[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = static_cast((tempPixels[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = static_cast((tempPixels[intIndex] >> 0) & 0xff); } } for(int i = 0; i < 10; i++ ) { - if(data[i] != NULL) + if(data[i] != nullptr) { delete data[i]; - data[i] = NULL; + data[i] = nullptr; } } @@ -618,7 +618,7 @@ void Texture::transferFromImage(BufferedImage *image) delete [] tempBytes.data; - if(mipmapped || image->getData(1) != NULL) + if(mipmapped || image->getData(1) != nullptr) { mipmapped = true; for(unsigned int level = 1; level < MAX_MIP_LEVELS; ++level) @@ -641,10 +641,10 @@ void Texture::transferFromImage(BufferedImage *image) // Pull ARGB bytes into either RGBA or BGRA depending on format - tempBytes[byteIndex + byteRemap[0]] = (byte)((tempData[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (byte)((tempData[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (byte)((tempData[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (byte)((tempData[intIndex] >> 0) & 0xff); + tempBytes[byteIndex + byteRemap[0]] = static_cast((tempData[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = static_cast((tempData[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = static_cast((tempData[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = static_cast((tempData[intIndex] >> 0) & 0xff); } } } @@ -676,10 +676,10 @@ void Texture::transferFromImage(BufferedImage *image) // Pull ARGB bytes into either RGBA or BGRA depending on format - tempBytes[byteIndex + byteRemap[0]] = (byte)((col >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (byte)((col >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (byte)((col >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (byte)((col >> 0) & 0xff); + tempBytes[byteIndex + byteRemap[0]] = static_cast((col >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = static_cast((col >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = static_cast((col >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = static_cast((col >> 0) & 0xff); } } @@ -713,8 +713,8 @@ void Texture::transferFromImage(BufferedImage *image) // 4J Kept from older versions for where we create mip-maps for levels that do not have pre-made graphics int Texture::crispBlend(int c0, int c1) { - int a0 = (int) (((c0 & 0xff000000) >> 24)) & 0xff; - int a1 = (int) (((c1 & 0xff000000) >> 24)) & 0xff; + int a0 = static_cast(((c0 & 0xff000000) >> 24)) & 0xff; + int a1 = static_cast(((c1 & 0xff000000) >> 24)) & 0xff; int a = 255; if (a0 + a1 < 255) @@ -807,7 +807,7 @@ void Texture::updateOnGPU() { for (int level = 1; level < m_iMipLevels; level++) { - if(data[level] == NULL) break; + if(data[level] == nullptr) break; data[level]->flip(); } diff --git a/Minecraft.Client/Texture.h b/Minecraft.Client/Texture.h index 09b7495e9..5dcf2b481 100644 --- a/Minecraft.Client/Texture.h +++ b/Minecraft.Client/Texture.h @@ -59,7 +59,7 @@ private: #ifdef __PS3__ ByteBuffer_IO *data[10]; #else - ByteBuffer *data[10]; // Arrays for mipmaps - NULL if not used + ByteBuffer *data[10]; // Arrays for mipmaps - nullptr if not used #endif public: diff --git a/Minecraft.Client/TextureHolder.cpp b/Minecraft.Client/TextureHolder.cpp index 0f10272cf..11c8fb96b 100644 --- a/Minecraft.Client/TextureHolder.cpp +++ b/Minecraft.Client/TextureHolder.cpp @@ -22,12 +22,12 @@ Texture *TextureHolder::getTexture() int TextureHolder::getWidth() const { - return rotated ? smallestFittingMinTexel((int) (height * scale)) : smallestFittingMinTexel((int) (width * scale)); + return rotated ? smallestFittingMinTexel(static_cast(height * scale)) : smallestFittingMinTexel(static_cast(width * scale)); } int TextureHolder::getHeight() const { - return rotated ? smallestFittingMinTexel((int) (width * scale)) : smallestFittingMinTexel((int) (height * scale)); + return rotated ? smallestFittingMinTexel(static_cast(width * scale)) : smallestFittingMinTexel(static_cast(height * scale)); } void TextureHolder::rotate() @@ -52,7 +52,7 @@ void TextureHolder::setForcedScale(int targetSize) return; } - scale = (float) targetSize / min(width, height); + scale = static_cast(targetSize) / min(width, height); } //@Override diff --git a/Minecraft.Client/TextureManager.cpp b/Minecraft.Client/TextureManager.cpp index 542b94998..d6cbe2c33 100644 --- a/Minecraft.Client/TextureManager.cpp +++ b/Minecraft.Client/TextureManager.cpp @@ -7,7 +7,7 @@ #include "TextureManager.h" #include "..\Minecraft.World\StringHelpers.h" -TextureManager *TextureManager::instance = NULL; +TextureManager *TextureManager::instance = nullptr; void TextureManager::createInstance() { @@ -36,7 +36,7 @@ Texture *TextureManager::getTexture(const wstring &name) return idToTextureMap.find(stringToIDMap.find(name)->second)->second; } - return NULL; + return nullptr; } void TextureManager::registerName(const wstring &name, Texture *texture) @@ -136,7 +136,7 @@ vector *TextureManager::createTextures(const wstring &filename, bool for (int i = 0; i < frameCount; i++) { BufferedImage *subImage = image->getSubimage(0, frameHeight * i, frameWidth, frameHeight); - Texture *texture = createTexture(texName, mode, frameWidth, frameHeight, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, subImage); + Texture *texture = createTexture(texName, mode, frameWidth, frameHeight, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != nullptr, subImage); delete subImage; result->push_back(texture); } @@ -146,7 +146,7 @@ vector *TextureManager::createTextures(const wstring &filename, bool // TODO: Remove this hack -- fix proper rotation support (needed for 'off-aspect textures') if (width == height) { - result->push_back(createTexture(texName, mode, width, height, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, image)); + result->push_back(createTexture(texName, mode, width, height, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != nullptr, image)); } else { @@ -191,6 +191,6 @@ Texture *TextureManager::createTexture(const wstring &name, int mode, int width, Texture *TextureManager::createTexture(const wstring &name, int mode, int width, int height, int format, bool mipmap) { // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader - //return createTexture(name, mode, width, height, Texture::WM_CLAMP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); - return createTexture(name, mode, width, height, Texture::WM_WRAP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); + //return createTexture(name, mode, width, height, Texture::WM_CLAMP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, nullptr); + return createTexture(name, mode, width, height, Texture::WM_WRAP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, nullptr); } \ No newline at end of file diff --git a/Minecraft.Client/TextureMap.cpp b/Minecraft.Client/TextureMap.cpp index 9aefbb637..902dc9d66 100644 --- a/Minecraft.Client/TextureMap.cpp +++ b/Minecraft.Client/TextureMap.cpp @@ -22,8 +22,8 @@ TextureMap::TextureMap(int type, const wstring &name, const wstring &path, Buffe this->missingTexture = missingTexture; // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + missingPosition = nullptr; + stitchResult = nullptr; m_mipMap = mipmap; } @@ -37,7 +37,7 @@ void TextureMap::stitch() //for (Tile tile : Tile.tiles) for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { - if (Tile::tiles[i] != NULL) + if (Tile::tiles[i] != nullptr) { Tile::tiles[i]->registerIcons(this); } @@ -51,7 +51,7 @@ void TextureMap::stitch() for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) + if (item != nullptr && item->getIconType() == iconType) { item->registerIcons(this); } @@ -89,7 +89,7 @@ void TextureMap::stitch() // TODO: [EB] Put the frames into a proper object, not this inside out hack vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); - if (frames == NULL || frames->empty()) + if (frames == nullptr || frames->empty()) { continue; // Couldn't load a texture, skip it } @@ -124,7 +124,7 @@ void TextureMap::stitch() vector *frames = textures.find(textureHolder)->second; - StitchedTexture *stored = NULL; + StitchedTexture *stored = nullptr; auto itTex = texturesToRegister.find(textureName); if(itTex != texturesToRegister.end() ) stored = itTex->second; @@ -188,7 +188,7 @@ void TextureMap::stitch() StitchedTexture *TextureMap::getTexture(const wstring &name) { StitchedTexture *result = texturesByName.find(name)->second; - if (result == NULL) result = missingPosition; + if (result == nullptr) result = missingPosition; return result; } @@ -212,7 +212,7 @@ Icon *TextureMap::registerIcon(const wstring &name) { if (name.empty()) { - app.DebugPrintf("Don't register NULL\n"); + app.DebugPrintf("Don't register nullptr\n"); #ifndef _CONTENT_PACKAGE __debugbreak(); #endif @@ -220,11 +220,11 @@ Icon *TextureMap::registerIcon(const wstring &name) } // TODO: [EB]: Why do we allow multiple registrations? - StitchedTexture *result = NULL; + StitchedTexture *result = nullptr; auto it = texturesToRegister.find(name); if(it != texturesToRegister.end()) result = it->second; - if (result == NULL) + if (result == nullptr) { result = StitchedTexture::create(name); texturesToRegister.insert( stringStitchedTextureMap::value_type(name, result) ); diff --git a/Minecraft.Client/TexturePack.cpp b/Minecraft.Client/TexturePack.cpp index 7ed208ae3..bacb29516 100644 --- a/Minecraft.Client/TexturePack.cpp +++ b/Minecraft.Client/TexturePack.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "TexturePack.h" -wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/,const char *pchBDPatchFileName /*= NULL*/) +wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/,const char *pchBDPatchFileName /*= nullptr*/) { wstring wDrive; #ifdef _XBOX @@ -24,8 +24,8 @@ wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/,const char *pc #ifdef __PS3__ // 4J-PB - we need to check for a BD patch - this is going to be an issue for full DLC texture packs (Halloween) - char *pchUsrDir=NULL; - if(app.GetBootedFromDiscPatch() && pchBDPatchFileName!=NULL) + char *pchUsrDir=nullptr; + if(app.GetBootedFromDiscPatch() && pchBDPatchFileName!=nullptr) { pchUsrDir = app.GetBDUsrDirPath(pchBDPatchFileName); wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); diff --git a/Minecraft.Client/TexturePack.h b/Minecraft.Client/TexturePack.h index 23cb4f62e..8e6134233 100644 --- a/Minecraft.Client/TexturePack.h +++ b/Minecraft.Client/TexturePack.h @@ -35,11 +35,11 @@ public: */ return name; } - virtual DLCPack * getDLCPack() { return NULL;} + virtual DLCPack * getDLCPack() { return nullptr;} // 4J Added - virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=NULL); + virtual wstring getPath(bool bTitleUpdateTexture = false, const char *pchBDPatchFilename=nullptr); virtual wstring getAnimationString(const wstring &textureName, const wstring &path, bool allowFallback) = 0; virtual BufferedImage *getImageResource(const wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const wstring &drive =L"") = 0; virtual void loadColourTable() = 0; diff --git a/Minecraft.Client/TexturePackRepository.cpp b/Minecraft.Client/TexturePackRepository.cpp index 6bb3ccccb..ef926d78b 100644 --- a/Minecraft.Client/TexturePackRepository.cpp +++ b/Minecraft.Client/TexturePackRepository.cpp @@ -8,8 +8,9 @@ #include "..\Minecraft.World\File.h" #include "..\Minecraft.World\StringHelpers.h" #include "Minimap.h" +#include "Common/UI/UI.h" -TexturePack *TexturePackRepository::DEFAULT_TEXTURE_PACK = NULL; +TexturePack *TexturePackRepository::DEFAULT_TEXTURE_PACK = nullptr; TexturePackRepository::TexturePackRepository(File workingDirectory, Minecraft *minecraft) { @@ -17,7 +18,7 @@ TexturePackRepository::TexturePackRepository(File workingDirectory, Minecraft *m // 4J - added usingWeb = false; - selected = NULL; + selected = nullptr; texturePacks = new vector; this->minecraft = minecraft; @@ -28,9 +29,9 @@ TexturePackRepository::TexturePackRepository(File workingDirectory, Minecraft *m DEFAULT_TEXTURE_PACK->loadColourTable(); - m_dummyTexturePack = NULL; - m_dummyDLCTexturePack = NULL; - lastSelected = NULL; + m_dummyTexturePack = nullptr; + m_dummyDLCTexturePack = nullptr; + lastSelected = nullptr; updateList(); } @@ -49,13 +50,13 @@ void TexturePackRepository::addDebugPacks() { DLCPack *pack = app.m_dlcManager.getPack(L"DLCTestPack"); - if( pack != NULL && pack->IsCorrupt() ) + if( pack != nullptr && pack->IsCorrupt() ) { app.m_dlcManager.removePack(pack); - pack = NULL; + pack = nullptr; } - if(pack == NULL) + if(pack == nullptr) { wprintf(L"Pack \"%ls\" is not installed, so adding it\n", L"DLCTestPack"); pack = new DLCPack(L"DLCTestPack",0xffffffff); @@ -164,7 +165,7 @@ void TexturePackRepository::updateList() currentPacks->push_back(m_dummyTexturePack); cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; - if(m_dummyDLCTexturePack != NULL) + if(m_dummyDLCTexturePack != nullptr) { currentPacks->push_back(m_dummyDLCTexturePack); cacheById[m_dummyDLCTexturePack->getId()] = m_dummyDLCTexturePack; @@ -227,7 +228,7 @@ wstring TexturePackRepository::getIdOrNull(File file) return file.getName() + ":folder:" + file.lastModified(); } - return NULL; + return nullptr; #endif return L""; } @@ -357,17 +358,17 @@ TexturePack *TexturePackRepository::getTexturePackById(DWORD id) return it->second; } - return NULL; + return nullptr; } TexturePack *TexturePackRepository::addTexturePackFromDLC(DLCPack *dlcPack, DWORD id) { - TexturePack *newPack = NULL; + TexturePack *newPack = nullptr; // 4J-PB - The City texture pack went out with a child id for the texture pack of 1 instead of zero // we need to mask off the child id here to deal with this DWORD dwParentID=id&0xFFFFFF; // child id is <<24 and Or'd with parent - if(dlcPack != NULL) + if(dlcPack != nullptr) { newPack = new DLCTexturePack(dwParentID, dlcPack, DEFAULT_TEXTURE_PACK); texturePacks->push_back(newPack); @@ -408,7 +409,7 @@ void TexturePackRepository::removeTexturePackById(DWORD id) texturePacks->erase(it2); if(lastSelected == oldPack) { - lastSelected = NULL; + lastSelected = nullptr; } } m_texturePacksToDelete.push_back(oldPack); @@ -417,19 +418,19 @@ void TexturePackRepository::removeTexturePackById(DWORD id) void TexturePackRepository::updateUI() { - if(lastSelected != NULL && lastSelected != selected) + if(lastSelected != nullptr && lastSelected != selected) { lastSelected->unloadUI(); selected->loadUI(); Minimap::reloadColours(); ui.StartReloadSkinThread(); - lastSelected = NULL; + lastSelected = nullptr; } } bool TexturePackRepository::needsUIUpdate() { - return lastSelected != NULL && lastSelected != selected; + return lastSelected != nullptr && lastSelected != selected; } unsigned int TexturePackRepository::getTexturePackCount() @@ -439,7 +440,7 @@ unsigned int TexturePackRepository::getTexturePackCount() TexturePack *TexturePackRepository::getTexturePackByIndex(unsigned int index) { - TexturePack *pack = NULL; + TexturePack *pack = nullptr; if(index < texturePacks->size()) { pack = texturePacks->at(index); diff --git a/Minecraft.Client/Textures.cpp b/Minecraft.Client/Textures.cpp index 9a2e98a66..ba7c02821 100644 --- a/Minecraft.Client/Textures.cpp +++ b/Minecraft.Client/Textures.cpp @@ -288,7 +288,7 @@ void Textures::loadIndexedTextures() // 4J - added - preload a set of commonly used textures that can then be referenced directly be an enumerated type rather by string for( int i = 0; i < TN_COUNT - 2; i++ ) { - preLoadedIdx[i] = loadTexture((TEXTURE_NAME)i, wstring(preLoaded[i]) + L".png"); + preLoadedIdx[i] = loadTexture(static_cast(i), wstring(preLoaded[i]) + L".png"); } } @@ -299,15 +299,15 @@ intArray Textures::loadTexturePixels(TEXTURE_NAME texId, const wstring& resource { intArray id = pixelsMap[resourceName]; // 4J - if resourceName isn't in the map, it should add an element and as that will use the default constructor, its - // internal data pointer will be NULL - if (id.data != NULL) return id; + // internal data pointer will be nullptr + if (id.data != nullptr) return id; } // 4J - removed try/catch // try { intArray res; //wstring in = skin->getResource(resourceName); - if (false)// 4J - removed - was ( in == NULL) + if (false)// 4J - removed - was ( in == nullptr) { res = loadTexturePixels(missingNo); } @@ -451,14 +451,14 @@ void Textures::bindTextureLayers(ResourceLocation *resource) for( int i = 0; i < layers; i++ ) { TEXTURE_NAME textureName = resource->getTexture(i); - if( textureName == (_TEXTURE_NAME)-1 ) + if( textureName == static_cast<_TEXTURE_NAME>(-1) ) { continue; } wstring resourceName = wstring(preLoaded[textureName]) + L".png"; BufferedImage *image = readImage(textureName, resourceName); - if( image == NULL ) + if( image == nullptr ) { continue; } @@ -500,10 +500,10 @@ void Textures::bindTextureLayers(ResourceLocation *resource) float srcFactor = srcAlpha / outAlpha; float dstFactor = (dstAlpha * (1.0f - srcAlpha)) / outAlpha; - int outA = (int)(outAlpha * 255.0f + 0.5f); - int outR = (int)((((src >> 16) & 0xff) * srcFactor) + (((dst >> 16) & 0xff) * dstFactor) + 0.5f); - int outG = (int)((((src >> 8) & 0xff) * srcFactor) + (((dst >> 8) & 0xff) * dstFactor) + 0.5f); - int outB = (int)(((src & 0xff) * srcFactor) + ((dst & 0xff) * dstFactor) + 0.5f); + int outA = static_cast(outAlpha * 255.0f + 0.5f); + int outR = static_cast((((src >> 16) & 0xff) * srcFactor) + (((dst >> 16) & 0xff) * dstFactor) + 0.5f); + int outG = static_cast((((src >> 8) & 0xff) * srcFactor) + (((dst >> 8) & 0xff) * dstFactor) + 0.5f); + int outB = static_cast(((src & 0xff) * srcFactor) + ((dst & 0xff) * dstFactor) + 0.5f); mergedPixels[p] = (outA << 24) | (outR << 16) | (outG << 8) | outB; } } @@ -618,7 +618,7 @@ int Textures::loadTexture(TEXTURE_NAME texId, const wstring& resourceName) if (clamp) pathName = resourceName.substr(7); //wstring in = skins->getSelected()->getResource(pathName); - if (false ) // 4J - removed was ( in == NULL) + if (false ) // 4J - removed was ( in == nullptr) { loadTexture(missingNo, id, blur, clamp); } @@ -711,7 +711,7 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) intArray rawPixels(w*h); img->getRGB(0, 0, w, h, rawPixels, 0, w); - if (options != NULL && options->anaglyph3d) + if (options != nullptr && options->anaglyph3d) { rawPixels = anaglyph(rawPixels); } @@ -730,10 +730,10 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) newPixels[i * 4 + 2] = (byte) g; newPixels[i * 4 + 3] = (byte) b; #else - newPixels[i * 4 + 0] = (byte) r; - newPixels[i * 4 + 1] = (byte) g; - newPixels[i * 4 + 2] = (byte) b; - newPixels[i * 4 + 3] = (byte) a; + newPixels[i * 4 + 0] = static_cast(r); + newPixels[i * 4 + 1] = static_cast(g); + newPixels[i * 4 + 2] = static_cast(b); + newPixels[i * 4 + 3] = static_cast(a); #endif } // 4J - now creating a buffer of the size we require dynamically @@ -877,7 +877,7 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - if (options != NULL && options->anaglyph3d) + if (options != nullptr && options->anaglyph3d) { rawPixels = anaglyph(rawPixels); } @@ -890,7 +890,7 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) int g = (rawPixels[i] >> 8) & 0xff; int b = (rawPixels[i]) & 0xff; - if (options != NULL && options->anaglyph3d) + if (options != nullptr && options->anaglyph3d) { int rr = (r * 30 + g * 59 + b * 11) / 100; int gg = (r * 30 + g * 70) / (100); @@ -901,10 +901,10 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) b = bb; } - newPixels[i * 4 + 0] = (byte) r; - newPixels[i * 4 + 1] = (byte) g; - newPixels[i * 4 + 2] = (byte) b; - newPixels[i * 4 + 3] = (byte) a; + newPixels[i * 4 + 0] = static_cast(r); + newPixels[i * 4 + 1] = static_cast(g); + newPixels[i * 4 + 2] = static_cast(b); + newPixels[i * 4 + 3] = static_cast(a); } ByteBuffer *pixels = MemoryTracker::createByteBuffer(w * h * 4); // 4J - now creating dynamically pixels->put(newPixels); @@ -997,16 +997,23 @@ void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, int id) void Textures::releaseTexture(int id) { + if (id <= 0) return; loadedImages.erase(id); - glDeleteTextures(id); + // TextureFree() has no bounds check and crashes on stale IDs (e.g. after + // RenderManager.Initialise() which memsets the texture table to zero). + // TextureGetTexture() IS safe — returns NULL for invalid/unallocated IDs. + if (RenderManager.TextureGetTexture(id) != NULL) + { + glDeleteTextures(id); + } } int Textures::loadHttpTexture(const wstring& url, const wstring& backup) { HttpTexture *texture = httpTextures[url]; - if (texture != NULL) + if (texture != nullptr) { - if (texture->loadedImage != NULL && !texture->isLoaded) + if (texture->loadedImage != nullptr && !texture->isLoaded) { if (texture->id < 0) { @@ -1019,7 +1026,7 @@ int Textures::loadHttpTexture(const wstring& url, const wstring& backup) texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) + if (texture == nullptr || texture->id < 0) { if (backup.empty() ) return -1; return loadTexture(TN_COUNT, backup); @@ -1030,9 +1037,9 @@ int Textures::loadHttpTexture(const wstring& url, const wstring& backup) int Textures::loadHttpTexture(const wstring& url, int backup) { HttpTexture *texture = httpTextures[url]; - if (texture != NULL) + if (texture != nullptr) { - if (texture->loadedImage != NULL && !texture->isLoaded) + if (texture->loadedImage != nullptr && !texture->isLoaded) { if (texture->id < 0) { @@ -1045,7 +1052,7 @@ int Textures::loadHttpTexture(const wstring& url, int backup) texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) + if (texture == nullptr || texture->id < 0) { return loadTexture(backup); } @@ -1060,7 +1067,7 @@ bool Textures::hasHttpTexture(const wstring &url) HttpTexture *Textures::addHttpTexture(const wstring& url, HttpTextureProcessor *processor) { HttpTexture *texture = httpTextures[url]; - if (texture == NULL) + if (texture == nullptr) { httpTextures[url] = new HttpTexture(url, processor); } @@ -1074,7 +1081,7 @@ HttpTexture *Textures::addHttpTexture(const wstring& url, HttpTextureProcessor * void Textures::removeHttpTexture(const wstring& url) { HttpTexture *texture = httpTextures[url]; - if (texture != NULL) + if (texture != nullptr) { texture->count--; if (texture->count == 0) @@ -1088,20 +1095,20 @@ void Textures::removeHttpTexture(const wstring& url) // 4J-PB - adding for texture in memory (from global title storage) int Textures::loadMemTexture(const wstring& url, const wstring& backup) { - MemTexture *texture = NULL; + MemTexture *texture = nullptr; auto it = memTextures.find(url); if (it != memTextures.end()) { texture = (*it).second; } - if(texture == NULL && app.IsFileInMemoryTextures(url)) + if(texture == nullptr && app.IsFileInMemoryTextures(url)) { // If we haven't loaded it yet, but we have the data for it then add it texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); } - if(texture != NULL) + if(texture != nullptr) { - if (texture->loadedImage != NULL && !texture->isLoaded) + if (texture->loadedImage != nullptr && !texture->isLoaded) { // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo if( ( url.substr(0,7) == L"dlcskin" ) || @@ -1122,7 +1129,7 @@ int Textures::loadMemTexture(const wstring& url, const wstring& backup) MIPMAP = true; } } - if (texture == NULL || texture->id < 0) + if (texture == nullptr || texture->id < 0) { if (backup.empty() ) return -1; return loadTexture(TN_COUNT,backup); @@ -1132,21 +1139,21 @@ int Textures::loadMemTexture(const wstring& url, const wstring& backup) int Textures::loadMemTexture(const wstring& url, int backup) { - MemTexture *texture = NULL; + MemTexture *texture = nullptr; auto it = memTextures.find(url); if (it != memTextures.end()) { texture = (*it).second; } - if(texture == NULL && app.IsFileInMemoryTextures(url)) + if(texture == nullptr && app.IsFileInMemoryTextures(url)) { // If we haven't loaded it yet, but we have the data for it then add it texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); } - if(texture != NULL) + if(texture != nullptr) { texture->ticksSinceLastUse = 0; - if (texture->loadedImage != NULL && !texture->isLoaded) + if (texture->loadedImage != nullptr && !texture->isLoaded) { // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo if( ( url.substr(0,7) == L"dlcskin" ) || @@ -1166,7 +1173,7 @@ int Textures::loadMemTexture(const wstring& url, int backup) MIPMAP = true; } } - if (texture == NULL || texture->id < 0) + if (texture == nullptr || texture->id < 0) { return loadTexture(backup); } @@ -1175,16 +1182,16 @@ int Textures::loadMemTexture(const wstring& url, int backup) MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *processor) { - MemTexture *texture = NULL; + MemTexture *texture = nullptr; auto it = memTextures.find(name); if (it != memTextures.end()) { texture = (*it).second; } - if(texture == NULL) + if(texture == nullptr) { // can we find it in the app mem files? - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwBytes=0; app.GetMemFileDetails(name,&pbData,&dwBytes); @@ -1196,7 +1203,7 @@ MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *pro else { // 4J Stu - Make an entry for this anyway and we can populate it later - memTextures[name] = NULL; + memTextures[name] = nullptr; } } else @@ -1212,7 +1219,7 @@ MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *pro // MemTexture *Textures::getMemTexture(const wstring& url, MemTextureProcessor *processor) // { // MemTexture *texture = memTextures[url]; -// if (texture != NULL) +// if (texture != nullptr) // { // texture->count++; // } @@ -1221,16 +1228,16 @@ MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *pro void Textures::removeMemTexture(const wstring& url) { - MemTexture *texture = NULL; + MemTexture *texture = nullptr; auto it = memTextures.find(url); if (it != memTextures.end()) { texture = (*it).second; - // If it's NULL then we should just remove the entry - if( texture == NULL ) memTextures.erase(url); + // If it's nullptr then we should just remove the entry + if( texture == nullptr ) memTextures.erase(url); } - if(texture != NULL) + if(texture != nullptr) { texture->count--; if (texture->count == 0) @@ -1380,7 +1387,7 @@ Icon *Textures::getMissingIcon(int type) BufferedImage *Textures::readImage(TEXTURE_NAME texId, const wstring& name) // 4J was InputStream *in { - BufferedImage *img=NULL; + BufferedImage *img=nullptr; MemSect(32); // is this image one of the Title Update ones? bool isTu = IsTUImage(texId, name); @@ -1534,7 +1541,7 @@ const wchar_t *TUImagePaths[] = // - NULL + nullptr }; bool Textures::IsTUImage(TEXTURE_NAME texId, const wstring& name) @@ -1583,7 +1590,7 @@ const wchar_t *OriginalImagesPaths[] = { L"misc/watercolor.png", - NULL + nullptr }; bool Textures::IsOriginalImage(TEXTURE_NAME texId, const wstring& name) diff --git a/Minecraft.Client/TheEndPortalRenderer.cpp b/Minecraft.Client/TheEndPortalRenderer.cpp index 98c7e7cc5..c709cfd18 100644 --- a/Minecraft.Client/TheEndPortalRenderer.cpp +++ b/Minecraft.Client/TheEndPortalRenderer.cpp @@ -16,9 +16,9 @@ void TheEndPortalRenderer::render(shared_ptr _table, double x, doubl { // 4J Convert as we aren't using a templated class shared_ptr table = dynamic_pointer_cast(_table); - float xx = (float) tileEntityRenderDispatcher->xPlayer; - float yy = (float) tileEntityRenderDispatcher->yPlayer; - float zz = (float) tileEntityRenderDispatcher->zPlayer; + float xx = static_cast(tileEntityRenderDispatcher->xPlayer); + float yy = static_cast(tileEntityRenderDispatcher->yPlayer); + float zz = static_cast(tileEntityRenderDispatcher->zPlayer); glDisable(GL_LIGHTING); @@ -50,12 +50,12 @@ void TheEndPortalRenderer::render(shared_ptr _table, double x, doubl sscale = 1 / 2.0f; } - float dd = (float) -(y + hoff); + float dd = static_cast(-(y + hoff)); { float ss1 = (float) (dd + Camera::yPlayerOffs); float ss2 = (float) (dd + dist + Camera::yPlayerOffs); float s = ss1 / ss2; - s = (float) (y + hoff) + s; + s = static_cast(y + hoff) + s; glTranslatef(xx, s, zz); } diff --git a/Minecraft.Client/TileEntityRenderDispatcher.cpp b/Minecraft.Client/TileEntityRenderDispatcher.cpp index 887663fe1..5a1519c7f 100644 --- a/Minecraft.Client/TileEntityRenderDispatcher.cpp +++ b/Minecraft.Client/TileEntityRenderDispatcher.cpp @@ -15,7 +15,7 @@ #include "EnderChestRenderer.h" #include "BeaconRenderer.h" -TileEntityRenderDispatcher *TileEntityRenderDispatcher::instance = NULL; +TileEntityRenderDispatcher *TileEntityRenderDispatcher::instance = nullptr; double TileEntityRenderDispatcher::xOff = 0; double TileEntityRenderDispatcher::yOff = 0; double TileEntityRenderDispatcher::zOff = 0; @@ -28,9 +28,9 @@ void TileEntityRenderDispatcher::staticCtor() TileEntityRenderDispatcher::TileEntityRenderDispatcher() { // 4J -a dded - font = NULL; - textures = NULL; - level = NULL; + font = nullptr; + textures = nullptr; + level = nullptr; cameraEntity = nullptr; playerRotY = 0.0f; playerRotX = 0.0f;; @@ -45,7 +45,7 @@ TileEntityRenderDispatcher::TileEntityRenderDispatcher() renderers[eTYPE_ENCHANTMENTTABLEENTITY] = new EnchantTableRenderer(); renderers[eTYPE_THEENDPORTALTILEENTITY] = new TheEndPortalRenderer(); renderers[eTYPE_SKULLTILEENTITY] = new SkullTileRenderer(); - renderers[eTYPE_FURNACETILEENTITY] = NULL; + renderers[eTYPE_FURNACETILEENTITY] = nullptr; renderers[eTYPE_BEACONTILEENTITY] = new BeaconRenderer(); glDisable(GL_LIGHTING); @@ -57,13 +57,13 @@ TileEntityRenderDispatcher::TileEntityRenderDispatcher() TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) { - TileEntityRenderer *r = NULL; + TileEntityRenderer *r = nullptr; //TileEntityRenderer *r = renderers[e]; auto it = renderers.find(e); // 4J Stu - The .at and [] accessors insert elements if they don't exist if( it == renderers.end() ) { - return NULL; + return nullptr; } /* 4J - not doing this hierarchical search anymore. We need to explicitly add renderers for any eINSTANCEOF type that we want to be able to render @@ -83,12 +83,12 @@ TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) bool TileEntityRenderDispatcher::hasRenderer(shared_ptr e) { - return getRenderer(e) != NULL; + return getRenderer(e) != nullptr; } TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(shared_ptr e) { - if (e == NULL) return NULL; + if (e == nullptr) return nullptr; return getRenderer(e->GetType()); } @@ -135,7 +135,7 @@ void TileEntityRenderDispatcher::render(shared_ptr e, float a, bool void TileEntityRenderDispatcher::render(shared_ptr entity, double x, double y, double z, float a, bool setColor/*=true*/, float alpha, bool useCompiled) { TileEntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) + if (renderer != nullptr) { renderer->render(entity, x, y, z, a, setColor, alpha, useCompiled); } diff --git a/Minecraft.Client/TileEntityRenderer.cpp b/Minecraft.Client/TileEntityRenderer.cpp index 94bdd39ce..86bfee7b2 100644 --- a/Minecraft.Client/TileEntityRenderer.cpp +++ b/Minecraft.Client/TileEntityRenderer.cpp @@ -5,13 +5,13 @@ void TileEntityRenderer::bindTexture(ResourceLocation *location) { Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadTexture(location->getTexture())); + if(t != nullptr) t->bind(t->loadTexture(location->getTexture())); } void TileEntityRenderer::bindTexture(const wstring& urlTexture, ResourceLocation *location) { Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadHttpTexture(urlTexture, location->getTexture())); + if(t != nullptr) t->bind(t->loadHttpTexture(urlTexture, location->getTexture())); } Level *TileEntityRenderer::getLevel() diff --git a/Minecraft.Client/TileRenderer.cpp b/Minecraft.Client/TileRenderer.cpp index 4735b9416..b77729ab5 100644 --- a/Minecraft.Client/TileRenderer.cpp +++ b/Minecraft.Client/TileRenderer.cpp @@ -19,7 +19,7 @@ const float smallUV = ( 1.0f / 16.0f ); void TileRenderer::_init() { - fixedTexture = NULL; + fixedTexture = nullptr; xFlipTexture = false; noCulling = false; applyAmbienceOcclusion = false; @@ -44,7 +44,7 @@ void TileRenderer::_init() xMin = 0; yMin = 0; zMin = 0; - cache = NULL; + cache = nullptr; } bool TileRenderer::isTranslucentAt(LevelSource *level, int x, int y, int z) @@ -131,7 +131,7 @@ int TileRenderer::getLightColor( Tile *tt, LevelSource *level, int x, int y, int // Tiles that were determined to be invisible (by being surrounded by solid stuff) will be set to 255 rather than their actual ID if( ucTileId != 255 ) { - tileId = (int)ucTileId; + tileId = static_cast(ucTileId); } } int ret = tt->getLightColor(level, x, y, z, tileId); @@ -170,7 +170,7 @@ TileRenderer::TileRenderer( LevelSource* level ) TileRenderer::TileRenderer() { - this->level = NULL; + this->level = nullptr; _init(); } @@ -181,7 +181,7 @@ void TileRenderer::setFixedTexture( Icon *fixedTexture ) void TileRenderer::clearFixedTexture() { - this->fixedTexture = NULL; + this->fixedTexture = nullptr; } bool TileRenderer::hasFixedTexture() @@ -195,7 +195,7 @@ bool TileRenderer::hasFixedTexture() } #endif - return fixedTexture != NULL; + return fixedTexture != nullptr; } void TileRenderer::setShape(float x0, float y0, float z0, float x1, float y1, float z1) @@ -347,7 +347,7 @@ bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceDat retVal = tesselateTorchInWorld( tt, x, y, z ); break; case Tile::SHAPE_FIRE: - retVal = tesselateFireInWorld( (FireTile *)tt, x, y, z ); + retVal = tesselateFireInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_RED_DUST: retVal = tesselateDustInWorld( tt, x, y, z ); @@ -359,19 +359,19 @@ bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceDat retVal = tesselateDoorInWorld( tt, x, y, z ); break; case Tile::SHAPE_RAIL: - retVal = tesselateRailInWorld( ( RailTile* )tt, x, y, z ); + retVal = tesselateRailInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_STAIRS: - retVal = tesselateStairsInWorld( (StairTile *)tt, x, y, z ); + retVal = tesselateStairsInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_EGG: - retVal = tesselateEggInWorld((EggTile*) tt, x, y, z); + retVal = tesselateEggInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_FENCE: - retVal = tesselateFenceInWorld( ( FenceTile* )tt, x, y, z ); + retVal = tesselateFenceInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_WALL: - retVal = tesselateWallInWorld( (WallTile *) tt, x, y, z); + retVal = tesselateWallInWorld( static_cast(tt), x, y, z); break; case Tile::SHAPE_LEVER: retVal = tesselateLeverInWorld( tt, x, y, z ); @@ -386,13 +386,13 @@ bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceDat retVal = tesselateBedInWorld( tt, x, y, z ); break; case Tile::SHAPE_REPEATER: - retVal = tesselateRepeaterInWorld((RepeaterTile *)tt, x, y, z); + retVal = tesselateRepeaterInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_DIODE: - retVal = tesselateDiodeInWorld( (DiodeTile *)tt, x, y, z ); + retVal = tesselateDiodeInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_COMPARATOR: - retVal = tesselateComparatorInWorld((ComparatorTile *)tt, x, y, z); + retVal = tesselateComparatorInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_PISTON_BASE: retVal = tesselatePistonBaseInWorld( tt, x, y, z, false, forceData ); @@ -401,7 +401,7 @@ bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceDat retVal = tesselatePistonExtensionInWorld( tt, x, y, z, true, forceData ); break; case Tile::SHAPE_IRON_FENCE: - retVal = tesselateThinFenceInWorld( ( ThinFenceTile* )tt, x, y, z ); + retVal = tesselateThinFenceInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_THIN_PANE: retVal = tesselateThinPaneInWorld(tt, x, y, z); @@ -410,25 +410,25 @@ bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceDat retVal = tesselateVineInWorld( tt, x, y, z ); break; case Tile::SHAPE_FENCE_GATE: - retVal = tesselateFenceGateInWorld( ( FenceGateTile* )tt, x, y, z ); + retVal = tesselateFenceGateInWorld( static_cast(tt), x, y, z ); break; case Tile::SHAPE_CAULDRON: - retVal = tesselateCauldronInWorld((CauldronTile* ) tt, x, y, z); + retVal = tesselateCauldronInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_FLOWER_POT: - retVal = tesselateFlowerPotInWorld((FlowerPotTile *) tt, x, y, z); + retVal = tesselateFlowerPotInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_ANVIL: - retVal = tesselateAnvilInWorld((AnvilTile *) tt, x, y, z); + retVal = tesselateAnvilInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_BREWING_STAND: - retVal = tesselateBrewingStandInWorld((BrewingStandTile* ) tt, x, y, z); + retVal = tesselateBrewingStandInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_PORTAL_FRAME: - retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile *)tt, x, y, z); + retVal = tesselateAirPortalFrameInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_COCOA: - retVal = tesselateCocoaInWorld((CocoaTile *)tt, x, y, z); + retVal = tesselateCocoaInWorld(static_cast(tt), x, y, z); break; case Tile::SHAPE_BEACON: retVal = tesselateBeaconInWorld(tt, x, y, z); @@ -907,7 +907,7 @@ bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, in float xOff = 0; float yOff = 4; float zOff = 0; - Tile *plant = NULL; + Tile *plant = nullptr; switch (type) { @@ -927,7 +927,7 @@ bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, in t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); - if (plant != NULL) + if (plant != nullptr) { tesselateInWorld(plant, x, y, z); } @@ -1160,23 +1160,23 @@ bool TileRenderer::tesselateTorchInWorld( Tile* tt, int x, int y, int z ) float h = 0.20f; if ( dir == 1 ) { - tesselateTorch( tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x) - r2, static_cast(y) + h, static_cast(z), -r, 0.0f, 0 ); } else if ( dir == 2 ) { - tesselateTorch( tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x) + r2, static_cast(y) + h, static_cast(z), +r, 0.0f, 0 ); } else if ( dir == 3 ) { - tesselateTorch( tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y) + h, z - r2, 0.0f, -r, 0 ); } else if ( dir == 4 ) { - tesselateTorch( tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y) + h, static_cast(z) + r2, 0.0f, +r, 0 ); } else { - tesselateTorch( tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0 ); + tesselateTorch( tt, static_cast(x), static_cast(y), static_cast(z), 0.0f, 0.0f, 0 ); } return true; @@ -1257,7 +1257,7 @@ bool TileRenderer::tesselateRepeaterInWorld(RepeaterTile *tt, int x, int y, int south = 14.f; break; } - setShape(west / 16.0f + (float) transmitterX, 2.f / 16.0f, north / 16.0f + (float) transmitterZ, east / 16.0f + (float) transmitterX, 4.f / 16.0f, south / 16.0f + (float) transmitterZ); + setShape(west / 16.0f + static_cast(transmitterX), 2.f / 16.0f, north / 16.0f + static_cast(transmitterZ), east / 16.0f + static_cast(transmitterX), 4.f / 16.0f, south / 16.0f + static_cast(transmitterZ)); double u0 = lockTex->getU(west); double v0 = lockTex->getV(north); double u1 = lockTex->getU(east); @@ -1503,7 +1503,7 @@ bool TileRenderer::tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bo } // weird way of telling the piston to use the // "inside" texture for the forward-facing edge - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); + static_cast(tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); tesselateBlockInWorld( tt, x, y, z ); northFlip = FLIP_NONE; southFlip = FLIP_NONE; @@ -1511,7 +1511,7 @@ bool TileRenderer::tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bo westFlip = FLIP_NONE; upFlip = FLIP_NONE; downFlip = FLIP_NONE; - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); + static_cast(tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); } else { @@ -1902,7 +1902,7 @@ bool TileRenderer::tesselateLeverInWorld( Tile* tt, int x, int y, int z ) } } - Vec3* c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + Vec3* c0 = nullptr, *c1 = nullptr, *c2 = nullptr, *c3 = nullptr; for ( int i = 0; i < 6; i++ ) { if ( i == 0 ) @@ -1961,10 +1961,10 @@ bool TileRenderer::tesselateLeverInWorld( Tile* tt, int x, int y, int z ) c2 = corners[7]; c3 = corners[4]; } - t->vertexUV( ( float )( c0->x ), ( float )( c0->y ), ( float )( c0->z ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c1->x ), ( float )( c1->y ), ( float )( c1->z ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c2->x ), ( float )( c2->y ), ( float )( c2->z ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( c3->x ), ( float )( c3->y ), ( float )( c3->z ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(c0->x), static_cast(c0->y), static_cast(c0->z), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(c1->x), static_cast(c1->y), static_cast(c1->z), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(c2->x), static_cast(c2->y), static_cast(c2->z), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(c3->x), static_cast(c3->y), static_cast(c3->z), ( float )( u0 ), ( float )( v0 ) ); } return true; @@ -2073,7 +2073,7 @@ bool TileRenderer::tesselateTripwireSourceInWorld(Tile *tt, int x, int y, int z) corners[i]->z += z + 0.5; } - Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + Vec3 *c0 = nullptr, *c1 = nullptr, *c2 = nullptr, *c3 = nullptr; int stickX0 = 7; int stickX1 = 9; int stickY0 = 9; @@ -2491,15 +2491,15 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) float z0_ = z + 0.5f - 0.3f; float z1_ = z + 0.5f + 0.3f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 1), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u0 ), ( float )( v0 ) ); tex = secondTex; u0 = tex->getU0(true); @@ -2507,15 +2507,15 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) u1 = tex->getU1(true); v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); x0 = x + 0.5f - 0.5f; x1 = x + 0.5f + 0.5f; @@ -2527,15 +2527,15 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) z0_ = z + 0.5f - 0.4f; z1_ = z + 0.5f + 0.4f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), static_cast(z + 1), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 1), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), static_cast(z + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1_ ), ( float )( y + h ), static_cast(z + 0), ( float )( u1 ), ( float )( v0 ) ); tex = firstTex; u0 = tex->getU0(true); @@ -2543,15 +2543,15 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) u1 = tex->getU1(true); v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 0), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); } else { @@ -2595,10 +2595,10 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) { t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1 - 0), ( float )( y + 0 + yo ), ( float )( z + + 0.0f ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x + 1 - 0), ( float )( y + 0 + yo ), ( float )( z + + 1.0f ), ( float )( u1 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + 1.0f ), ( float )( u1 ), ( float )( v0 ) ); @@ -2674,14 +2674,14 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) if ( ( ( x + y + z ) & 1 ) == 0 ) { - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x0_), ( float )( y + h ), static_cast(z + + 0), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x0), static_cast(y + 0), static_cast(z + + 0), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x0), static_cast(y + 0), static_cast(z + + 1), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x0_), ( float )( y + h ), static_cast(z + + 1), ( float )( u0 ), ( float )( v0 ) ); tex = secondTex; u0 = tex->getU0(true); @@ -2689,25 +2689,25 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) u1 = tex->getU1(true); v1 = tex->getV1(true); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x1_), ( float )( y + h ), ( float )( z + + 1.0f ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV( static_cast(x1), ( float )( y + 0.0f ), ( float )( z + + 1.0f ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x1), ( float )( y + 0.0f ), static_cast(z + + 0), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( static_cast(x1_), ( float )( y + h ), static_cast(z + + 0), ( float )( u0 ), ( float )( v0 ) ); } else { t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + h ), static_cast(z1_), ( float )( u1 ), ( float )( v0 ) ); t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + 0.0f ), static_cast(z1), ( float )( u1 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); + 0.0f ), static_cast(z1), ( float )( u0 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + h ), static_cast(z1_), ( float )( u0 ), ( float )( v0 ) ); tex = secondTex; u0 = tex->getU0(true); @@ -2716,13 +2716,13 @@ bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) v1 = tex->getV1(true); t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); + h ), static_cast(z0_), ( float )( u1 ), ( float )( v0 ) ); t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); + 0.0f ), static_cast(z0), ( float )( u1 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + 0.0f ), static_cast(z0), ( float )( u0 ), ( float )( v1 ) ); t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + h ), static_cast(z0_), ( float )( u0 ), ( float )( v0 ) ); } } } @@ -2838,13 +2838,13 @@ bool TileRenderer::tesselateDustInWorld( Tile* tt, int x, int y, int z ) int v1 = SharedConstants::WORLD_RESOLUTION; int cutDistance = 5; - if (!w) x0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; + if (!w) x0 += cutDistance / static_cast(SharedConstants::WORLD_RESOLUTION); if (!w) u0 += cutDistance; - if (!e) x1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; + if (!e) x1 -= cutDistance / static_cast(SharedConstants::WORLD_RESOLUTION); if (!e) u1 -= cutDistance; - if (!n) z0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; + if (!n) z0 += cutDistance / static_cast(SharedConstants::WORLD_RESOLUTION); if (!n) v0 += cutDistance; - if (!s) z1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; + if (!s) z1 -= cutDistance / static_cast(SharedConstants::WORLD_RESOLUTION); if (!s) v1 -= cutDistance; t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTexture->getU(u1, true), crossTexture->getV(v1) ); t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTexture->getU(u1, true), crossTexture->getV(v0) ); @@ -2891,58 +2891,58 @@ bool TileRenderer::tesselateDustInWorld( Tile* tt, int x, int y, int z ) if ( level->isSolidBlockingTile( x - 1, y, z ) && level->getTile( x - 1, y + 1, z ) == Tile::redStoneDust_Id ) { t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 1), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->vertexUV( ( float )( x + dustOffset ), static_cast(y + 0), static_cast(z + 1), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->vertexUV( ( float )( x + dustOffset ), static_cast(y + 0), static_cast(z + 0), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 0), lineTexture->getU1(true), lineTexture->getV1(true) ); t->color( br, br, br ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 1), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( ( float )( x + overlayOffset ), static_cast(y + 0), static_cast(z + 1), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( ( float )( x + overlayOffset ), static_cast(y + 0), static_cast(z + 0), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 0), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); } if ( level->isSolidBlockingTile( x + 1, y, z ) && level->getTile( x + 1, y + 1, z ) == Tile::redStoneDust_Id ) { t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->vertexUV( ( float )( x + 1 - dustOffset ), static_cast(y + 0), static_cast(z + 1), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 1), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 0), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->vertexUV( ( float )( x + 1 - dustOffset ), static_cast(y + 0), static_cast(z + 0), lineTexture->getU0(true), lineTexture->getV0(true) ); t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( ( float )( x + 1 - overlayOffset ), static_cast(y + 0), static_cast(z + 1), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 1), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), static_cast(z + 0), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( ( float )( x + 1 - overlayOffset ), static_cast(y + 0), static_cast(z + 0), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); } if ( level->isSolidBlockingTile( x, y, z - 1 ) && level->getTile( x, y + 1, z - 1 ) == Tile::redStoneDust_Id ) { t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->vertexUV( static_cast(x + 1), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->vertexUV( static_cast(x + 0), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( static_cast(x + 1), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( static_cast(x + 0), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); } if ( level->isSolidBlockingTile( x, y, z + 1 ) && level->getTile( x, y + 1, z + 1 ) == Tile::redStoneDust_Id ) { t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->vertexUV( static_cast(x + 1), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->vertexUV( static_cast(x + 0), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( static_cast(x + 1), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( static_cast(x + 1), static_cast(y + 0), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); + t->vertexUV( static_cast(x + 0), static_cast(y + 0), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); + t->vertexUV( static_cast(x + 0), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); } } @@ -2982,15 +2982,15 @@ bool TileRenderer::tesselateRailInWorld( RailTile* tt, int x, int y, int z ) float r = 1 / 16.0f; - float x0 = ( float )( x + 1 ); - float x1 = ( float )( x + 1 ); - float x2 = ( float )( x + 0 ); - float x3 = ( float )( x + 0 ); + float x0 = static_cast(x + 1); + float x1 = static_cast(x + 1); + float x2 = static_cast(x + 0); + float x3 = static_cast(x + 0); - float z0 = ( float )( z + 0 ); - float z1 = ( float )( z + 1 ); - float z2 = ( float )( z + 1 ); - float z3 = ( float )( z + 0 ); + float z0 = static_cast(z + 0); + float z1 = static_cast(z + 1); + float z2 = static_cast(z + 1); + float z3 = static_cast(z + 0); float y0 = ( float )( y + r ); float y1 = ( float )( y + r ); @@ -2999,24 +2999,24 @@ bool TileRenderer::tesselateRailInWorld( RailTile* tt, int x, int y, int z ) if ( data == 1 || data == 2 || data == 3 || data == 7 ) { - x0 = x3 = ( float )( x + 1 ); - x1 = x2 = ( float )( x + 0 ); - z0 = z1 = ( float )( z + 1 ); - z2 = z3 = ( float )( z + 0 ); + x0 = x3 = static_cast(x + 1); + x1 = x2 = static_cast(x + 0); + z0 = z1 = static_cast(z + 1); + z2 = z3 = static_cast(z + 0); } else if ( data == 8 ) { - x0 = x1 = ( float )( x + 0 ); - x2 = x3 = ( float )( x + 1 ); - z0 = z3 = ( float )( z + 1 ); - z1 = z2 = ( float )( z + 0 ); + x0 = x1 = static_cast(x + 0); + x2 = x3 = static_cast(x + 1); + z0 = z3 = static_cast(z + 1); + z1 = z2 = static_cast(z + 0); } else if ( data == 9 ) { - x0 = x3 = ( float )( x + 0 ); - x1 = x2 = ( float )( x + 1 ); - z0 = z1 = ( float )( z + 0 ); - z2 = z3 = ( float )( z + 1 ); + x0 = x3 = static_cast(x + 0); + x1 = x2 = static_cast(x + 1); + z0 = z1 = static_cast(z + 0); + z2 = z3 = static_cast(z + 1); } if ( data == 2 || data == 4 ) @@ -3241,7 +3241,7 @@ bool TileRenderer::tesselateThinPaneInWorld(Tile *tt, int x, int y, int z) Icon *tex; Icon *edgeTex; - bool stained = dynamic_cast(tt) != NULL; + bool stained = dynamic_cast(tt) != nullptr; if (hasFixedTexture()) { tex = fixedTexture; @@ -3251,7 +3251,7 @@ bool TileRenderer::tesselateThinPaneInWorld(Tile *tt, int x, int y, int z) { int data = level->getData(x, y, z); tex = getTexture(tt, 0, data); - edgeTex = (stained) ? ((StainedGlassPaneBlock *) tt)->getEdgeTexture(data) : ((ThinFenceTile *) tt)->getEdgeTexture(); + edgeTex = (stained) ? static_cast(tt)->getEdgeTexture(data) : static_cast(tt)->getEdgeTexture(); } double u0 = tex->getU0(); @@ -3277,10 +3277,10 @@ bool TileRenderer::tesselateThinPaneInWorld(Tile *tt, int x, int y, int z) double iz0 = z + .5 - 1.0 / 16.0; double iz1 = z + .5 + 1.0 / 16.0; - bool n = (stained) ? ((StainedGlassPaneBlock *)tt)->attachsTo(level->getTile(x, y, z - 1)) : ((ThinFenceTile *)tt)->attachsTo(level->getTile(x, y, z - 1)); - bool s = (stained) ? ((StainedGlassPaneBlock *)tt)->attachsTo(level->getTile(x, y, z + 1)) : ((ThinFenceTile *)tt)->attachsTo(level->getTile(x, y, z + 1)); - bool w = (stained) ? ((StainedGlassPaneBlock *)tt)->attachsTo(level->getTile(x - 1, y, z)) : ((ThinFenceTile *)tt)->attachsTo(level->getTile(x - 1, y, z)); - bool e = (stained) ? ((StainedGlassPaneBlock *)tt)->attachsTo(level->getTile(x + 1, y, z)) : ((ThinFenceTile *)tt)->attachsTo(level->getTile(x + 1, y, z)); + bool n = (stained) ? static_cast(tt)->attachsTo(level->getTile(x, y, z - 1)) : static_cast(tt)->attachsTo(level->getTile(x, y, z - 1)); + bool s = (stained) ? static_cast(tt)->attachsTo(level->getTile(x, y, z + 1)) : static_cast(tt)->attachsTo(level->getTile(x, y, z + 1)); + bool w = (stained) ? static_cast(tt)->attachsTo(level->getTile(x - 1, y, z)) : static_cast(tt)->attachsTo(level->getTile(x - 1, y, z)); + bool e = (stained) ? static_cast(tt)->attachsTo(level->getTile(x + 1, y, z)) : static_cast(tt)->attachsTo(level->getTile(x + 1, y, z)); double noZFightingOffset = 0.001; double yt = 1.0 - noZFightingOffset; @@ -3691,10 +3691,10 @@ bool TileRenderer::tesselateThinFenceInWorld( ThinFenceTile* tt, int x, int y, i float iv1 = edgeTex->getV(8, true); float iv2 = edgeTex->getV1(true); - float x0 = (float)x; + float x0 = static_cast(x); float x1 = x + 0.5f; float x2 = x + 1.0f; - float z0 = (float)z; + float z0 = static_cast(z); float z1 = z + 0.5f; float z2 = z + 1.0f; float ix0 = x + 0.5f - 1.0f / 16.0f; @@ -4161,9 +4161,9 @@ bool TileRenderer::tesselateCrossInWorld( Tile* tt, int x, int y, int z ) } t->color( br * r, br * g, br * b ); - float xt = (float)x; - float yt = (float)y; - float zt = (float)z; + float xt = static_cast(x); + float yt = static_cast(y); + float zt = static_cast(z); if (tt == Tile::tallgrass) { @@ -4181,7 +4181,7 @@ bool TileRenderer::tesselateCrossInWorld( Tile* tt, int x, int y, int z ) bool TileRenderer::tesselateStemInWorld( Tile* _tt, int x, int y, int z ) { - StemTile* tt = ( StemTile* )_tt; + StemTile* tt = static_cast(_tt); Tesselator* t = Tesselator::getInstance(); float br; @@ -4409,7 +4409,7 @@ bool TileRenderer::tesselateLilypadInWorld(Tile *tt, int x, int y, int z) int64_t seed = (x * 3129871) ^ (z * 116129781l) ^ (y); seed = seed * seed * 42317861 + seed * 11; - int dir = (int) ((seed >> 16) & 0x3); + int dir = static_cast((seed >> 16) & 0x3); @@ -4622,7 +4622,7 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) { changed = true; Icon *tex = getTexture( tt, 1, data ); - float angle = ( float )LiquidTile::getSlopeAngle( level, x, y, z, m ); + float angle = static_cast(LiquidTile::getSlopeAngle(level, x, y, z, m)); if ( angle > -999 ) { tex = getTexture( tt, 2, data ); @@ -4717,8 +4717,8 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) { hh0 = ( float )( h0 ); hh1 = ( float )( h3 ); - x0 = ( float )( x ); - x1 = ( float )( x + 1 ); + x0 = static_cast(x); + x1 = static_cast(x + 1); z0 = ( float )( z + offs); z1 = ( float )( z + offs); } @@ -4726,8 +4726,8 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) { hh0 = ( float )( h2 ); hh1 = ( float )( h1 ); - x0 = ( float )( x + 1 ); - x1 = ( float )( x ); + x0 = static_cast(x + 1); + x1 = static_cast(x); z0 = ( float )( z + 1 - offs); z1 = ( float )( z + 1 - offs); } @@ -4737,8 +4737,8 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) hh1 = ( float )( h0 ); x0 = ( float )( x + offs); x1 = ( float )( x + offs); - z0 = ( float )( z + 1 ); - z1 = ( float )( z ); + z0 = static_cast(z + 1); + z1 = static_cast(z); } else { @@ -4746,8 +4746,8 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) hh1 = ( float )( h2 ); x0 = ( float )( x + 1 - offs); x1 = ( float )( x + 1 - offs); - z0 = ( float )( z ); - z1 = ( float )( z + 1 ); + z0 = static_cast(z); + z1 = static_cast(z + 1); } @@ -4777,8 +4777,8 @@ bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) t->color( c11 * br * r, c11 * br * g, c11 * br * b ); t->vertexUV( ( float )( x0 ), ( float )( y + hh0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v01 ) ); t->vertexUV( ( float )( x1 ), ( float )( y + hh1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v02 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x1 ), static_cast(y + 0), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); + t->vertexUV( ( float )( x0 ), static_cast(y + 0), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); } @@ -5207,7 +5207,7 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* // but they also happen to draw a lot of faces, and the code for determining which texture to use is more complex than in most // cases. Optimisation here then to store a uniform texture where appropriate (could be extended beyond leaves) that will stop // any other faces being evaluated. - Icon *uniformTex = NULL; + Icon *uniformTex = nullptr; int id = tt->id; if( id == Tile::leaves_Id ) { @@ -5257,7 +5257,7 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* Tesselator* t = Tesselator::getInstance(); t->tex2( 0xf000f ); - if( uniformTex == NULL ) + if( uniformTex == nullptr ) { if ( getTexture(tt)->getFlags() == Icon::IS_GRASS_TOP ) tintSides = false; } @@ -5534,14 +5534,14 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); + ll1 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX0)); + ll2 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX1)); + ll3 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX1)); + ll4 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX0)); int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); @@ -5689,14 +5689,14 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); + ll1 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX0)); + ll2 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX0)); + ll3 = static_cast(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) + * (1.0 - tileShapeX1)); + ll4 = static_cast(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) + * (1.0 - tileShapeX1)); int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); @@ -5840,14 +5840,14 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ1); - ll2 = (float) (_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ0); - ll3 = (float) (_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ0); - ll4 = (float) (_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ1); + ll1 = static_cast(_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) + * tileShapeZ1); + ll2 = static_cast(_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) + * tileShapeZ0); + ll3 = static_cast(_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) + * tileShapeZ0); + ll4 = static_cast(_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) + * tileShapeZ1); int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); @@ -5991,14 +5991,14 @@ bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - ll1 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 - * tileShapeZ1); - ll2 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 - * tileShapeZ0); - ll3 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 - * tileShapeZ0); - ll4 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 - * tileShapeZ1); + ll1 = static_cast(_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 + * tileShapeZ1); + ll2 = static_cast(_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 + * tileShapeZ0); + ll3 = static_cast(_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 + * tileShapeZ0); + ll4 = static_cast(_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 + * tileShapeZ1); int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); @@ -6085,8 +6085,8 @@ int TileRenderer::blend( int a, int b, int c, int def ) int TileRenderer::blend(int a, int b, int c, int d, double fa, double fb, double fc, double fd) { - int top = (int) ((double) ((a >> 16) & 0xff) * fa + (double) ((b >> 16) & 0xff) * fb + (double) ((c >> 16) & 0xff) * fc + (double) ((d >> 16) & 0xff) * fd) & 0xff; - int bottom = (int) ((double) (a & 0xff) * fa + (double) (b & 0xff) * fb + (double) (c & 0xff) * fc + (double) (d & 0xff) * fd) & 0xff; + int top = static_cast((double)((a >> 16) & 0xff) * fa + (double)((b >> 16) & 0xff) * fb + (double)((c >> 16) & 0xff) * fc + (double)((d >> 16) & 0xff) * fd) & 0xff; + int bottom = static_cast((double)(a & 0xff) * fa + (double)(b & 0xff) * fb + (double)(c & 0xff) * fc + (double)(d & 0xff) * fd) & 0xff; return (top << 16) | bottom; } @@ -7282,23 +7282,23 @@ void TileRenderer::renderFaceDown( Tile* tt, double x, double y, double z, Icon t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), ( float )( u00 ), ( float )( v00 ) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u01), static_cast(v01) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), ( float )( u11 ), ( float )( v11 ) ); } else { - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u01), static_cast(v01) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), ( float )( u11 ), ( float )( v11 ) ); } } @@ -7394,23 +7394,23 @@ void TileRenderer::renderFaceUp( Tile* tt, double x, double y, double z, Icon *t t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), ( float )( u11 ), ( float )( v11 ) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), ( float )( u01 ), ( float )( v01 ) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), ( float )( u00 ), ( float )( v00 ) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), ( float )( u10 ), ( float )( v10 ) ); } else { - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), ( float )( u10 ), ( float )( v10 ) ); } } @@ -7513,23 +7513,23 @@ void TileRenderer::renderNorth( Tile* tt, double x, double y, double z, Icon *te t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), static_cast(u01), static_cast(v01) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), static_cast(u00), static_cast(v00) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u10), static_cast(v10) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), static_cast(u11), static_cast(v11) ); } else { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), static_cast(u01), static_cast(v01) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), static_cast(u00), static_cast(v00) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u10), static_cast(v10) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), static_cast(u11), static_cast(v11) ); } } @@ -7632,23 +7632,23 @@ void TileRenderer::renderSouth( Tile* tt, double x, double y, double z, Icon *te t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), static_cast(u00), static_cast(v00) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), static_cast(u11), static_cast(v11) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), static_cast(u01), static_cast(v01) ); } else { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), static_cast(u00), static_cast(v00) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), static_cast(u11), static_cast(v11) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), static_cast(u01), static_cast(v01) ); } } @@ -7750,23 +7750,23 @@ void TileRenderer::renderWest( Tile* tt, double x, double y, double z, Icon *tex t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), static_cast(u01), static_cast(v01) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), static_cast(u00), static_cast(v00) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), static_cast(u10), static_cast(v10) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u11), static_cast(v11) ); } else { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z1), static_cast(u01), static_cast(v01) ); + t->vertexUV( static_cast(x0), static_cast(y1), static_cast(z0), static_cast(u00), static_cast(v00) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z0), static_cast(u10), static_cast(v10) ); + t->vertexUV( static_cast(x0), static_cast(y0), static_cast(z1), static_cast(u11), static_cast(v11) ); } } @@ -7868,23 +7868,23 @@ void TileRenderer::renderEast( Tile* tt, double x, double y, double z, Icon *tex t->color( c1r, c1g, c1b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); t->color( c2r, c2g, c2b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u11), static_cast(v11) ); t->color( c3r, c3g, c3b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), static_cast(u01), static_cast(v01) ); t->color( c4r, c4g, c4b ); if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), static_cast(u00), static_cast(v00) ); } else { - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z1), static_cast(u10), static_cast(v10) ); + t->vertexUV( static_cast(x1), static_cast(y0), static_cast(z0), static_cast(u11), static_cast(v11) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z0), static_cast(u01), static_cast(v01) ); + t->vertexUV( static_cast(x1), static_cast(y1), static_cast(z1), static_cast(u00), static_cast(v00) ); } } @@ -8399,7 +8399,7 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl else if (shape == Tile::SHAPE_ANVIL) { glTranslatef(-0.5f, -0.5f, -0.5f); - tesselateAnvilInWorld((AnvilTile *) tile, 0, 0, 0, data << 2, true); + tesselateAnvilInWorld(static_cast(tile), 0, 0, 0, data << 2, true); glTranslatef(0.5f, 0.5f, 0.5f); } else if ( shape == Tile::SHAPE_PORTAL_FRAME ) @@ -8550,7 +8550,7 @@ Icon *TileRenderer::getTexture(Tile *tile) Icon *TileRenderer::getTextureOrMissing(Icon *icon) { - if (icon == NULL) return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); + if (icon == nullptr) return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); #ifdef __PSVITA__ // AP - alpha cut out is expensive on vita. Pass on the Alpha Cut out flag to the tesselator diff --git a/Minecraft.Client/Timer.cpp b/Minecraft.Client/Timer.cpp index 636904b7c..3ef51eb7c 100644 --- a/Minecraft.Client/Timer.cpp +++ b/Minecraft.Client/Timer.cpp @@ -40,10 +40,10 @@ void Timer::advanceTime() accumMs += passedMs; if (accumMs > 1000) { - int64_t msSysTime = (int64_t)(now * 1000.0); - int64_t passedMsSysTime = msSysTime - lastMsSysTime; + const int64_t msSysTime = static_cast(now * 1000.0); + const int64_t passedMsSysTime = msSysTime - lastMsSysTime; - double adjustTimeT = accumMs / (double) passedMsSysTime; + const double adjustTimeT = accumMs / static_cast(passedMsSysTime); adjustTime += (adjustTimeT - adjustTime) * 0.2f; lastMsSysTime = msSysTime; @@ -51,7 +51,7 @@ void Timer::advanceTime() } if (accumMs < 0) { - lastMsSysTime = (int64_t)(now * 1000.0); + lastMsSysTime = static_cast(now * 1000.0); } } lastMs = nowMs; @@ -62,9 +62,9 @@ void Timer::advanceTime() if (passedSeconds < 0) passedSeconds = 0; if (passedSeconds > 1) passedSeconds = 1; - passedTime = (float)( passedTime + (passedSeconds * timeScale * ticksPerSecond)); + passedTime = static_cast(passedTime + (passedSeconds * timeScale * ticksPerSecond)); - ticks = (int) passedTime; + ticks = static_cast(passedTime); passedTime -= ticks; if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; @@ -75,10 +75,10 @@ void Timer::advanceTime() void Timer::advanceTimeQuickly() { - double passedSeconds = (double) MAX_TICKS_PER_UPDATE / (double) ticksPerSecond; + double passedSeconds = static_cast(MAX_TICKS_PER_UPDATE) / static_cast(ticksPerSecond); - passedTime = (float)(passedTime + (passedSeconds * timeScale * ticksPerSecond)); - ticks = (int) passedTime; + passedTime = static_cast(passedTime + (passedSeconds * timeScale * ticksPerSecond)); + ticks = static_cast(passedTime); passedTime -= ticks; a = passedTime; @@ -110,7 +110,7 @@ void Timer::skipTime() { int64_t passedMsSysTime = msSysTime - lastMsSysTime; - double adjustTimeT = accumMs / (double) passedMsSysTime; + double adjustTimeT = accumMs / static_cast(passedMsSysTime); adjustTime += (adjustTimeT - adjustTime) * 0.2f; lastMsSysTime = msSysTime; @@ -130,9 +130,9 @@ void Timer::skipTime() if (passedSeconds < 0) passedSeconds = 0; if (passedSeconds > 1) passedSeconds = 1; - passedTime = (float)(passedTime + (passedSeconds * timeScale * ticksPerSecond)); + passedTime = static_cast(passedTime + (passedSeconds * timeScale * ticksPerSecond)); - ticks = (int) 0; + ticks = static_cast(0); if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; passedTime -= ticks; diff --git a/Minecraft.Client/TitleScreen.cpp b/Minecraft.Client/TitleScreen.cpp index 1c7d5125b..d522963ca 100644 --- a/Minecraft.Client/TitleScreen.cpp +++ b/Minecraft.Client/TitleScreen.cpp @@ -18,7 +18,7 @@ TitleScreen::TitleScreen() { // 4J - added initialisers vo = 0; - multiplayerButton = NULL; + multiplayerButton = nullptr; splash = L"missingno"; // try { // 4J - removed try/catch @@ -93,7 +93,7 @@ void TitleScreen::init() buttons.push_back(new Button(4, width / 2 + 2, topPos + spacing * 3 + 12, 98, 20, language->getElement(L"menu.quit"))); } - if (minecraft->user == NULL) + if (minecraft->user == nullptr) { multiplayerButton->active = false; } diff --git a/Minecraft.Client/TntRenderer.cpp b/Minecraft.Client/TntRenderer.cpp index 52e2877dc..848a456c1 100644 --- a/Minecraft.Client/TntRenderer.cpp +++ b/Minecraft.Client/TntRenderer.cpp @@ -17,7 +17,7 @@ void TntRenderer::render(shared_ptr _tnt, double x, double y, double z, shared_ptr tnt = dynamic_pointer_cast(_tnt); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); if (tnt->life - a + 1 < 10) { float g = 1 - ((tnt->life - a + 1) / 10.0f); diff --git a/Minecraft.Client/TrackedEntity.cpp b/Minecraft.Client/TrackedEntity.cpp index 0a5a02bff..3aa33248d 100644 --- a/Minecraft.Client/TrackedEntity.cpp +++ b/Minecraft.Client/TrackedEntity.cpp @@ -63,10 +63,10 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl updatePlayers(tracker, players); } - if (lastRidingEntity != e->riding || (e->riding != NULL && tickCount % (SharedConstants::TICKS_PER_SECOND * 3) == 0)) + if (lastRidingEntity != e->riding || (e->riding != nullptr && tickCount % (SharedConstants::TICKS_PER_SECOND * 3) == 0)) { lastRidingEntity = e->riding; - broadcast(shared_ptr(new SetEntityLinkPacket(SetEntityLinkPacket::RIDING, e, e->riding))); + broadcast(std::make_shared(SetEntityLinkPacket::RIDING, e, e->riding)); } // Moving forward special case for item frames @@ -75,7 +75,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl shared_ptr frame = dynamic_pointer_cast (e); shared_ptr item = frame->getItem(); - if (item != NULL && item->getItem()->id == Item::map_Id && !e->removed) + if (item != nullptr && item->getItem()->id == Item::map_Id && !e->removed) { shared_ptr data = Item::map->getSavedData(item, e->level); for (auto& it : *players) @@ -86,7 +86,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl if (!player->removed && player->connection && player->connection->countDelayedPackets() <= 5) { shared_ptr packet = Item::map->getUpdatePacket(item, e->level, player); - if (packet != NULL) player->connection->send(packet); + if (packet != nullptr) player->connection->send(packet); } } } @@ -94,7 +94,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl shared_ptr entityData = e->getEntityData(); if (entityData->isDirty()) { - broadcastAndSend( shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); + broadcastAndSend(std::make_shared(e->entityId, entityData, false)); } } else if (tickCount % updateInterval == 0 || e->hasImpulse || e->getEntityData()->isDirty()) @@ -107,7 +107,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl int yRota = yRotn - yRotp; int xRota = xRotn - xRotp; - if(e->riding == NULL) + if(e->riding == nullptr) { teleportDelay++; @@ -152,7 +152,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl ) { teleportDelay = 0; - packet = shared_ptr( new TeleportEntityPacket(e->entityId, xn, yn, zn, (byte) yRotn, (byte) xRotn) ); + packet = std::make_shared(e->entityId, xn, yn, zn, static_cast(yRotn), static_cast(xRotn)); // printf("%d: New teleport rot %d\n",e->entityId,yRotn); yRotp = yRotn; xRotp = xRotn; @@ -179,12 +179,12 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl yRotn = yRotp + yRota; } // 5 bits each for x & z, and 6 for y - packet = shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, 0 ) ); + packet = std::make_shared(e->entityId, static_cast(xa), static_cast(ya), static_cast(za), static_cast(yRota), 0); c0a++; } else { - packet = shared_ptr( new MoveEntityPacket::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, (char) xRota) ); + packet = std::make_shared(e->entityId, static_cast(xa), static_cast(ya), static_cast(za), static_cast(yRota), static_cast(xRota)); // printf("%d: New posrot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); c0b++; } @@ -197,7 +197,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl ( ya >= -16 ) && ( ya <= 15 ) ) { // 4 bits each for x & z, and 5 for y - packet = shared_ptr( new MoveEntityPacketSmall::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); + packet = std::make_shared(e->entityId, static_cast(xa), static_cast(ya), static_cast(za)); c1a++; } @@ -206,12 +206,12 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl ( ya >= -32 ) && ( ya <= 31 ) ) { // use the packet with small packet with rotation if we can - 5 bits each for x & z, and 6 for y - still a byte less than the alternative - packet = shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, 0, 0 )); + packet = std::make_shared(e->entityId, static_cast(xa), static_cast(ya), static_cast(za), 0, 0); c1b++; } else { - packet = shared_ptr( new MoveEntityPacket::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); + packet = std::make_shared(e->entityId, static_cast(xa), static_cast(ya), static_cast(za)); c1c++; } } @@ -231,13 +231,13 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl yRota = 15; yRotn = yRotp + yRota; } - packet = shared_ptr( new MoveEntityPacketSmall::Rot(e->entityId, (char) yRota, 0) ); + packet = std::make_shared(e->entityId, static_cast(yRota), 0); c2a++; } else { // printf("%d: New rot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); - packet = shared_ptr( new MoveEntityPacket::Rot(e->entityId, (char) yRota, (char) xRota) ); + packet = std::make_shared(e->entityId, static_cast(yRota), static_cast(xRota)); c2b++; } } @@ -259,12 +259,12 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl xap = e->xd; yap = e->yd; zap = e->zd; - broadcast( shared_ptr( new SetEntityMotionPacket(e->entityId, xap, yap, zap) ) ); + broadcast(std::make_shared(e->entityId, xap, yap, zap)); } } - if (packet != NULL) + if (packet != nullptr) { broadcast(packet); } @@ -291,7 +291,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl if (rot) { // 4J: Changed this to use deltas - broadcast( shared_ptr( new MoveEntityPacket::Rot(e->entityId, (byte) yRota, (byte) xRota)) ); + broadcast(std::make_shared(e->entityId, static_cast(yRota), static_cast(xRota))); yRotp = yRotn; xRotp = xRotn; } @@ -308,7 +308,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl int yHeadRot = Mth::floor(e->getYHeadRot() * 256 / 360); if (abs(yHeadRot - yHeadRotp) >= TOLERANCE_LEVEL) { - broadcast(shared_ptr( new RotateHeadPacket(e->entityId, (byte) yHeadRot))); + broadcast(std::make_shared(e->entityId, static_cast(yHeadRot))); yHeadRotp = yHeadRot; } @@ -320,7 +320,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector > *pl if (e->hurtMarked) { // broadcast(new AnimatePacket(e, AnimatePacket.HURT)); - broadcastAndSend( shared_ptr( new SetEntityMotionPacket(e) ) ); + broadcastAndSend(std::make_shared(e)); e->hurtMarked = false; } @@ -331,18 +331,18 @@ void TrackedEntity::sendDirtyEntityData() shared_ptr entityData = e->getEntityData(); if (entityData->isDirty()) { - broadcastAndSend( shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false)) ); + broadcastAndSend(std::make_shared(e->entityId, entityData, false)); } if ( e->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr living = dynamic_pointer_cast(e); - ServersideAttributeMap *attributeMap = (ServersideAttributeMap *) living->getAttributes(); + ServersideAttributeMap *attributeMap = static_cast(living->getAttributes()); unordered_set *attributes = attributeMap->getDirtyAttributes(); if (!attributes->empty()) { - broadcastAndSend(shared_ptr( new UpdateAttributesPacket(e->entityId, attributes)) ); + broadcastAndSend(std::make_shared(e->entityId, attributes)); } attributes->clear(); @@ -368,7 +368,7 @@ void TrackedEntity::broadcast(shared_ptr packet) if( sentTo.size() ) { INetworkPlayer *thisPlayer =player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) + if( thisPlayer == nullptr ) { dontSend = true; } @@ -377,7 +377,7 @@ void TrackedEntity::broadcast(shared_ptr packet) for(auto& player2 : sentTo) { INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { dontSend = true; } @@ -410,7 +410,7 @@ void TrackedEntity::broadcastAndSend(shared_ptr packet) vector< shared_ptr > sentTo; broadcast(packet); shared_ptr sp = e->instanceof(eTYPE_SERVERPLAYER) ? dynamic_pointer_cast(e) : nullptr; - if (sp != NULL && sp->connection) + if (sp != nullptr && sp->connection) { sp->connection->send(packet); } @@ -477,7 +477,7 @@ TrackedEntity::eVisibility TrackedEntity::isVisible(EntityTracker *tracker, shar if( ep->dimension != sp->dimension ) continue; INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) + if( otherPlayer != nullptr && thisPlayer->IsSameSystem(otherPlayer) ) { // 4J Stu - We call update players when the entity has moved more than a certain amount at the start of it's tick // Before this call we set xpu, ypu and zpu to the entities new position, but xp,yp and zp are the old position until later in the tick. @@ -499,7 +499,7 @@ TrackedEntity::eVisibility TrackedEntity::isVisible(EntityTracker *tracker, shar // 4J-JEV: ADDED! An entities mount has to be visible before the entity visible, // this is to ensure that the mount is already in the client's game when the rider is added. - if (canBeSeenBy && bVisible && e->riding != NULL) + if (canBeSeenBy && bVisible && e->riding != nullptr) { return tracker->getTracker(e->riding)->isVisible(tracker, sp, true); } @@ -530,43 +530,43 @@ void TrackedEntity::updatePlayer(EntityTracker *tracker, shared_ptr plr = dynamic_pointer_cast(e); app.DebugPrintf( "TrackedEntity:: Player '%ls' is now visible to player '%ls', %s.\n", plr->name.c_str(), sp->name.c_str(), - (e->riding==NULL?"not riding minecart":"in minecart") + (e->riding==nullptr?"not riding minecart":"in minecart") ); } - bool isAddMobPacket = dynamic_pointer_cast(packet) != NULL; + bool isAddMobPacket = dynamic_pointer_cast(packet) != nullptr; // 4J Stu brought forward to fix when Item Frames if (!e->getEntityData()->isEmpty() && !isAddMobPacket) { - sp->connection->send(shared_ptr( new SetEntityDataPacket(e->entityId, e->getEntityData(), true))); + sp->connection->send(std::make_shared(e->entityId, e->getEntityData(), true)); } if ( e->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr living = dynamic_pointer_cast(e); - ServersideAttributeMap *attributeMap = (ServersideAttributeMap *) living->getAttributes(); + ServersideAttributeMap *attributeMap = static_cast(living->getAttributes()); unordered_set *attributes = attributeMap->getSyncableAttributes(); if (!attributes->empty()) { - sp->connection->send(shared_ptr( new UpdateAttributesPacket(e->entityId, attributes)) ); + sp->connection->send(std::make_shared(e->entityId, attributes)); } delete attributes; } if (trackDelta && !isAddMobPacket) { - sp->connection->send( shared_ptr( new SetEntityMotionPacket(e->entityId, e->xd, e->yd, e->zd) ) ); + sp->connection->send(std::make_shared(e->entityId, e->xd, e->yd, e->zd)); } - if (e->riding != NULL) + if (e->riding != nullptr) { - sp->connection->send(shared_ptr(new SetEntityLinkPacket(SetEntityLinkPacket::RIDING, e, e->riding))); + sp->connection->send(std::make_shared(SetEntityLinkPacket::RIDING, e, e->riding)); } - if ( e->instanceof(eTYPE_MOB) && dynamic_pointer_cast(e)->getLeashHolder() != NULL) + if ( e->instanceof(eTYPE_MOB) && dynamic_pointer_cast(e)->getLeashHolder() != nullptr) { - sp->connection->send( shared_ptr( new SetEntityLinkPacket(SetEntityLinkPacket::LEASH, e, dynamic_pointer_cast(e)->getLeashHolder())) ); + sp->connection->send(std::make_shared(SetEntityLinkPacket::LEASH, e, dynamic_pointer_cast(e)->getLeashHolder())); } if ( e->instanceof(eTYPE_LIVINGENTITY) ) @@ -574,7 +574,7 @@ void TrackedEntity::updatePlayer(EntityTracker *tracker, shared_ptr item = dynamic_pointer_cast(e)->getCarried(i); - if(item != NULL) sp->connection->send( shared_ptr( new SetEquippedItemPacket(e->entityId, i, item) ) ); + if(item != nullptr) sp->connection->send(std::make_shared(e->entityId, i, item)); } } @@ -583,7 +583,7 @@ void TrackedEntity::updatePlayer(EntityTracker *tracker, shared_ptr spe = dynamic_pointer_cast(e); if (spe->isSleeping()) { - sp->connection->send( shared_ptr( new EntityActionAtPositionPacket(e, EntityActionAtPositionPacket::START_SLEEP, Mth::floor(e->x), Mth::floor(e->y), Mth::floor(e->z)) ) ); + sp->connection->send(std::make_shared(e, EntityActionAtPositionPacket::START_SLEEP, Mth::floor(e->x), Mth::floor(e->y), Mth::floor(e->z))); } } @@ -636,15 +636,15 @@ shared_ptr TrackedEntity::getAddEntityPacket() } // 4J-PB - replacing with a switch, rather than tons of ifs - if (dynamic_pointer_cast(e) != NULL) + if (dynamic_pointer_cast(e) != nullptr) { yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return shared_ptr( new AddMobPacket(dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp) ); + return std::make_shared(dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp); } if (e->instanceof(eTYPE_ITEMENTITY)) { - shared_ptr packet = shared_ptr( new AddEntityPacket(e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp) ); + shared_ptr packet = std::make_shared(e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp); return packet; } else if (e->instanceof(eTYPE_SERVERPLAYER)) @@ -653,61 +653,61 @@ shared_ptr TrackedEntity::getAddEntityPacket() PlayerUID xuid = INVALID_XUID; PlayerUID OnlineXuid = INVALID_XUID; - if( player != NULL ) + if( player != nullptr ) { xuid = player->getXuid(); OnlineXuid = player->getOnlineXuid(); } // 4J Added yHeadRotp param to fix #102563 - TU12: Content: Gameplay: When one of the Players is idle for a few minutes his head turns 180 degrees. - return shared_ptr( new AddPlayerPacket( player, xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp, yHeadRotp ) ); + return std::make_shared(player, xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp, yHeadRotp); } else if (e->instanceof(eTYPE_MINECART)) { shared_ptr minecart = dynamic_pointer_cast(e); - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART, minecart->getType(), yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::MINECART, minecart->getType(), yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_BOAT)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_ENDERDRAGON)) { yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return shared_ptr( new AddMobPacket(dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp ) ); + return std::make_shared(dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp); } else if (e->instanceof(eTYPE_FISHINGHOOK)) { shared_ptr owner = dynamic_pointer_cast(e)->owner; - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::FISH_HOOK, owner != nullptr ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_ARROW)) { shared_ptr owner = (dynamic_pointer_cast(e))->owner; - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::ARROW, owner != nullptr ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_SNOWBALL)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_THROWNPOTION)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_POTION, ((dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp)); + return std::make_shared(e, AddEntityPacket::THROWN_POTION, ((dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_THROWNEXPBOTTLE)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_THROWNENDERPEARL)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_EYEOFENDERSIGNAL)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_FIREWORKS_ROCKET)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREWORKS, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::FIREWORKS, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_FIREBALL)) { @@ -728,39 +728,39 @@ shared_ptr TrackedEntity::getAddEntityPacket() shared_ptr fb = dynamic_pointer_cast(e); shared_ptr aep = nullptr; - if (fb->owner != NULL) + if (fb->owner != nullptr) { - aep = shared_ptr( new AddEntityPacket(e, type, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); + aep = std::make_shared(e, type, fb->owner->entityId, yRotp, xRotp, xp, yp, zp); } else { - aep = shared_ptr( new AddEntityPacket(e, type, 0, yRotp, xRotp, xp, yp, zp) ); + aep = std::make_shared(e, type, 0, yRotp, xRotp, xp, yp, zp); } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); + aep->xa = static_cast(fb->xPower * 8000); + aep->ya = static_cast(fb->yPower * 8000); + aep->za = static_cast(fb->zPower * 8000); return aep; } else if (e->instanceof(eTYPE_THROWNEGG)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_PRIMEDTNT)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_ENDER_CRYSTAL)) { - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_FALLINGTILE)) { shared_ptr ft = dynamic_pointer_cast(e); - return shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, xRotp, xp, yp, zp) ); + return std::make_shared(e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, xRotp, xp, yp, zp); } else if (e->instanceof(eTYPE_PAINTING)) { - return shared_ptr( new AddPaintingPacket(dynamic_pointer_cast(e)) ); + return std::make_shared(dynamic_pointer_cast(e)); } else if (e->instanceof(eTYPE_ITEM_FRAME)) { @@ -774,7 +774,7 @@ shared_ptr TrackedEntity::getAddEntityPacket() app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); } - shared_ptr packet = shared_ptr(new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); + shared_ptr packet = std::make_shared(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp); packet->x = Mth::floor(frame->xTile * 32.0f); packet->y = Mth::floor(frame->yTile * 32.0f); packet->z = Mth::floor(frame->zTile * 32.0f); @@ -783,15 +783,15 @@ shared_ptr TrackedEntity::getAddEntityPacket() else if (e->instanceof(eTYPE_LEASHFENCEKNOT)) { shared_ptr knot = dynamic_pointer_cast(e); - shared_ptr packet = shared_ptr(new AddEntityPacket(e, AddEntityPacket::LEASH_KNOT, yRotp, xRotp, xp, yp, zp) ); - packet->x = Mth::floor((float)knot->xTile * 32); - packet->y = Mth::floor((float)knot->yTile * 32); - packet->z = Mth::floor((float)knot->zTile * 32); + shared_ptr packet = std::make_shared(e, AddEntityPacket::LEASH_KNOT, yRotp, xRotp, xp, yp, zp); + packet->x = Mth::floor(static_cast(knot->xTile) * 32); + packet->y = Mth::floor(static_cast(knot->yTile) * 32); + packet->z = Mth::floor(static_cast(knot->zTile) * 32); return packet; } else if (e->instanceof(eTYPE_EXPERIENCEORB)) { - return shared_ptr( new AddExperienceOrbPacket(dynamic_pointer_cast(e)) ); + return std::make_shared(dynamic_pointer_cast(e)); } else { diff --git a/Minecraft.Client/VideoSettingsScreen.cpp b/Minecraft.Client/VideoSettingsScreen.cpp index 5c948cdd1..cc13eab29 100644 --- a/Minecraft.Client/VideoSettingsScreen.cpp +++ b/Minecraft.Client/VideoSettingsScreen.cpp @@ -46,9 +46,9 @@ void VideoSettingsScreen::init() void VideoSettingsScreen::buttonClicked(Button *button) { if (!button->active) return; - if (button->id < 100 && (dynamic_cast(button) != NULL)) + if (button->id < 100 && (dynamic_cast(button) != nullptr)) { - options->toggle(((SmallButton *) button)->getOption(), 1); + options->toggle(static_cast(button)->getOption(), 1); button->msg = options->getMessage(Options::Option::getItem(button->id)); } if (button->id == 200) diff --git a/Minecraft.Client/VillagerGolemRenderer.cpp b/Minecraft.Client/VillagerGolemRenderer.cpp index 5d6809784..0b62435b2 100644 --- a/Minecraft.Client/VillagerGolemRenderer.cpp +++ b/Minecraft.Client/VillagerGolemRenderer.cpp @@ -10,7 +10,7 @@ ResourceLocation VillagerGolemRenderer::GOLEM_LOCATION = ResourceLocation(TN_MOB VillagerGolemRenderer::VillagerGolemRenderer() : MobRenderer(new VillagerGolemModel(), 0.5f) { - golemModel = (VillagerGolemModel *) model; + golemModel = static_cast(model); } void VillagerGolemRenderer::render(shared_ptr mob, double x, double y, double z, float rot, float a) diff --git a/Minecraft.Client/VillagerRenderer.cpp b/Minecraft.Client/VillagerRenderer.cpp index ac885747c..0b54a70b7 100644 --- a/Minecraft.Client/VillagerRenderer.cpp +++ b/Minecraft.Client/VillagerRenderer.cpp @@ -12,7 +12,7 @@ ResourceLocation VillagerRenderer::VILLAGER_BUTCHER_LOCATION = ResourceLocation( VillagerRenderer::VillagerRenderer() : MobRenderer(new VillagerModel(0), 0.5f) { - villagerModel = (VillagerModel *) model; + villagerModel = static_cast(model); } int VillagerRenderer::prepareArmor(shared_ptr villager, int layer, float a) diff --git a/Minecraft.Client/WaterDropParticle.cpp b/Minecraft.Client/WaterDropParticle.cpp index 90035243e..065738af9 100644 --- a/Minecraft.Client/WaterDropParticle.cpp +++ b/Minecraft.Client/WaterDropParticle.cpp @@ -8,7 +8,7 @@ WaterDropParticle::WaterDropParticle(Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) { xd *= 0.3f; - yd = (float) Math::random() * 0.2f + 0.1f; + yd = static_cast(Math::random()) * 0.2f + 0.1f; zd *= 0.3f; rCol = 1.0f; @@ -19,7 +19,7 @@ WaterDropParticle::WaterDropParticle(Level *level, double x, double y, double z) gravity = 0.06f; noPhysics = true; // 4J - optimisation - do we really need collision on these? its really slow... - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + lifetime = static_cast(8 / (Math::random() * 0.8 + 0.2)); } void WaterDropParticle::tick() diff --git a/Minecraft.Client/Windows64/4JLibs/inc/4J_Input.h b/Minecraft.Client/Windows64/4JLibs/inc/4J_Input.h index 9ac5c55d1..26e88e067 100644 --- a/Minecraft.Client/Windows64/4JLibs/inc/4J_Input.h +++ b/Minecraft.Client/Windows64/4JLibs/inc/4J_Input.h @@ -107,8 +107,8 @@ public: void SetMenuDisplayed(int iPad, bool bVal); -// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); -// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); +// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); +// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=nullptr); EKeyboardResult RequestKeyboard(LPCWSTR Title, LPCWSTR Text, DWORD dwPad, UINT uiMaxChars, int( *Func)(LPVOID,const bool),LPVOID lpParam,C_4JInput::EKeyboardMode eMode); void GetText(uint16_t *UTF16String); diff --git a/Minecraft.Client/Windows64/4JLibs/inc/4J_Profile.h b/Minecraft.Client/Windows64/4JLibs/inc/4J_Profile.h index f1bd85bbe..6b9cc2890 100644 --- a/Minecraft.Client/Windows64/4JLibs/inc/4J_Profile.h +++ b/Minecraft.Client/Windows64/4JLibs/inc/4J_Profile.h @@ -100,7 +100,7 @@ public: // ACHIEVEMENTS & AWARDS void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); + CXuiStringTable*pStringTable=nullptr, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=nullptr, unsigned int uiThemeSize=0L); int GetAwardId(int iAwardNumber); eAwardType GetAwardType(int iAwardNumber); bool CanBeAwarded(int iQuadrant, int iAwardNumber); diff --git a/Minecraft.Client/Windows64/4JLibs/inc/4J_Render.h b/Minecraft.Client/Windows64/4JLibs/inc/4J_Render.h index 737caa98b..fb16ccb32 100644 --- a/Minecraft.Client/Windows64/4JLibs/inc/4J_Render.h +++ b/Minecraft.Client/Windows64/4JLibs/inc/4J_Render.h @@ -16,8 +16,8 @@ public: int GetType() { return m_type; } void *GetBufferPointer() { return m_pBuffer; } int GetBufferSize() { return m_bufferSize; } - void Release() { free(m_pBuffer); m_pBuffer = NULL; } - bool Allocated() { return m_pBuffer != NULL; } + void Release() { free(m_pBuffer); m_pBuffer = nullptr; } + bool Allocated() { return m_pBuffer != nullptr; } }; typedef struct @@ -60,7 +60,7 @@ public: void StartFrame(); void DoScreenGrabOnNextPresent(); void Present(); - void Clear(int flags, D3D11_RECT *pRect = NULL); + void Clear(int flags, D3D11_RECT *pRect = nullptr); void SetClearColour(const float colourRGBA[4]); bool IsWidescreen(); bool IsHiDef(); diff --git a/Minecraft.Client/Windows64/4JLibs/inc/4J_Storage.h b/Minecraft.Client/Windows64/4JLibs/inc/4J_Storage.h index 45bfb31a9..006c3c88b 100644 --- a/Minecraft.Client/Windows64/4JLibs/inc/4J_Storage.h +++ b/Minecraft.Client/Windows64/4JLibs/inc/4J_Storage.h @@ -239,7 +239,7 @@ public: // Messages C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, - int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=NULL,LPVOID lpParam=NULL, C4JStringTable *pStringTable=NULL, WCHAR *pwchFormatString=NULL,DWORD dwFocusButton=0); + int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=nullptr,LPVOID lpParam=nullptr, C4JStringTable *pStringTable=nullptr, WCHAR *pwchFormatString=nullptr,DWORD dwFocusButton=0); C4JStorage::EMessageResult GetMessageBoxResult(); @@ -296,17 +296,17 @@ public: C4JStorage::EDLCStatus GetInstalledDLC(int iPad,int( *Func)(LPVOID, int, int),LPVOID lpParam); XCONTENT_DATA& GetDLC(DWORD dw); - DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive=NULL); - DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL); + DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive=nullptr); + DWORD UnmountInstalledDLC(LPCSTR szMountDrive = nullptr); void GetMountedDLCFileList(const char* szMountDrive, std::vector& fileList); std::string GetMountedPath(std::string szMount); // Global title storage C4JStorage::ETMSStatus ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType, - WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int)=NULL,LPVOID lpParam=NULL, int iAction=0); + WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int)=nullptr,LPVOID lpParam=nullptr, int iAction=0); bool WriteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename,BYTE *pBuffer,DWORD dwBufferSize); bool DeleteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename); - void StoreTMSPathName(WCHAR *pwchName=NULL); + void StoreTMSPathName(WCHAR *pwchName=nullptr); // TMS++ #ifdef _XBOX @@ -314,11 +314,11 @@ public: HRESULT GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam); #endif - // C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0); + // C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); // C4JStorage::ETMSStatus TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam, int iUserData=0); - C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)=NULL,LPVOID lpParam=NULL, int iUserData=0); - // C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int iUserData=0); - // C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int iUserData=0); + C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); + // C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); + // C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=nullptr, int iUserData=0); // bool TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const wstring &Filename); // unsigned int CRC(unsigned char *buf, int len); diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d10_shaders.inl b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d10_shaders.inl index d4d2bb229..6ea0d142f 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d10_shaders.inl +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d10_shaders.inl @@ -1364,7 +1364,7 @@ static DWORD pshader_exceptional_blend_12[276] = { }; static ProgramWithCachedVariableLocations pshader_exceptional_blend_arr[13] = { - { NULL, 0, }, + { nullptr, 0, }, { pshader_exceptional_blend_1, 1340, }, { pshader_exceptional_blend_2, 1444, }, { pshader_exceptional_blend_3, 1424, }, @@ -2672,10 +2672,10 @@ static ProgramWithCachedVariableLocations pshader_filter_arr[32] = { { pshader_filter_9, 708, }, { pshader_filter_10, 1644, }, { pshader_filter_11, 1372, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, { pshader_filter_16, 1740, }, { pshader_filter_17, 1732, }, { pshader_filter_18, 1820, }, @@ -2688,10 +2688,10 @@ static ProgramWithCachedVariableLocations pshader_filter_arr[32] = { { pshader_filter_25, 1468, }, { pshader_filter_26, 1820, }, { pshader_filter_27, 1548, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, }; static DWORD pshader_blur_2[320] = { @@ -3193,8 +3193,8 @@ static DWORD pshader_blur_9[621] = { }; static ProgramWithCachedVariableLocations pshader_blur_arr[10] = { - { NULL, 0, }, - { NULL, 0, }, + { nullptr, 0, }, + { nullptr, 0, }, { pshader_blur_2, 1280, }, { pshader_blur_3, 1452, }, { pshader_blur_4, 1624, }, diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.cpp b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.cpp index 9ebf6c5d9..b9fb627bf 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.cpp +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.cpp @@ -64,7 +64,7 @@ static void *map_buffer(ID3D1XContext *ctx, ID3D11Buffer *buf, bool discard) HRESULT hr = ctx->Map(buf, 0, discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE, 0, &msr); if (FAILED(hr)) { report_d3d_error(hr, "Map", "of buffer"); - return NULL; + return nullptr; } else return msr.pData; } @@ -76,12 +76,12 @@ static void unmap_buffer(ID3D1XContext *ctx, ID3D11Buffer *buf) static RADINLINE void set_pixel_shader(ID3D11DeviceContext *ctx, ID3D11PixelShader *shader) { - ctx->PSSetShader(shader, NULL, 0); + ctx->PSSetShader(shader, nullptr, 0); } static RADINLINE void set_vertex_shader(ID3D11DeviceContext *ctx, ID3D11VertexShader *shader) { - ctx->VSSetShader(shader, NULL, 0); + ctx->VSSetShader(shader, nullptr, 0); } static ID3D11BlendState *create_blend_state(ID3D11Device *dev, BOOL blend, D3D11_BLEND src, D3D11_BLEND dst) @@ -100,7 +100,7 @@ static ID3D11BlendState *create_blend_state(ID3D11Device *dev, BOOL blend, D3D11 HRESULT hr = dev->CreateBlendState(&desc, &res); if (FAILED(hr)) { report_d3d_error(hr, "CreateBlendState", ""); - res = NULL; + res = nullptr; } return res; @@ -113,10 +113,10 @@ static void create_pixel_shader(ProgramWithCachedVariableLocations *p, ProgramWi { *p = *src; if(p->bytecode) { - HRESULT hr = gdraw->d3d_device->CreatePixelShader(p->bytecode, p->size, NULL, &p->pshader); + HRESULT hr = gdraw->d3d_device->CreatePixelShader(p->bytecode, p->size, nullptr, &p->pshader); if (FAILED(hr)) { report_d3d_error(hr, "CreatePixelShader", ""); - p->pshader = NULL; + p->pshader = nullptr; return; } } @@ -126,10 +126,10 @@ static void create_vertex_shader(ProgramWithCachedVariableLocations *p, ProgramW { *p = *src; if(p->bytecode) { - HRESULT hr = gdraw->d3d_device->CreateVertexShader(p->bytecode, p->size, NULL, &p->vshader); + HRESULT hr = gdraw->d3d_device->CreateVertexShader(p->bytecode, p->size, nullptr, &p->vshader); if (FAILED(hr)) { report_d3d_error(hr, "CreateVertexShader", ""); - p->vshader = NULL; + p->vshader = nullptr; return; } } diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.h b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.h index 7fd7012fe..47fe3c29b 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.h +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.h @@ -42,7 +42,7 @@ IDOC extern GDrawFunctions * gdraw_D3D11_CreateContext(ID3D11Device *dev, ID3D11 There can only be one D3D GDraw context active at any one time. If initialization fails for some reason (the main reason would be an out of memory condition), - NULL is returned. Otherwise, you can pass the return value to IggySetGDraw. */ + nullptr is returned. Otherwise, you can pass the return value to IggySetGDraw. */ IDOC extern void gdraw_D3D11_DestroyContext(void); /* Destroys the current GDraw context, if any. */ @@ -70,7 +70,7 @@ IDOC extern void gdraw_D3D11_SetTileOrigin(ID3D11RenderTargetView *main_rt, ID3D If your rendertarget uses multisampling, you also need to specify a shader resource view for a non-MSAA rendertarget texture (identically sized to main_rt) in non_msaa_rt. This is only used if the Flash content includes non-standard - blend modes which have to use a special blend shader, so you can leave it NULL + blend modes which have to use a special blend shader, so you can leave it nullptr if you forbid such content. You need to call this before Iggy calls any rendering functions. */ diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d1x_shared.inl b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d1x_shared.inl index 7e4db0380..62e97e0fe 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d1x_shared.inl +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d1x_shared.inl @@ -196,16 +196,16 @@ static void safe_release(T *&p) { if (p) { p->Release(); - p = NULL; + p = nullptr; } } static void report_d3d_error(HRESULT hr, const char *call, const char *context) { if (hr == E_OUTOFMEMORY) - IggyGDrawSendWarning(NULL, "GDraw D3D out of memory in %s%s", call, context); + IggyGDrawSendWarning(nullptr, "GDraw D3D out of memory in %s%s", call, context); else - IggyGDrawSendWarning(NULL, "GDraw D3D error in %s%s: 0x%08x", call, context, hr); + IggyGDrawSendWarning(nullptr, "GDraw D3D error in %s%s: 0x%08x", call, context, hr); } static void unbind_resources(void) @@ -214,13 +214,13 @@ static void unbind_resources(void) // unset active textures and vertex/index buffers, // to make sure there are no dangling refs - static ID3D1X(ShaderResourceView) *no_views[3] = { 0 }; - ID3D1X(Buffer) *no_vb = NULL; + static ID3D1X(ShaderResourceView) *no_views[3] = { nullptr }; + ID3D1X(Buffer) *no_vb = nullptr; UINT no_offs = 0; d3d->PSSetShaderResources(0, 3, no_views); d3d->IASetVertexBuffers(0, 1, &no_vb, &no_offs, &no_offs); - d3d->IASetIndexBuffer(NULL, DXGI_FORMAT_UNKNOWN, 0); + d3d->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0); } static void api_free_resource(GDrawHandle *r) @@ -251,11 +251,11 @@ static void RADLINK gdraw_UnlockHandles(GDrawStats * /*stats*/) static void *start_write_dyn(DynBuffer *buf, U32 size) { - U8 *ptr = NULL; + U8 *ptr = nullptr; if (size > buf->size) { - IggyGDrawSendWarning(NULL, "GDraw dynamic vertex buffer usage of %d bytes in one call larger than buffer size %d", size, buf->size); - return NULL; + IggyGDrawSendWarning(nullptr, "GDraw dynamic vertex buffer usage of %d bytes in one call larger than buffer size %d", size, buf->size); + return nullptr; } // update statistics @@ -270,7 +270,7 @@ static void *start_write_dyn(DynBuffer *buf, U32 size) // discard buffer whenever the current write position is 0; // done this way so that if a DISCARD Map() were to fail, we would // just keep retrying the next time around. - ptr = (U8 *) map_buffer(gdraw->d3d_context, buf->buffer, buf->write_pos == 0); + ptr = static_cast(map_buffer(gdraw->d3d_context, buf->buffer, buf->write_pos == 0)); if (ptr) { ptr += buf->write_pos; // we return pointer to write position in buffer buf->alloc_pos = buf->write_pos + size; // bump alloc position @@ -373,19 +373,19 @@ extern GDrawTexture *gdraw_D3D1X_(WrappedTextureCreate)(ID3D1X(ShaderResourceVie { GDrawStats stats={0}; GDrawHandle *p = gdraw_res_alloc_begin(gdraw->texturecache, 0, &stats); // it may need to free one item to give us a handle - p->handle.tex.d3d = NULL; + p->handle.tex.d3d = nullptr; p->handle.tex.d3d_view = tex_view; - p->handle.tex.d3d_rtview = NULL; + p->handle.tex.d3d_rtview = nullptr; p->handle.tex.w = 1; p->handle.tex.h = 1; - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); return (GDrawTexture *) p; } extern void gdraw_D3D1X_(WrappedTextureChange)(GDrawTexture *tex, ID3D1X(ShaderResourceView) *tex_view) { GDrawHandle *p = (GDrawHandle *) tex; - p->handle.tex.d3d = NULL; + p->handle.tex.d3d = nullptr; p->handle.tex.d3d_view = tex_view; } @@ -407,12 +407,12 @@ static void RADLINK gdraw_SetTextureUniqueID(GDrawTexture *tex, void *old_id, vo static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format format, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; DXGI_FORMAT dxgi_fmt; S32 bpp, size = 0, nmips = 0; if (width >= 16384 || height >= 16384) { - IggyGDrawSendWarning(NULL, "GDraw texture size too large (%d x %d), dimension limit is 16384", width, height); + IggyGDrawSendWarning(nullptr, "GDraw texture size too large (%d x %d), dimension limit is 16384", width, height); return false; } @@ -433,7 +433,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, // try to allocate memory for the client to write to p->texture_data = (U8 *) IggyGDrawMalloc(size); if (!p->texture_data) { - IggyGDrawSendWarning(NULL, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); + IggyGDrawSendWarning(nullptr, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); return false; } @@ -446,9 +446,9 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, t->handle.tex.w = width; t->handle.tex.h = height; - t->handle.tex.d3d = NULL; - t->handle.tex.d3d_view = NULL; - t->handle.tex.d3d_rtview = NULL; + t->handle.tex.d3d = nullptr; + t->handle.tex.d3d_view = nullptr; + t->handle.tex.d3d_rtview = nullptr; p->texture_type = GDRAW_TEXTURE_TYPE_rgba; p->p0 = t; @@ -474,7 +474,7 @@ static rrbool RADLINK gdraw_MakeTextureMore(GDraw_MakeTexture_ProcessingInfo * / static GDrawTexture * RADLINK gdraw_MakeTextureEnd(GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *stats) { - GDrawHandle *t = (GDrawHandle *) p->p0; + GDrawHandle *t = static_cast(p->p0); D3D1X_(SUBRESOURCE_DATA) mipdata[24]; S32 i, w, h, nmips, bpp; HRESULT hr = S_OK; @@ -512,7 +512,7 @@ static GDrawTexture * RADLINK gdraw_MakeTextureEnd(GDraw_MakeTexture_ProcessingI // and create a corresponding shader resource view failed_call = "CreateShaderResourceView"; - hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_view); + hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_view); done: if (!FAILED(hr)) { @@ -525,7 +525,7 @@ done: safe_release(t->handle.tex.d3d_view); gdraw_HandleCacheAllocateFail(t); - t = NULL; + t = nullptr; report_d3d_error(hr, failed_call, " while creating texture"); } @@ -554,8 +554,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *t, void * /*unique_id*/ static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *stats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); // @GDRAW_ASSERT - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); // @GDRAW_ASSERT + if (t->owner == unique_id || unique_id == nullptr) { if (t->cache == &gdraw->rendertargets) { gdraw_HandleCacheUnlock(t); // cache it by simply not freeing it @@ -595,7 +595,7 @@ static void RADLINK gdraw_SetAntialiasTexture(S32 width, U8 *rgba) return; } - hr = gdraw->d3d_device->CreateShaderResourceView(gdraw->aa_tex, NULL, &gdraw->aa_tex_view); + hr = gdraw->d3d_device->CreateShaderResourceView(gdraw->aa_tex, nullptr, &gdraw->aa_tex_view); if (FAILED(hr)) { report_d3d_error(hr, "CreateShaderResourceView", " while creating texture"); safe_release(gdraw->aa_tex); @@ -616,8 +616,8 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat if (p->vertex_data && p->index_data) { GDrawHandle *vb = gdraw_res_alloc_begin(gdraw->vbufcache, vbuf_size + ibuf_size, stats); if (vb) { - vb->handle.vbuf.verts = NULL; - vb->handle.vbuf.inds = NULL; + vb->handle.vbuf.verts = nullptr; + vb->handle.vbuf.inds = nullptr; p->vertex_data_length = vbuf_size; p->index_data_length = ibuf_size; @@ -643,7 +643,7 @@ static rrbool RADLINK gdraw_MakeVertexBufferMore(GDraw_MakeVertexBuffer_Processi static GDrawVertexBuffer * RADLINK gdraw_MakeVertexBufferEnd(GDraw_MakeVertexBuffer_ProcessingInfo *p, GDrawStats * /*stats*/) { - GDrawHandle *vb = (GDrawHandle *) p->p0; + GDrawHandle *vb = static_cast(p->p0); HRESULT hr; D3D1X_(BUFFER_DESC) vbdesc = { static_cast(p->vertex_data_length), D3D1X_(USAGE_IMMUTABLE), D3D1X_(BIND_VERTEX_BUFFER), 0U, 0U }; @@ -661,7 +661,7 @@ static GDrawVertexBuffer * RADLINK gdraw_MakeVertexBufferEnd(GDraw_MakeVertexBuf safe_release(vb->handle.vbuf.inds); gdraw_HandleCacheAllocateFail(vb); - vb = NULL; + vb = nullptr; report_d3d_error(hr, "CreateBuffer", " creating vertex buffer"); } else { @@ -682,7 +682,7 @@ static rrbool RADLINK gdraw_TryLockVertexBuffer(GDrawVertexBuffer *vb, void *uni static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); // @GDRAW_ASSERT + assert(h != nullptr); // @GDRAW_ASSERT if (h->owner == unique_id) gdraw_res_free(h, stats); } @@ -712,31 +712,31 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) // ran out of RTs, allocate a new one S32 size = gdraw->frametex_width * gdraw->frametex_height * 4; if (gdraw->rendertargets.bytes_free < size) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit size limit of %d bytes", gdraw->rendertargets.total_bytes); - return NULL; + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit size limit of %d bytes", gdraw->rendertargets.total_bytes); + return nullptr; } t = gdraw_HandleCacheAllocateBegin(&gdraw->rendertargets); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget allocation failed: hit handle limit"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget allocation failed: hit handle limit"); return t; } D3D1X_(TEXTURE2D_DESC) desc = { static_cast(gdraw->frametex_width), static_cast(gdraw->frametex_height), 1U, 1U, DXGI_FORMAT_R8G8B8A8_UNORM, { 1, 0 }, D3D1X_(USAGE_DEFAULT), D3D1X_(BIND_SHADER_RESOURCE) | D3D1X_(BIND_RENDER_TARGET), 0U, 0U }; - t->handle.tex.d3d = NULL; - t->handle.tex.d3d_view = NULL; - t->handle.tex.d3d_rtview = NULL; + t->handle.tex.d3d = nullptr; + t->handle.tex.d3d_view = nullptr; + t->handle.tex.d3d_rtview = nullptr; - HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, NULL, &t->handle.tex.d3d); + HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, nullptr, &t->handle.tex.d3d); failed_call = "CreateTexture2D"; if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_view); + hr = gdraw->d3d_device->CreateShaderResourceView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_view); failed_call = "CreateTexture2D"; } if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateRenderTargetView(t->handle.tex.d3d, NULL, &t->handle.tex.d3d_rtview); + hr = gdraw->d3d_device->CreateRenderTargetView(t->handle.tex.d3d, nullptr, &t->handle.tex.d3d_rtview); failed_call = "CreateRenderTargetView"; } @@ -748,7 +748,7 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *stats) report_d3d_error(hr, failed_call, " creating rendertarget"); - return NULL; + return nullptr; } gdraw_HandleCacheAllocateEnd(t, size, (void *) 1, GDRAW_HANDLE_STATE_locked); @@ -768,10 +768,10 @@ static ID3D1X(DepthStencilView) *get_rendertarget_depthbuffer(GDrawStats *stats) D3D1X_(TEXTURE2D_DESC) desc = { static_cast(gdraw->frametex_width), static_cast(gdraw->frametex_height), 1U, 1U, DXGI_FORMAT_D24_UNORM_S8_UINT, { 1, 0 }, D3D1X_(USAGE_DEFAULT), D3D1X_(BIND_DEPTH_STENCIL), 0U, 0U }; - HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, NULL, &gdraw->rt_depth_buffer); + HRESULT hr = gdraw->d3d_device->CreateTexture2D(&desc, nullptr, &gdraw->rt_depth_buffer); failed_call = "CreateTexture2D"; if (!FAILED(hr)) { - hr = gdraw->d3d_device->CreateDepthStencilView(gdraw->rt_depth_buffer, NULL, &gdraw->depth_buffer[1]); + hr = gdraw->d3d_device->CreateDepthStencilView(gdraw->rt_depth_buffer, nullptr, &gdraw->depth_buffer[1]); failed_call = "CreateDepthStencilView while creating rendertarget"; } @@ -861,7 +861,7 @@ static void disable_scissor(int force) static void set_viewport_raw(S32 x, S32 y, S32 w, S32 h) { - D3D1X_(VIEWPORT) vp = { (ViewCoord) x, (ViewCoord) y, (ViewCoord) w, (ViewCoord) h, 0.0f, 1.0f }; + D3D1X_(VIEWPORT) vp = { static_cast(x), static_cast(y), static_cast(w), static_cast(h), 0.0f, 1.0f }; gdraw->d3d_context->RSSetViewports(1, &vp); gdraw->cview.x = x; gdraw->cview.y = y; @@ -891,8 +891,8 @@ static void set_projection_raw(S32 x0, S32 x1, S32 y0, S32 y1) { gdraw->projection[0] = 2.0f / (x1-x0); gdraw->projection[1] = 2.0f / (y1-y0); - gdraw->projection[2] = (x1+x0)/(F32)(x0-x1); - gdraw->projection[3] = (y1+y0)/(F32)(y0-y1); + gdraw->projection[2] = (x1+x0)/static_cast(x0 - x1); + gdraw->projection[3] = (y1+y0)/static_cast(y0 - y1); set_projection_base(); } @@ -996,6 +996,9 @@ void gdraw_D3D1X_(SetTileOrigin)(ID3D1X(RenderTargetView) *main_rt, ID3D1X(Depth static void RADLINK gdraw_SetViewSizeAndWorldScale(S32 w, S32 h, F32 scalex, F32 scaley) { + static S32 s_lastW = 0, s_lastH = 0; + static F32 s_lastSx = 0, s_lastSy = 0; + memset(gdraw->frame, 0, sizeof(gdraw->frame)); gdraw->cur = gdraw->frame; gdraw->fw = w; @@ -1113,7 +1116,7 @@ static void set_render_target(GDrawStats *stats) gdraw->d3d_context->OMSetRenderTargets(1, &target, gdraw->depth_buffer[0]); gdraw->d3d_context->RSSetState(gdraw->raster_state[gdraw->main_msaa]); } else { - ID3D1X(DepthStencilView) *depth = NULL; + ID3D1X(DepthStencilView) *depth = nullptr; if (gdraw->cur->flags & (GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_id | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_stencil)) depth = get_rendertarget_depthbuffer(stats); @@ -1128,15 +1131,15 @@ static void set_render_target(GDrawStats *stats) static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_texture_format /*format*/, U32 flags, void *owner, GDrawStats *stats) { GDrawFramebufferState *n = gdraw->cur+1; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (gdraw->tw == 0 || gdraw->th == 0) { - IggyGDrawSendWarning(NULL, "GDraw warning: w=0,h=0 rendertarget"); + IggyGDrawSendWarning(nullptr, "GDraw warning: w=0,h=0 rendertarget"); return false; } if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) { assert(0); - IggyGDrawSendWarning(NULL, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget nesting exceeds MAX_RENDER_STACK_DEPTH"); return false; } @@ -1150,10 +1153,10 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex n->flags = flags; n->color_buffer = t; - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT ++gdraw->cur; - gdraw->cur->cached = owner != NULL; + gdraw->cur->cached = owner != nullptr; if (owner) { gdraw->cur->base_x = region->x0; gdraw->cur->base_y = region->y0; @@ -1164,7 +1167,7 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex set_render_target(stats); assert(gdraw->frametex_width >= gdraw->tw && gdraw->frametex_height >= gdraw->th); // @GDRAW_ASSERT - S32 k = (S32) (t - gdraw->rendertargets.handle); + S32 k = static_cast(t - gdraw->rendertargets.handle); if (region) { gswf_recti r; @@ -1190,7 +1193,7 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex if (r.x1 <= r.x0 || r.y1 <= r.y0) { // region doesn't intersect with current tile --gdraw->cur; - gdraw_FreeTexture((GDrawTexture *) t, 0, stats); + gdraw_FreeTexture((GDrawTexture *) t, nullptr, stats); // note: don't send a warning since this will happen during regular tiled rendering return false; } @@ -1224,17 +1227,17 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *stats) { GDrawFramebufferState *n = gdraw->cur; GDrawFramebufferState *m = --gdraw->cur; - if (gdraw->tw == 0 || gdraw->th == 0) return 0; + if (gdraw->tw == 0 || gdraw->th == 0) return nullptr; if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) - return 0; // already returned a warning in Begin + return nullptr; // already returned a warning in Begin assert(m >= gdraw->frame); // bug in Iggy -- unbalanced if (m != gdraw->frame) { - assert(m->color_buffer != NULL); // @GDRAW_ASSERT + assert(m->color_buffer != nullptr); // @GDRAW_ASSERT } - assert(n->color_buffer != NULL); // @GDRAW_ASSERT + assert(n->color_buffer != nullptr); // @GDRAW_ASSERT // switch back to old render target set_render_target(stats); @@ -1284,15 +1287,15 @@ static void RADLINK gdraw_ClearID(void) // assuming the depth buffer has been mappped to 0..1 static F32 depth_from_id(S32 id) { - return 1.0f - ((F32) id + 1.0f) / MAX_DEPTH_VALUE; + return 1.0f - (static_cast(id) + 1.0f) / MAX_DEPTH_VALUE; } static void set_texture(S32 texunit, GDrawTexture *tex, rrbool nearest, S32 wrap) { ID3D1XContext *d3d = gdraw->d3d_context; - if (tex == NULL) { - ID3D1X(ShaderResourceView) *notex = NULL; + if (tex == nullptr) { + ID3D1X(ShaderResourceView) *notex = nullptr; d3d->PSSetShaderResources(texunit, 1, ¬ex); } else { GDrawHandle *h = (GDrawHandle *) tex; @@ -1303,7 +1306,7 @@ static void set_texture(S32 texunit, GDrawTexture *tex, rrbool nearest, S32 wrap static void RADLINK gdraw_Set3DTransform(F32 *mat) { - if (mat == NULL) + if (mat == nullptr) gdraw->use_3d = 0; else { gdraw->use_3d = 1; @@ -1319,7 +1322,7 @@ static int set_renderstate_full(S32 vertex_format, GDrawRenderState *r, GDrawSta set_vertex_shader(d3d, gdraw->vert[vertex_format].vshader); // set vertex shader constants - if (VertexVars *vvars = (VertexVars *) map_buffer(gdraw->d3d_context, gdraw->cb_vertex, true)) { + if (VertexVars *vvars = static_cast(map_buffer(gdraw->d3d_context, gdraw->cb_vertex, true))) { F32 depth = depth_from_id(r->id); if (!r->use_world_space) gdraw_ObjectSpace(vvars->world[0], r->o2w, depth, 0.0f); @@ -1366,9 +1369,9 @@ static int set_renderstate_full(S32 vertex_format, GDrawRenderState *r, GDrawSta // in stencil set mode, prefer not doing any shading at all // but if alpha test is on, we need to make an exception -#ifndef GDRAW_D3D11_LEVEL9 // level9 can't do NULL PS it seems +#ifndef GDRAW_D3D11_LEVEL9 // level9 can't do nullptr PS it seems if (which != GDRAW_TEXTURE_alpha_test) - program = NULL; + program = nullptr; else #endif { @@ -1384,7 +1387,7 @@ static int set_renderstate_full(S32 vertex_format, GDrawRenderState *r, GDrawSta set_texture(0, r->tex[0], r->nearest0, r->wrap0); // pixel shader constants - if (PixelCommonVars *pvars = (PixelCommonVars *) map_buffer(gdraw->d3d_context, gdraw->cb_ps_common, true)) { + if (PixelCommonVars *pvars = static_cast(map_buffer(gdraw->d3d_context, gdraw->cb_ps_common, true))) { memcpy(pvars->color_mul, r->color, 4*sizeof(float)); if (r->cxf_add) { @@ -1478,13 +1481,13 @@ static int vertsize[GDRAW_vformat__basic_count] = { // Draw triangles with a given renderstate // -static void tag_resources(void *r1, void *r2=NULL, void *r3=NULL, void *r4=NULL) +static void tag_resources(void *r1, void *r2=nullptr, void *r3=nullptr, void *r4=nullptr) { U64 now = gdraw->frame_counter; - if (r1) ((GDrawHandle *) r1)->fence.value = now; - if (r2) ((GDrawHandle *) r2)->fence.value = now; - if (r3) ((GDrawHandle *) r3)->fence.value = now; - if (r4) ((GDrawHandle *) r4)->fence.value = now; + if (r1) static_cast(r1)->fence.value = now; + if (r2) static_cast(r2)->fence.value = now; + if (r3) static_cast(r3)->fence.value = now; + if (r4) static_cast(r4)->fence.value = now; } static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimitive *p, GDrawVertexBuffer *buf, GDrawStats *stats) @@ -1501,10 +1504,10 @@ static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimiti d3d->IASetInputLayout(gdraw->inlayout[vfmt]); if (vb) { - UINT offs = (UINT) (UINTa) p->vertices; + UINT offs = static_cast((UINTa)p->vertices); d3d->IASetVertexBuffers(0, 1, &vb->handle.vbuf.verts, &stride, &offs); - d3d->IASetIndexBuffer(vb->handle.vbuf.inds, DXGI_FORMAT_R16_UINT, (UINT) (UINTa) p->indices); + d3d->IASetIndexBuffer(vb->handle.vbuf.inds, DXGI_FORMAT_R16_UINT, static_cast((UINTa)p->indices)); d3d->DrawIndexed(p->num_indices, 0, 0); } else if (p->indices) { U32 vbytes = p->num_vertices * stride; @@ -1581,10 +1584,10 @@ static void set_pixel_constant(F32 *constant, F32 x, F32 y, F32 z, F32 w) static void do_screen_quad(gswf_recti *s, const F32 *tc, GDrawStats *stats) { ID3D1XContext *d3d = gdraw->d3d_context; - F32 px0 = (F32) s->x0, py0 = (F32) s->y0, px1 = (F32) s->x1, py1 = (F32) s->y1; + F32 px0 = static_cast(s->x0), py0 = static_cast(s->y0), px1 = static_cast(s->x1), py1 = static_cast(s->y1); // generate vertex data - gswf_vertex_xyst *vert = (gswf_vertex_xyst *) start_write_dyn(&gdraw->dyn_vb, 4 * sizeof(gswf_vertex_xyst)); + gswf_vertex_xyst *vert = static_cast(start_write_dyn(&gdraw->dyn_vb, 4 * sizeof(gswf_vertex_xyst))); if (!vert) return; @@ -1595,7 +1598,7 @@ static void do_screen_quad(gswf_recti *s, const F32 *tc, GDrawStats *stats) UINT offs = end_write_dyn(&gdraw->dyn_vb); UINT stride = sizeof(gswf_vertex_xyst); - if (VertexVars *vvars = (VertexVars *) map_buffer(gdraw->d3d_context, gdraw->cb_vertex, true)) { + if (VertexVars *vvars = static_cast(map_buffer(gdraw->d3d_context, gdraw->cb_vertex, true))) { gdraw_PixelSpace(vvars->world[0]); memcpy(vvars->x3d, gdraw->projmat, 12*sizeof(F32)); unmap_buffer(gdraw->d3d_context, gdraw->cb_vertex); @@ -1629,7 +1632,7 @@ static void manual_clear(gswf_recti *r, GDrawStats *stats) set_projection_raw(0, gdraw->frametex_width, gdraw->frametex_height, 0); set_pixel_shader(d3d, gdraw->clear_ps.pshader); - if (PixelCommonVars *pvars = (PixelCommonVars *) map_buffer(gdraw->d3d_context, gdraw->cb_ps_common, true)) { + if (PixelCommonVars *pvars = static_cast(map_buffer(gdraw->d3d_context, gdraw->cb_ps_common, true))) { memset(pvars, 0, sizeof(*pvars)); unmap_buffer(gdraw->d3d_context, gdraw->cb_ps_common); d3d->PSSetConstantBuffers(0, 1, &gdraw->cb_ps_common); @@ -1643,7 +1646,7 @@ static void gdraw_DriverBlurPass(GDrawRenderState *r, int taps, float *data, gs set_texture(0, r->tex[0], false, GDRAW_WRAP_clamp); set_pixel_shader(gdraw->d3d_context, gdraw->blur_prog[taps].pshader); - PixelParaBlur *para = (PixelParaBlur *) start_ps_constants(gdraw->cb_blur); + PixelParaBlur *para = static_cast(start_ps_constants(gdraw->cb_blur)); memcpy(para->clamp, clamp, 4 * sizeof(float)); memcpy(para->tap, data, taps * 4 * sizeof(float)); end_ps_constants(gdraw->cb_blur); @@ -1654,13 +1657,13 @@ static void gdraw_DriverBlurPass(GDrawRenderState *r, int taps, float *data, gs static void gdraw_Colormatrix(GDrawRenderState *r, gswf_recti *s, float *tc, GDrawStats *stats) { - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, stats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, stats)) return; set_texture(0, r->tex[0], false, GDRAW_WRAP_clamp); set_pixel_shader(gdraw->d3d_context, gdraw->colormatrix.pshader); - PixelParaColorMatrix *para = (PixelParaColorMatrix *) start_ps_constants(gdraw->cb_colormatrix); + PixelParaColorMatrix *para = static_cast(start_ps_constants(gdraw->cb_colormatrix)); memcpy(para->data, r->shader_data, 5 * 4 * sizeof(float)); end_ps_constants(gdraw->cb_colormatrix); @@ -1672,7 +1675,7 @@ static void gdraw_Colormatrix(GDrawRenderState *r, gswf_recti *s, float *tc, GDr static gswf_recti *get_valid_rect(GDrawTexture *tex) { GDrawHandle *h = (GDrawHandle *) tex; - S32 n = (S32) (h - gdraw->rendertargets.handle); + S32 n = static_cast(h - gdraw->rendertargets.handle); assert(n >= 0 && n <= MAX_RENDER_STACK_DEPTH+1); return &gdraw->rt_valid[n]; } @@ -1690,7 +1693,7 @@ static void set_clamp_constant(F32 *constant, GDrawTexture *tex) static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbevel, GDrawStats *stats) { - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, stats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, stats)) return; set_texture(0, r->tex[0], false, GDRAW_WRAP_clamp); @@ -1698,12 +1701,12 @@ static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbe set_texture(2, r->tex[2], false, GDRAW_WRAP_clamp); set_pixel_shader(gdraw->d3d_context, gdraw->filter_prog[isbevel][r->filter_mode].pshader); - PixelParaFilter *para = (PixelParaFilter *) start_ps_constants(gdraw->cb_filter); + PixelParaFilter *para = static_cast(start_ps_constants(gdraw->cb_filter)); set_clamp_constant(para->clamp0, r->tex[0]); set_clamp_constant(para->clamp1, r->tex[1]); set_pixel_constant(para->color, r->shader_data[0], r->shader_data[1], r->shader_data[2], r->shader_data[3]); set_pixel_constant(para->color2, r->shader_data[8], r->shader_data[9], r->shader_data[10], r->shader_data[11]); - set_pixel_constant(para->tc_off, -r->shader_data[4] / (F32)gdraw->frametex_width, -r->shader_data[5] / (F32)gdraw->frametex_height, r->shader_data[6], 0); + set_pixel_constant(para->tc_off, -r->shader_data[4] / static_cast(gdraw->frametex_width), -r->shader_data[5] / static_cast(gdraw->frametex_height), r->shader_data[6], 0); end_ps_constants(gdraw->cb_filter); do_screen_quad(s, tc, stats); @@ -1725,10 +1728,10 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 if (s.x1 < s.x0 || s.y1 < s.y0) return; - tc[0] = (s.x0 - gdraw->tx0p) / (F32) gdraw->frametex_width; - tc[1] = (s.y0 - gdraw->ty0p) / (F32) gdraw->frametex_height; - tc[2] = (s.x1 - gdraw->tx0p) / (F32) gdraw->frametex_width; - tc[3] = (s.y1 - gdraw->ty0p) / (F32) gdraw->frametex_height; + tc[0] = (s.x0 - gdraw->tx0p) / static_cast(gdraw->frametex_width); + tc[1] = (s.y0 - gdraw->ty0p) / static_cast(gdraw->frametex_height); + tc[2] = (s.x1 - gdraw->tx0p) / static_cast(gdraw->frametex_width); + tc[3] = (s.y1 - gdraw->ty0p) / static_cast(gdraw->frametex_height); // clear to known render state d3d->OMSetBlendState(gdraw->blend_state[GDRAW_BLEND_none], four_zeros, ~0u); @@ -1778,7 +1781,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 assert(0); } } else { - GDrawHandle *blend_tex = NULL; + GDrawHandle *blend_tex = nullptr; // for crazy blend modes, we need to read back from the framebuffer // and do the blending in the pixel shader. we do this with copies @@ -1811,10 +1814,10 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 d3d->PSSetSamplers(1, 1, &gdraw->sampler_state[0][GDRAW_WRAP_clamp]); // calculate texture coordinate remapping - rescale1[0] = gdraw->frametex_width / (F32) texdesc.Width; - rescale1[1] = gdraw->frametex_height / (F32) texdesc.Height; - rescale1[2] = (gdraw->vx - gdraw->tx0 + gdraw->tx0p) / (F32) texdesc.Width; - rescale1[3] = (gdraw->vy - gdraw->ty0 + gdraw->ty0p) / (F32) texdesc.Height; + rescale1[0] = gdraw->frametex_width / static_cast(texdesc.Width); + rescale1[1] = gdraw->frametex_height / static_cast(texdesc.Height); + rescale1[2] = (gdraw->vx - gdraw->tx0 + gdraw->tx0p) / static_cast(texdesc.Width); + rescale1[3] = (gdraw->vy - gdraw->ty0 + gdraw->ty0p) / static_cast(texdesc.Height); } else { D3D1X_(BOX) box = { 0,0,0,0,0,1 }; S32 dx = 0, dy = 0; @@ -1847,7 +1850,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 do_screen_quad(&s, tc, stats); tag_resources(r->tex[0], r->tex[1]); if (blend_tex) - gdraw_FreeTexture((GDrawTexture *) blend_tex, 0, stats); + gdraw_FreeTexture((GDrawTexture *) blend_tex, nullptr, stats); } } @@ -1862,18 +1865,18 @@ static void destroy_shader(ProgramWithCachedVariableLocations *p) { if (p->pshader) { p->pshader->Release(); - p->pshader = NULL; + p->pshader = nullptr; } } static ID3D1X(Buffer) *create_dynamic_buffer(U32 size, U32 bind) { D3D1X_(BUFFER_DESC) desc = { size, D3D1X_(USAGE_DYNAMIC), bind, D3D1X_(CPU_ACCESS_WRITE), 0 }; - ID3D1X(Buffer) *buf = NULL; - HRESULT hr = gdraw->d3d_device->CreateBuffer(&desc, NULL, &buf); + ID3D1X(Buffer) *buf = nullptr; + HRESULT hr = gdraw->d3d_device->CreateBuffer(&desc, nullptr, &buf); if (FAILED(hr)) { report_d3d_error(hr, "CreateBuffer", " creating dynamic vertex buffer"); - buf = NULL; + buf = nullptr; } return buf; } @@ -1910,7 +1913,7 @@ static void create_all_shaders_and_state(void) HRESULT hr = d3d->CreateInputLayout(vformats[i].desc, vformats[i].nelem, vsh->bytecode, vsh->size, &gdraw->inlayout[i]); if (FAILED(hr)) { report_d3d_error(hr, "CreateInputLayout", ""); - gdraw->inlayout[i] = NULL; + gdraw->inlayout[i] = nullptr; } } @@ -2029,11 +2032,11 @@ static void create_all_shaders_and_state(void) hr = gdraw->d3d_device->CreateBuffer(&bufdesc, &data, &gdraw->quad_ib); if (FAILED(hr)) { report_d3d_error(hr, "CreateBuffer", " for constants"); - gdraw->quad_ib = NULL; + gdraw->quad_ib = nullptr; } IggyGDrawFree(inds); } else - gdraw->quad_ib = NULL; + gdraw->quad_ib = nullptr; } static void destroy_all_shaders_and_state() @@ -2106,7 +2109,7 @@ static void free_gdraw() if (gdraw->texturecache) IggyGDrawFree(gdraw->texturecache); if (gdraw->vbufcache) IggyGDrawFree(gdraw->vbufcache); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } static bool alloc_dynbuffer(U32 size) @@ -2142,7 +2145,7 @@ static bool alloc_dynbuffer(U32 size) gdraw->max_quad_vert_count = RR_MIN(size / sizeof(gswf_vertex_xyst), QUAD_IB_COUNT * 4); gdraw->max_quad_vert_count &= ~3; // must be multiple of four - return gdraw->dyn_vb.buffer != NULL && gdraw->dyn_ib.buffer != NULL; + return gdraw->dyn_vb.buffer != nullptr && gdraw->dyn_ib.buffer != nullptr; } int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S32 num_bytes) @@ -2181,7 +2184,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 IggyGDrawFree(gdraw->texturecache); } gdraw->texturecache = make_handle_cache(GDRAW_D3D1X_(RESOURCE_texture)); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_D3D1X_(RESOURCE_vertexbuffer): if (gdraw->vbufcache) { @@ -2189,7 +2192,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 IggyGDrawFree(gdraw->vbufcache); } gdraw->vbufcache = make_handle_cache(GDRAW_D3D1X_(RESOURCE_vertexbuffer)); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; case GDRAW_D3D1X_(RESOURCE_dynbuffer): unbind_resources(); @@ -2205,7 +2208,7 @@ int gdraw_D3D1X_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S3 static GDrawFunctions *create_context(ID3D1XDevice *dev, ID3D1XContext *ctx, S32 w, S32 h) { gdraw = (GDraw *) IggyGDrawMalloc(sizeof(*gdraw)); - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -2220,7 +2223,7 @@ static GDrawFunctions *create_context(ID3D1XDevice *dev, ID3D1XContext *ctx, S32 if (!gdraw->texturecache || !gdraw->vbufcache || !alloc_dynbuffer(gdraw_limits[GDRAW_D3D1X_(RESOURCE_dynbuffer)].num_bytes)) { free_gdraw(); - return NULL; + return nullptr; } create_all_shaders_and_state(); @@ -2291,7 +2294,7 @@ void gdraw_D3D1X_(DestroyContext)(void) if (gdraw->texturecache) gdraw_res_flush(gdraw->texturecache, &stats); if (gdraw->vbufcache) gdraw_res_flush(gdraw->vbufcache, &stats); - gdraw->d3d_device = NULL; + gdraw->d3d_device = nullptr; } free_gdraw(); @@ -2354,7 +2357,7 @@ void RADLINK gdraw_D3D1X_(GetResourceUsageStats)(gdraw_resourcetype type, S32 *h case GDRAW_D3D1X_(RESOURCE_texture): cache = gdraw->texturecache; break; case GDRAW_D3D1X_(RESOURCE_vertexbuffer): cache = gdraw->vbufcache; break; case GDRAW_D3D1X_(RESOURCE_dynbuffer): *handles_used = 0; *bytes_used = gdraw->last_dyn_maxalloc; return; - default: cache = NULL; break; + default: cache = nullptr; break; } *handles_used = *bytes_used = 0; @@ -2385,14 +2388,14 @@ static S32 num_pixels(S32 w, S32 h, S32 mipmaps) GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, S32 /*len*/, IggyFileTextureRaw *texture) { const char *failed_call=""; - U8 *free_data = 0; - GDrawTexture *t=0; + U8 *free_data = nullptr; + GDrawTexture *t=nullptr; S32 width, height, mipmaps, size, blk; - ID3D1X(Texture2D) *tex=0; - ID3D1X(ShaderResourceView) *view=0; + ID3D1X(Texture2D) *tex=nullptr; + ID3D1X(ShaderResourceView) *view=nullptr; DXGI_FORMAT d3dfmt; - D3D1X_(SUBRESOURCE_DATA) mipdata[24] = { 0 }; + D3D1X_(SUBRESOURCE_DATA) mipdata[24] = { nullptr }; S32 k; HRESULT hr = S_OK; @@ -2413,7 +2416,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, case IFT_FORMAT_DXT3 : size=16; d3dfmt = DXGI_FORMAT_BC2_UNORM; blk = 4; break; case IFT_FORMAT_DXT5 : size=16; d3dfmt = DXGI_FORMAT_BC3_UNORM; blk = 4; break; default: { - IggyGDrawSendWarning(NULL, "GDraw .iggytex raw texture format %d not supported by hardware", texture->format); + IggyGDrawSendWarning(nullptr, "GDraw .iggytex raw texture format %d not supported by hardware", texture->format); done = true; } } @@ -2430,7 +2433,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, free_data = (U8 *) IggyGDrawMalloc(total_size); if (!free_data) { - IggyGDrawSendWarning(NULL, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); + IggyGDrawSendWarning(nullptr, "GDraw out of memory to store texture data to pass to D3D for %d x %d texture", width, height); done = true; } else { U8 *cur = free_data; @@ -2463,7 +2466,7 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, hr = gdraw->d3d_device->CreateTexture2D(&desc, mipdata, &tex); if (!FAILED(hr)) { failed_call = "CreateShaderResourceView for texture creation"; - hr = gdraw->d3d_device->CreateShaderResourceView(tex, NULL, &view); + hr = gdraw->d3d_device->CreateShaderResourceView(tex, nullptr, &view); if (!FAILED(hr)) t = gdraw_D3D1X_(WrappedTextureCreate)(view); } @@ -2483,14 +2486,14 @@ GDrawTexture * RADLINK gdraw_D3D1X_(MakeTextureFromResource)(U8 *resource_file, if (tex) tex->Release(); } else { - ((GDrawHandle *) t)->handle.tex.d3d = tex; + reinterpret_cast(t)->handle.tex.d3d = tex; } return t; } void RADLINK gdraw_D3D1X_(DestroyTextureFromResource)(GDrawTexture *tex) { - GDrawHandle *h = (GDrawHandle *) tex; + GDrawHandle *h = reinterpret_cast(tex); safe_release(h->handle.tex.d3d_view); safe_release(h->handle.tex.d3d); gdraw_D3D1X_(WrappedTextureDestroy)(tex); diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shaders.inl b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shaders.inl index dc8a0484d..74a292212 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shaders.inl +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shaders.inl @@ -181,7 +181,7 @@ static char *pshader_basic_vars[] = { "color_mul", "color_add", "focal", - NULL + nullptr }; static char pshader_general2_frag0[] = @@ -293,7 +293,7 @@ static char **pshader_general2(void) static char *pshader_general2_vars[] = { "tex0", - NULL + nullptr }; static char pshader_exceptional_blend_frag0[] = @@ -414,7 +414,7 @@ static char pshader_exceptional_blend_frag13[] = #define NUMFRAGMENTS_pshader_exceptional_blend 3 static char *pshader_exceptional_blend_arr[13][NUMFRAGMENTS_pshader_exceptional_blend] = { - { NULL, NULL, NULL, }, + { nullptr, nullptr, nullptr, }, { pshader_exceptional_blend_frag0, pshader_exceptional_blend_frag1, pshader_exceptional_blend_frag2, }, { pshader_exceptional_blend_frag0, pshader_exceptional_blend_frag3, pshader_exceptional_blend_frag2, }, { pshader_exceptional_blend_frag0, pshader_exceptional_blend_frag4, pshader_exceptional_blend_frag2, }, @@ -439,7 +439,7 @@ static char *pshader_exceptional_blend_vars[] = { "tex1", "color_mul", "color_add", - NULL + nullptr }; static char pshader_filter_frag0[] = @@ -593,10 +593,10 @@ static char *pshader_filter_arr[32][NUMFRAGMENTS_pshader_filter] = { { pshader_filter_frag0, pshader_filter_frag1, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag3, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag1, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag4, pshader_filter_frag1, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag1, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag4, pshader_filter_frag3, pshader_filter_frag2, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag3, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag4, pshader_filter_frag1, pshader_filter_frag2, }, @@ -609,10 +609,10 @@ static char *pshader_filter_arr[32][NUMFRAGMENTS_pshader_filter] = { { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag1, pshader_filter_frag3, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag4, pshader_filter_frag1, pshader_filter_frag2, }, { pshader_filter_frag0, pshader_filter_frag7, pshader_filter_frag6, pshader_filter_frag1, pshader_filter_frag4, pshader_filter_frag3, pshader_filter_frag2, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, - { NULL, NULL, NULL, NULL, NULL, NULL, NULL, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, }, }; static char **pshader_filter(int bevel, int ontop, int inner, int gradient, int knockout) @@ -629,7 +629,7 @@ static char *pshader_filter_vars[] = { "clamp0", "clamp1", "color2", - NULL + nullptr }; static char pshader_blur_frag0[] = @@ -701,8 +701,8 @@ static char pshader_blur_frag9[] = #define NUMFRAGMENTS_pshader_blur 3 static char *pshader_blur_arr[10][NUMFRAGMENTS_pshader_blur] = { - { NULL, NULL, NULL, }, - { NULL, NULL, NULL, }, + { nullptr, nullptr, nullptr, }, + { nullptr, nullptr, nullptr, }, { pshader_blur_frag0, pshader_blur_frag1, pshader_blur_frag2, }, { pshader_blur_frag0, pshader_blur_frag3, pshader_blur_frag2, }, { pshader_blur_frag0, pshader_blur_frag4, pshader_blur_frag2, }, @@ -722,7 +722,7 @@ static char *pshader_blur_vars[] = { "tex0", "tap", "clampv", - NULL + nullptr }; static char pshader_color_matrix_frag0[] = @@ -804,7 +804,7 @@ static char **pshader_color_matrix(void) static char *pshader_color_matrix_vars[] = { "tex0", "data", - NULL + nullptr }; static char pshader_manual_clear_frag0[] = @@ -855,7 +855,7 @@ static char **pshader_manual_clear(void) static char *pshader_manual_clear_vars[] = { "color_mul", - NULL + nullptr }; static char vshader_vsgl_frag0[] = @@ -966,7 +966,7 @@ static char *vshader_vsgl_vars[] = { "texgen_s", "texgen_t", "viewproj", - NULL + nullptr }; static char vshader_vsglihud_frag0[] = @@ -1079,6 +1079,6 @@ static char *vshader_vsglihud_vars[] = { "worldview", "material", "textmode", - NULL + nullptr }; diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shared.inl b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shared.inl index 9916096ad..f134b7407 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shared.inl +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_gl_shared.inl @@ -60,7 +60,7 @@ static RADINLINE void break_on_err(GLint e) static void report_err(GLint e) { break_on_err(e); - IggyGDrawSendWarning(NULL, "OpenGL glGetError error"); + IggyGDrawSendWarning(nullptr, "OpenGL glGetError error"); } static void compilation_err(const char *msg) @@ -256,7 +256,7 @@ static void make_texture(GLuint tex) static void make_rendertarget(GDrawHandle *t, GLuint tex, GLenum int_type, GLenum ext_type, GLenum data_type, S32 w, S32 h, S32 size) { glBindTexture(GL_TEXTURE_2D, tex); - glTexImage2D(GL_TEXTURE_2D, 0, int_type, w, h, 0, ext_type, data_type, NULL); + glTexImage2D(GL_TEXTURE_2D, 0, int_type, w, h, 0, ext_type, data_type, nullptr); make_texture(tex); glBindTexture(GL_TEXTURE_2D, 0); } @@ -309,7 +309,7 @@ extern GDrawTexture *gdraw_GLx_(WrappedTextureCreate)(S32 gl_texture_handle, S32 p->handle.tex.w = width; p->handle.tex.h = height; p->handle.tex.nonpow2 = !(is_pow2(width) && is_pow2(height)); - gdraw_HandleCacheAllocateEnd(p, 0, NULL, GDRAW_HANDLE_STATE_user_owned); + gdraw_HandleCacheAllocateEnd(p, 0, nullptr, GDRAW_HANDLE_STATE_user_owned); return (GDrawTexture *) p; } @@ -350,7 +350,7 @@ static void RADLINK gdraw_SetTextureUniqueID(GDrawTexture *tex, void *old_id, vo static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, gdraw_texture_format format, U32 flags, GDraw_MakeTexture_ProcessingInfo *p, GDrawStats *gstats) { S32 size=0, asize, stride; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; opengl_check(); stride = width; @@ -369,7 +369,7 @@ static rrbool RADLINK gdraw_MakeTextureBegin(void *owner, S32 width, S32 height, p->texture_data = IggyGDrawMalloc(size); if (!p->texture_data) { gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, "GDraw malloc for texture data failed"); + IggyGDrawSendWarning(nullptr, "GDraw malloc for texture data failed"); return false; } @@ -419,9 +419,9 @@ static GDrawTexture * RADLINK gdraw_MakeTextureEnd(GDraw_MakeTexture_ProcessingI if (e != 0) { gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, "GDraw OpenGL error creating texture"); + IggyGDrawSendWarning(nullptr, "GDraw OpenGL error creating texture"); eat_gl_err(); - return NULL; + return nullptr; } else { gdraw_HandleCacheAllocateEnd(t, p->i4, p->p1, (flags & GDRAW_MAKETEXTURE_FLAGS_never_flush) ? GDRAW_HANDLE_STATE_pinned : GDRAW_HANDLE_STATE_locked); stats->nonzero_flags |= GDRAW_STATS_alloc_tex; @@ -467,8 +467,8 @@ static void RADLINK gdraw_UpdateTextureEnd(GDrawTexture *tex, void *unique_id, G static void RADLINK gdraw_FreeTexture(GDrawTexture *tt, void *unique_id, GDrawStats *gstats) { GDrawHandle *t = (GDrawHandle *) tt; - assert(t != NULL); - if (t->owner == unique_id || unique_id == NULL) { + assert(t != nullptr); + if (t->owner == unique_id || unique_id == nullptr) { if (t->cache == &gdraw->rendertargets) { gdraw_HandleCacheUnlock(t); // cache it by simply not freeing it @@ -516,7 +516,7 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat opengl_check(); vb = gdraw_res_alloc_begin(gdraw->vbufcache, vbuf_size + ibuf_size, gstats); if (!vb) { - IggyGDrawSendWarning(NULL, "GDraw out of vertex buffer memory"); + IggyGDrawSendWarning(nullptr, "GDraw out of vertex buffer memory"); return false; } @@ -526,9 +526,9 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat glGenBuffers(1, &vb->handle.vbuf.base); glGenBuffers(1, &vb->handle.vbuf.indices); glBindBuffer(GL_ARRAY_BUFFER, vb->handle.vbuf.base); - glBufferData(GL_ARRAY_BUFFER, vbuf_size, NULL, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, vbuf_size, nullptr, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vb->handle.vbuf.indices); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibuf_size, NULL, GL_STATIC_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibuf_size, nullptr, GL_STATIC_DRAW); if (!e) e = glGetError(); if (e != GL_NO_ERROR) { glBindBuffer(GL_ARRAY_BUFFER, 0); @@ -537,7 +537,7 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat glDeleteBuffers(1, &vb->handle.vbuf.indices); gdraw_HandleCacheAllocateFail(vb); eat_gl_err(); - IggyGDrawSendWarning(NULL, "GDraw OpenGL vertex buffer creation failed"); + IggyGDrawSendWarning(nullptr, "GDraw OpenGL vertex buffer creation failed"); return false; } @@ -556,7 +556,7 @@ static rrbool RADLINK gdraw_MakeVertexBufferBegin(void *unique_id, gdraw_vformat if (!p->vertex_data || !p->index_data) { if (p->vertex_data) IggyGDrawFree(p->vertex_data); if (p->index_data) IggyGDrawFree(p->index_data); - IggyGDrawSendWarning(NULL, "GDraw malloc for vertex buffer temporary memory failed"); + IggyGDrawSendWarning(nullptr, "GDraw malloc for vertex buffer temporary memory failed"); return false; } } else { @@ -602,7 +602,7 @@ static GDrawVertexBuffer * RADLINK gdraw_MakeVertexBufferEnd(GDraw_MakeVertexBuf glDeleteBuffers(1, &vb->handle.vbuf.indices); gdraw_HandleCacheAllocateFail(vb); eat_gl_err(); - return NULL; + return nullptr; } else gdraw_HandleCacheAllocateEnd(vb, p->i0 + p->i1, p->p1, GDRAW_HANDLE_STATE_locked); @@ -619,7 +619,7 @@ static rrbool RADLINK gdraw_TryToLockVertexBuffer(GDrawVertexBuffer *vb, void *u static void RADLINK gdraw_FreeVertexBuffer(GDrawVertexBuffer *vb, void *unique_id, GDrawStats *stats) { GDrawHandle *h = (GDrawHandle *) vb; - assert(h != NULL); + assert(h != nullptr); if (h->owner == unique_id) gdraw_res_free(h, stats); } @@ -678,13 +678,13 @@ static GDrawHandle *get_color_rendertarget(GDrawStats *gstats) // ran out of RTs, allocate a new one size = gdraw->frametex_width * gdraw->frametex_height * 4; if (gdraw->rendertargets.bytes_free < size) { - IggyGDrawSendWarning(NULL, "GDraw exceeded available rendertarget memory"); - return NULL; + IggyGDrawSendWarning(nullptr, "GDraw exceeded available rendertarget memory"); + return nullptr; } t = gdraw_HandleCacheAllocateBegin(&gdraw->rendertargets); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw exceeded available rendertarget handles"); + IggyGDrawSendWarning(nullptr, "GDraw exceeded available rendertarget handles"); return t; } @@ -873,7 +873,7 @@ static void RADLINK gdraw_SetViewSizeAndWorldScale(S32 w, S32 h, F32 scalex, F32 static void RADLINK gdraw_Set3DTransform(F32 *mat) { - if (mat == NULL) + if (mat == nullptr) gdraw->use_3d = 0; else { gdraw->use_3d = 1; @@ -992,30 +992,30 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex GDrawHandle *t; int k; if (gdraw->tw == 0 || gdraw->th == 0) { - IggyGDrawSendWarning(NULL, "GDraw got a request for an empty rendertarget"); + IggyGDrawSendWarning(nullptr, "GDraw got a request for an empty rendertarget"); return false; } if (n >= &gdraw->frame[MAX_RENDER_STACK_DEPTH]) { - IggyGDrawSendWarning(NULL, "GDraw rendertarget nesting exceeded MAX_RENDER_STACK_DEPTH"); + IggyGDrawSendWarning(nullptr, "GDraw rendertarget nesting exceeded MAX_RENDER_STACK_DEPTH"); return false; } if (owner) { t = get_rendertarget_texture(region->x1 - region->x0, region->y1 - region->y0, owner, gstats); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw ran out of rendertargets for cacheAsBItmap"); + IggyGDrawSendWarning(nullptr, "GDraw ran out of rendertargets for cacheAsBItmap"); return false; } } else { t = get_color_rendertarget(gstats); if (!t) { - IggyGDrawSendWarning(NULL, "GDraw ran out of rendertargets"); + IggyGDrawSendWarning(nullptr, "GDraw ran out of rendertargets"); return false; } } n->color_buffer = t; - assert(n->color_buffer != NULL); + assert(n->color_buffer != nullptr); if (n == gdraw->frame+1) n->stencil_depth = get_depthstencil_renderbuffer(gstats); @@ -1023,7 +1023,7 @@ static rrbool RADLINK gdraw_TextureDrawBufferBegin(gswf_recti *region, gdraw_tex n->stencil_depth = (n-1)->stencil_depth; ++gdraw->cur; - gdraw->cur->cached = owner != NULL; + gdraw->cur->cached = owner != nullptr; if (owner) { gdraw->cur->base_x = region->x0; gdraw->cur->base_y = region->y0; @@ -1161,8 +1161,8 @@ static GDrawTexture *RADLINK gdraw_TextureDrawBufferEnd(GDrawStats *gstats) assert(m >= gdraw->frame); // bug in Iggy -- unbalanced if (m != gdraw->frame) - assert(m->color_buffer != NULL); - assert(n->color_buffer != NULL); + assert(m->color_buffer != nullptr); + assert(n->color_buffer != nullptr); // remove color and stencil buffers glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, 0); @@ -1274,7 +1274,7 @@ static float depth_from_id(S32 id) static void set_texture(U32 texunit, GDrawTexture *tex) { glActiveTexture(GL_TEXTURE0 + texunit); - if (tex == NULL) + if (tex == nullptr) glBindTexture(GL_TEXTURE_2D, 0); else glBindTexture(GL_TEXTURE_2D, ((GDrawHandle *) tex)->handle.tex.gl); @@ -1575,7 +1575,7 @@ static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimiti glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } - if (!set_render_state(r,p->vertex_format, NULL, p, gstats)) return; + if (!set_render_state(r,p->vertex_format, nullptr, p, gstats)) return; gstats->nonzero_flags |= GDRAW_STATS_batches; gstats->num_batches += 1; gstats->drawn_indices += p->num_indices; @@ -1593,7 +1593,7 @@ static void RADLINK gdraw_DrawIndexedTriangles(GDrawRenderState *r, GDrawPrimiti while (pos < p->num_vertices) { S32 vert_count = RR_MIN(p->num_vertices - pos, QUAD_IB_COUNT * 4); set_vertex_format(p->vertex_format, p->vertices + pos*stride); - glDrawElements(GL_TRIANGLES, (vert_count >> 2) * 6, GL_UNSIGNED_SHORT, NULL); + glDrawElements(GL_TRIANGLES, (vert_count >> 2) * 6, GL_UNSIGNED_SHORT, nullptr); pos += vert_count; } @@ -1719,7 +1719,7 @@ static void gdraw_DriverBlurPass(GDrawRenderState *r, int taps, F32 *data, gswf_ static void gdraw_Colormatrix(GDrawRenderState *r, gswf_recti *s, float *tc, GDrawStats *gstats) { ProgramWithCachedVariableLocations *prg = &gdraw->colormatrix; - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, gstats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, gstats)) return; use_lazy_shader(prg); set_texture(0, r->tex[0]); @@ -1752,7 +1752,7 @@ static void set_clamp_constant(GLint constant, GDrawTexture *tex) static void gdraw_Filter(GDrawRenderState *r, gswf_recti *s, float *tc, int isbevel, GDrawStats *gstats) { ProgramWithCachedVariableLocations *prg = &gdraw->filter_prog[isbevel][r->filter_mode]; - if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, NULL, gstats)) + if (!gdraw_TextureDrawBufferBegin(s, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, nullptr, gstats)) return; use_lazy_shader(prg); set_texture(0, r->tex[0]); @@ -1845,7 +1845,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 assert(0); } } else { - GDrawTexture *blend_tex = NULL; + GDrawTexture *blend_tex = nullptr; const int *vvars; // for crazy blend modes, we need to read back from the framebuffer @@ -1864,7 +1864,7 @@ static void RADLINK gdraw_FilterQuad(GDrawRenderState *r, S32 x0, S32 y0, S32 x1 set_texture(1, blend_tex); } - if (!set_render_state(r, GDRAW_vformat_v2tc2, &vvars, NULL, gstats)) + if (!set_render_state(r, GDRAW_vformat_v2tc2, &vvars, nullptr, gstats)) return; do_screen_quad(&s, tc, vvars, gstats, 0); tag_resources(r->tex[0],r->tex[1],0); @@ -1932,7 +1932,7 @@ static void make_fragment_program(ProgramWithCachedVariableLocations *p, int num } shad = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(shad, num_strings, (const GLchar **)strings, NULL); + glShaderSource(shad, num_strings, (const GLchar **)strings, nullptr); glCompileShader(shad); glGetShaderiv(shad, GL_COMPILE_STATUS, &res); if (!res) { @@ -1994,7 +1994,7 @@ static void make_vertex_program(GLuint *vprog, int num_strings, char **strings) if(strings[0]) { shad = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(shad, num_strings, (const GLchar **)strings, NULL); + glShaderSource(shad, num_strings, (const GLchar **)strings, nullptr); glCompileShader(shad); glGetShaderiv(shad, GL_COMPILE_STATUS, &res); if (!res) { @@ -2154,7 +2154,7 @@ static void free_gdraw() if (gdraw->texturecache) IggyGDrawFree(gdraw->texturecache); if (gdraw->vbufcache) IggyGDrawFree(gdraw->vbufcache); IggyGDrawFree(gdraw); - gdraw = NULL; + gdraw = nullptr; } int gdraw_GLx_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S32 num_bytes) @@ -2193,7 +2193,7 @@ int gdraw_GLx_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S32 IggyGDrawFree(gdraw->texturecache); } gdraw->texturecache = make_handle_cache(GDRAW_GLx_(RESOURCE_texture)); - return gdraw->texturecache != NULL; + return gdraw->texturecache != nullptr; case GDRAW_GLx_(RESOURCE_vertexbuffer): if (gdraw->vbufcache) { @@ -2201,7 +2201,7 @@ int gdraw_GLx_(SetResourceLimits)(gdraw_resourcetype type, S32 num_handles, S32 IggyGDrawFree(gdraw->vbufcache); } gdraw->vbufcache = make_handle_cache(GDRAW_GLx_(RESOURCE_vertexbuffer)); - return gdraw->vbufcache != NULL; + return gdraw->vbufcache != nullptr; default: return 0; @@ -2220,12 +2220,12 @@ GDrawTexture * RADLINK gdraw_GLx_(MakeTextureFromResource)(U8 *resource_file, S3 while (fmt->iggyfmt != texture->format && fmt->blkbytes) fmt++; if (!fmt->blkbytes) // end of list - i.e. format not supported - return NULL; + return nullptr; // prepare texture glGenTextures(1, &gl_texture_handle); if (gl_texture_handle == 0) - return NULL; + return nullptr; opengl_check(); make_texture(gl_texture_handle); @@ -2283,7 +2283,7 @@ GDrawTexture * RADLINK gdraw_GLx_(MakeTextureFromResource)(U8 *resource_file, S3 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mips-1); tex = gdraw_GLx_(WrappedTextureCreate)(gl_texture_handle, texture->w, texture->h, mips > 1); - if (tex == NULL) + if (tex == nullptr) glDeleteTextures(1, &gl_texture_handle); opengl_check(); return tex; @@ -2301,7 +2301,7 @@ static rrbool hasext(const char *exts, const char *which) size_t len; #ifdef GDRAW_USE_glGetStringi - if (exts == NULL) { + if (exts == nullptr) { GLint i, num_exts; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts); for (i=0; i < num_exts; ++i) @@ -2316,7 +2316,7 @@ static rrbool hasext(const char *exts, const char *which) for(;;) { where = strstr(where, which); - if (where == NULL) + if (where == nullptr) return false; if ( (where == exts || *(where - 1) == ' ') // starts with terminator @@ -2329,7 +2329,7 @@ static rrbool hasext(const char *exts, const char *which) static GDrawFunctions *create_context(S32 w, S32 h) { gdraw = IggyGDrawMalloc(sizeof(*gdraw)); - if (!gdraw) return NULL; + if (!gdraw) return nullptr; memset(gdraw, 0, sizeof(*gdraw)); @@ -2339,7 +2339,7 @@ static GDrawFunctions *create_context(S32 w, S32 h) if (!gdraw->texturecache || !gdraw->vbufcache || !make_quad_indices()) { free_gdraw(); - return NULL; + return nullptr; } opengl_check(); @@ -2380,7 +2380,7 @@ static GDrawFunctions *create_context(S32 w, S32 h) gdraw_funcs.ClearID = gdraw_ClearID; gdraw_funcs.MakeTextureBegin = gdraw_MakeTextureBegin; - gdraw_funcs.MakeTextureMore = NULL; + gdraw_funcs.MakeTextureMore = nullptr; gdraw_funcs.MakeTextureEnd = gdraw_MakeTextureEnd; gdraw_funcs.UpdateTextureRect = gdraw_UpdateTextureRect; diff --git a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_shared.inl b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_shared.inl index a60fa520c..1790de77e 100644 --- a/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_shared.inl +++ b/Minecraft.Client/Windows64/Iggy/gdraw/gdraw_shared.inl @@ -226,7 +226,7 @@ static void debug_check_raw_values(GDrawHandleCache *c) s = s->next; } s = c->active; - while (s != NULL) { + while (s != nullptr) { assert(s->raw_ptr != t->raw_ptr); s = s->next; } @@ -368,7 +368,7 @@ static void gdraw_HandleTransitionInsertBefore(GDrawHandle *t, GDrawHandleState { check_lists(t->cache); assert(t->state != GDRAW_HANDLE_STATE_sentinel); // sentinels should never get here! - assert(t->state != (U32) new_state); // code should never call "transition" if it's not transitioning! + assert(t->state != static_cast(new_state)); // code should never call "transition" if it's not transitioning! // unlink from prev state t->prev->next = t->next; t->next->prev = t->prev; @@ -433,7 +433,7 @@ static rrbool gdraw_HandleCacheLockStats(GDrawHandle *t, void *owner, GDrawStats static rrbool gdraw_HandleCacheLock(GDrawHandle *t, void *owner) { - return gdraw_HandleCacheLockStats(t, owner, NULL); + return gdraw_HandleCacheLockStats(t, owner, nullptr); } static void gdraw_HandleCacheUnlock(GDrawHandle *t) @@ -461,11 +461,11 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->is_thrashing = false; c->did_defragment = false; for (i=0; i < GDRAW_HANDLE_STATE__count; i++) { - c->state[i].owner = NULL; - c->state[i].cache = NULL; // should never follow cache link from sentinels! + c->state[i].owner = nullptr; + c->state[i].cache = nullptr; // should never follow cache link from sentinels! c->state[i].next = c->state[i].prev = &c->state[i]; #ifdef GDRAW_MANAGE_MEM - c->state[i].raw_ptr = NULL; + c->state[i].raw_ptr = nullptr; #endif c->state[i].fence.value = 0; c->state[i].bytes = 0; @@ -478,7 +478,7 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->handle[i].bytes = 0; c->handle[i].state = GDRAW_HANDLE_STATE_free; #ifdef GDRAW_MANAGE_MEM - c->handle[i].raw_ptr = NULL; + c->handle[i].raw_ptr = nullptr; #endif } c->state[GDRAW_HANDLE_STATE_free].next = &c->handle[0]; @@ -486,10 +486,10 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte c->prev_frame_start.value = 0; c->prev_frame_end.value = 0; #ifdef GDRAW_MANAGE_MEM - c->alloc = NULL; + c->alloc = nullptr; #endif #ifdef GDRAW_MANAGE_MEM_TWOPOOL - c->alloc_other = NULL; + c->alloc_other = nullptr; #endif check_lists(c); } @@ -497,14 +497,14 @@ static void gdraw_HandleCacheInit(GDrawHandleCache *c, S32 num_handles, S32 byte static GDrawHandle *gdraw_HandleCacheAllocateBegin(GDrawHandleCache *c) { GDrawHandle *free_list = &c->state[GDRAW_HANDLE_STATE_free]; - GDrawHandle *t = NULL; + GDrawHandle *t = nullptr; if (free_list->next != free_list) { t = free_list->next; gdraw_HandleTransitionTo(t, GDRAW_HANDLE_STATE_alloc); t->bytes = 0; t->owner = 0; #ifdef GDRAW_MANAGE_MEM - t->raw_ptr = NULL; + t->raw_ptr = nullptr; #endif #ifdef GDRAW_CORRUPTION_CHECK t->has_check_value = false; @@ -558,7 +558,7 @@ static GDrawHandle *gdraw_HandleCacheGetLRU(GDrawHandleCache *c) // at the front of the LRU list are the oldest ones, since in-use resources // will get appended on every transition from "locked" to "live". GDrawHandle *sentinel = &c->state[GDRAW_HANDLE_STATE_live]; - return (sentinel->next != sentinel) ? sentinel->next : NULL; + return (sentinel->next != sentinel) ? sentinel->next : nullptr; } static void gdraw_HandleCacheTick(GDrawHandleCache *c, GDrawFence now) @@ -773,7 +773,7 @@ static GDrawTexture *gdraw_BlurPass(GDrawFunctions *g, GDrawBlurInfo *c, GDrawRe if (!g->TextureDrawBufferBegin(draw_bounds, GDRAW_TEXTURE_FORMAT_rgba32, GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_color | GDRAW_TEXTUREDRAWBUFFER_FLAGS_needs_alpha, 0, gstats)) return r->tex[0]; - c->BlurPass(r, taps, data, draw_bounds, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, draw_bounds, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -825,7 +825,7 @@ static GDrawTexture *gdraw_BlurPassDownsample(GDrawFunctions *g, GDrawBlurInfo * assert(clamp[0] <= clamp[2]); assert(clamp[1] <= clamp[3]); - c->BlurPass(r, taps, data, &z, tc, (F32) c->h / c->frametex_height, clamp, gstats); + c->BlurPass(r, taps, data, &z, tc, static_cast(c->h) / c->frametex_height, clamp, gstats); return g->TextureDrawBufferEnd(gstats); } @@ -837,7 +837,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR GDrawTexture *t; F32 data[MAX_TAPS][4]; S32 off_axis = 1-axis; - S32 w = ((S32) ceil((blur_width-1)/2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 + S32 w = static_cast(ceil((blur_width - 1) / 2))*2+1; // 1.2 => 3, 2.8 => 3, 3.2 => 5 F32 edge_weight = 1 - (w - blur_width)/2; // 3 => 0 => 1; 1.2 => 1.8 => 0.9 => 0.1 F32 inverse_weight = 1.0f / blur_width; @@ -944,7 +944,7 @@ static void gdraw_BlurAxis(S32 axis, GDrawFunctions *g, GDrawBlurInfo *c, GDrawR // max coverage is 25 samples, or a filter width of 13. with 7 taps, we sample // 13 samples in one pass, max coverage is 13*13 samples or (13*13-1)/2 width, // which is ((2T-1)*(2T-1)-1)/2 or (4T^2 - 4T + 1 -1)/2 or 2T^2 - 2T or 2T*(T-1) - S32 w_mip = (S32) ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS)); + S32 w_mip = static_cast(ceil(linear_remap(w, MAX_TAPS+1, MAX_TAPS*MAX_TAPS, 2, MAX_TAPS))); S32 downsample = w_mip; F32 sample_spacing = texel; if (downsample < 2) downsample = 2; @@ -1090,7 +1090,7 @@ static void make_pool_aligned(void **start, S32 *num_bytes, U32 alignment) if (addr_aligned != addr_orig) { S32 diff = (S32) (addr_aligned - addr_orig); if (*num_bytes < diff) { - *start = NULL; + *start = nullptr; *num_bytes = 0; return; } else { @@ -1127,7 +1127,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) UINTa remaining = arena->end - arena->current; UINTa total_size = (ptr - arena->current) + size; if (remaining < total_size) // doesn't fit - return NULL; + return nullptr; arena->current = ptr + size; return ptr; @@ -1152,7 +1152,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // (i.e. block->next->prev == block->prev->next == block) // - All allocated blocks are also kept in a hash table, indexed by their // pointer (to allow free to locate the corresponding block_info quickly). -// There's a single-linked, NULL-terminated list of elements in each hash +// There's a single-linked, nullptr-terminated list of elements in each hash // bucket. // - The physical block list is ordered. It always contains all currently // active blocks and spans the whole managed memory range. There are no @@ -1161,7 +1161,7 @@ static void *gdraw_arena_alloc(GDrawArena *arena, U32 size, U32 align) // they are coalesced immediately. // - The maximum number of blocks that could ever be necessary is allocated // on initialization. All block_infos not currently in use are kept in a -// single-linked, NULL-terminated list of unused blocks. Every block is either +// single-linked, nullptr-terminated list of unused blocks. Every block is either // in the physical block list or the unused list, and the total number of // blocks is constant. // These invariants always hold before and after an allocation/free. @@ -1379,7 +1379,7 @@ static void gfxalloc_check2(gfx_allocator *alloc) static gfx_block_info *gfxalloc_pop_unused(gfx_allocator *alloc) { - GFXALLOC_ASSERT(alloc->unused_list != NULL); + GFXALLOC_ASSERT(alloc->unused_list != nullptr); GFXALLOC_ASSERT(alloc->unused_list->is_unused); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_unused);) @@ -1452,7 +1452,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma U32 i, max_blocks, size; if (!align || (align & (align - 1)) != 0) // align must be >0 and a power of 2 - return NULL; + return nullptr; // for <= max_allocs live allocs, there's <= 2*max_allocs+1 blocks. worst case: // [free][used][free] .... [free][used][free] @@ -1460,7 +1460,7 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma size = sizeof(gfx_allocator) + max_blocks * sizeof(gfx_block_info); a = (gfx_allocator *) IggyGDrawMalloc(size); if (!a) - return NULL; + return nullptr; memset(a, 0, size); @@ -1501,16 +1501,16 @@ static gfx_allocator *gfxalloc_create(void *mem, U32 mem_size, U32 align, U32 ma a->blocks[i].is_unused = 1; gfxalloc_check(a); - debug_complete_check(a, NULL, 0,0); + debug_complete_check(a, nullptr, 0,0); return a; } static void *gfxalloc_alloc(gfx_allocator *alloc, U32 size_in_bytes) { - gfx_block_info *cur, *best = NULL; + gfx_block_info *cur, *best = nullptr; U32 i, best_wasted = ~0u; U32 size = size_in_bytes; -debug_complete_check(alloc, NULL, 0,0); +debug_complete_check(alloc, nullptr, 0,0); gfxalloc_check(alloc); GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_blocks == alloc->num_alloc + alloc->num_free + alloc->num_unused);) GFXALLOC_IF_CHECK(GFXALLOC_ASSERT(alloc->num_free <= alloc->num_blocks+1);) @@ -1560,7 +1560,7 @@ gfxalloc_check(alloc); debug_check_overlap(alloc->cache, best->ptr, best->size); return best->ptr; } else - return NULL; // not enough space! + return nullptr; // not enough space! } static void gfxalloc_free(gfx_allocator *alloc, void *ptr) @@ -1730,7 +1730,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta // (unused for allocated blocks, we'll use it to store a back-pointer to the corresponding handle) for (b = alloc->blocks[0].next_phys; b != alloc->blocks; b=b->next_phys) if (!b->is_free) - b->prev = NULL; + b->prev = nullptr; // go through all handles and store a pointer to the handle in the corresponding memory block for (i=0; i < c->max_handles; i++) @@ -1743,7 +1743,7 @@ static void gdraw_DefragmentMain(GDrawHandleCache *c, U32 flags, GDrawStats *sta break; } - GFXALLOC_ASSERT(b != NULL); // didn't find this block anywhere! + GFXALLOC_ASSERT(b != nullptr); // didn't find this block anywhere! } // clear alloc hash table (we rebuild it during defrag) @@ -1905,7 +1905,7 @@ static rrbool gdraw_CanDefragment(GDrawHandleCache *c) static rrbool gdraw_MigrateResource(GDrawHandle *t, GDrawStats *stats) { GDrawHandleCache *c = t->cache; - void *ptr = NULL; + void *ptr = nullptr; assert(t->state == GDRAW_HANDLE_STATE_live || t->state == GDRAW_HANDLE_STATE_locked || t->state == GDRAW_HANDLE_STATE_pinned); // anything we migrate should be in the "other" (old) pool @@ -2295,7 +2295,7 @@ static void gdraw_bufring_init(gdraw_bufring * RADRESTRICT ring, void *ptr, U32 static void gdraw_bufring_shutdown(gdraw_bufring * RADRESTRICT ring) { - ring->cur = NULL; + ring->cur = nullptr; ring->seg_size = 0; } @@ -2305,7 +2305,7 @@ static void *gdraw_bufring_alloc(gdraw_bufring * RADRESTRICT ring, U32 size, U32 gdraw_bufring_seg *seg; if (size > ring->seg_size) - return NULL; // nope, won't fit + return nullptr; // nope, won't fit assert(align <= ring->align); @@ -2410,7 +2410,7 @@ static rrbool gdraw_res_free_lru(GDrawHandleCache *c, GDrawStats *stats) // was it referenced since end of previous frame (=in this frame)? // if some, we're thrashing; report it to the user, but only once per frame. if (c->prev_frame_end.value < r->fence.value && !c->is_thrashing) { - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Thrashing vertex memory" : "GDraw Thrashing texture memory"); c->is_thrashing = true; } @@ -2430,8 +2430,8 @@ static GDrawHandle *gdraw_res_alloc_outofmem(GDrawHandleCache *c, GDrawHandle *t { if (t) gdraw_HandleCacheAllocateFail(t); - IggyGDrawSendWarning(NULL, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); - return NULL; + IggyGDrawSendWarning(nullptr, c->is_vertex ? "GDraw Out of static vertex buffer %s" : "GDraw Out of texture %s", failed_type); + return nullptr; } #ifndef GDRAW_MANAGE_MEM @@ -2440,7 +2440,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt { GDrawHandle *t; if (size > c->total_bytes) - gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); else { // given how much data we're going to allocate, throw out // data until there's "room" (this basically lets us use @@ -2448,7 +2448,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // packing it and being exact) while (c->bytes_free < size) { if (!gdraw_res_free_lru(c, stats)) { - gdraw_res_alloc_outofmem(c, NULL, "memory"); + gdraw_res_alloc_outofmem(c, nullptr, "memory"); break; } } @@ -2463,8 +2463,8 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt // we'd trade off cost of regenerating) if (gdraw_res_free_lru(c, stats)) { t = gdraw_HandleCacheAllocateBegin(c); - if (t == NULL) { - gdraw_res_alloc_outofmem(c, NULL, "handles"); + if (t == nullptr) { + gdraw_res_alloc_outofmem(c, nullptr, "handles"); } } } @@ -2508,7 +2508,7 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) { GDRAW_FENCE_FLUSH(); // dead list is sorted by fence index - make sure all fence values are current. - r->owner = NULL; + r->owner = nullptr; gdraw_HandleCacheInsertDead(r); gdraw_res_reap(r->cache, stats); } @@ -2516,11 +2516,11 @@ static void gdraw_res_kill(GDrawHandle *r, GDrawStats *stats) static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawStats *stats) { GDrawHandle *t; - void *ptr = NULL; + void *ptr = nullptr; gdraw_res_reap(c, stats); // NB this also does GDRAW_FENCE_FLUSH(); if (size > c->total_bytes) - return gdraw_res_alloc_outofmem(c, NULL, "memory (single resource larger than entire pool)"); + return gdraw_res_alloc_outofmem(c, nullptr, "memory (single resource larger than entire pool)"); // now try to allocate a handle t = gdraw_HandleCacheAllocateBegin(c); @@ -2532,7 +2532,7 @@ static GDrawHandle *gdraw_res_alloc_begin(GDrawHandleCache *c, S32 size, GDrawSt gdraw_res_free_lru(c, stats); t = gdraw_HandleCacheAllocateBegin(c); if (!t) - return gdraw_res_alloc_outofmem(c, NULL, "handles"); + return gdraw_res_alloc_outofmem(c, nullptr, "handles"); } // try to allocate first diff --git a/Minecraft.Client/Windows64/Iggy/include/gdraw.h b/Minecraft.Client/Windows64/Iggy/include/gdraw.h index 404a2642b..7cc4ddd0e 100644 --- a/Minecraft.Client/Windows64/Iggy/include/gdraw.h +++ b/Minecraft.Client/Windows64/Iggy/include/gdraw.h @@ -356,13 +356,13 @@ IDOC typedef struct GDrawPrimitive IDOC typedef void RADLINK gdraw_draw_indexed_triangles(GDrawRenderState *r, GDrawPrimitive *prim, GDrawVertexBuffer *buf, GDrawStats *stats); /* Draws a collection of indexed triangles, ignoring special filters or blend modes. - If buf is NULL, then the pointers in 'prim' are machine pointers, and + If buf is nullptr, then the pointers in 'prim' are machine pointers, and you need to make a copy of the data (note currently all triangles implementing strokes (wide lines) go this path). - If buf is non-NULL, then use the appropriate vertex buffer, and the + If buf is non-nullptr, then use the appropriate vertex buffer, and the pointers in prim are actually offsets from the beginning of the - vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) NULL; + vertex buffer -- i.e. offset = (char*) prim->whatever - (char*) nullptr; (note there are separate spaces for vertices and indices; e.g. the first mesh in a given vertex buffer will normally have a 0 offset for the vertices and a 0 offset for the indices) @@ -455,7 +455,7 @@ IDOC typedef GDrawTexture * RADLINK gdraw_make_texture_end(GDraw_MakeTexture_Pro /* Ends specification of a new texture. $:info The same handle initially passed to $gdraw_make_texture_begin - $:return Handle for the newly created texture, or NULL if an error occured + $:return Handle for the newly created texture, or nullptr if an error occured */ IDOC typedef rrbool RADLINK gdraw_update_texture_begin(GDrawTexture *tex, void *unique_id, GDrawStats *stats); diff --git a/Minecraft.Client/Windows64/Iggy/include/iggyexpruntime.h b/Minecraft.Client/Windows64/Iggy/include/iggyexpruntime.h index 1f1a90a1c..a42ccbfff 100644 --- a/Minecraft.Client/Windows64/Iggy/include/iggyexpruntime.h +++ b/Minecraft.Client/Windows64/Iggy/include/iggyexpruntime.h @@ -25,8 +25,8 @@ IDOC RADEXPFUNC HIGGYEXP RADEXPLINK IggyExpCreate(char *ip_address, S32 port, vo $:storage A small block of storage that needed to store the $HIGGYEXP, must be at least $IGGYEXP_MIN_STORAGE $:storage_size_in_bytes The size of the block pointer to by storage -Returns a NULL HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer -can be contacted at the specified address/port. Otherwise returns a non-NULL $HIGGYEXP +Returns a nullptr HIGGYEXP if the IP address/hostname can't be resolved, or no Iggy Explorer +can be contacted at the specified address/port. Otherwise returns a non-nullptr $HIGGYEXP which you can pass to $IggyUseExplorer. */ IDOC RADEXPFUNC void RADEXPLINK IggyExpDestroy(HIGGYEXP p); diff --git a/Minecraft.Client/Windows64/KeyboardMouseInput.cpp b/Minecraft.Client/Windows64/KeyboardMouseInput.cpp index 3a98a0987..54191ebcb 100644 --- a/Minecraft.Client/Windows64/KeyboardMouseInput.cpp +++ b/Minecraft.Client/Windows64/KeyboardMouseInput.cpp @@ -288,7 +288,7 @@ void KeyboardMouseInput::SetMouseGrabbed(bool grabbed) else if (!grabbed && !m_cursorHiddenForUI && g_hWnd) { while (ShowCursor(TRUE) < 0) {} - ClipCursor(NULL); + ClipCursor(nullptr); } } @@ -317,7 +317,7 @@ void KeyboardMouseInput::SetCursorHiddenForUI(bool hidden) else if (!hidden && !m_mouseGrabbed && g_hWnd) { while (ShowCursor(TRUE) < 0) {} - ClipCursor(NULL); + ClipCursor(nullptr); } } @@ -347,13 +347,13 @@ void KeyboardMouseInput::SetWindowFocused(bool focused) else { while (ShowCursor(TRUE) < 0) {} - ClipCursor(NULL); + ClipCursor(nullptr); } } else { while (ShowCursor(TRUE) < 0) {} - ClipCursor(NULL); + ClipCursor(nullptr); } } diff --git a/Minecraft.Client/Windows64/KeyboardMouseInput.h b/Minecraft.Client/Windows64/KeyboardMouseInput.h index 0f14dfa1f..2079a72a1 100644 --- a/Minecraft.Client/Windows64/KeyboardMouseInput.h +++ b/Minecraft.Client/Windows64/KeyboardMouseInput.h @@ -25,12 +25,20 @@ public: static const int KEY_DROP = 'Q'; static const int KEY_CRAFTING = 'C'; static const int KEY_CRAFTING_ALT = 'R'; + static const int KEY_CHAT = 'T'; static const int KEY_CONFIRM = VK_RETURN; static const int KEY_CANCEL = VK_ESCAPE; static const int KEY_PAUSE = VK_ESCAPE; - static const int KEY_THIRD_PERSON = VK_F5; + static const int KEY_TOGGLE_HUD = VK_F1; static const int KEY_DEBUG_INFO = VK_F3; static const int KEY_DEBUG_MENU = VK_F4; + static const int KEY_THIRD_PERSON = VK_F5; + static const int KEY_DEBUG_CONSOLE = VK_F6; + static const int KEY_HOST_SETTINGS = VK_F8; + static const int KEY_FULLSCREEN = VK_F11; + + // todo: implement and shi + static const int KEY_SCREENSHOT = VK_F2; void Init(); void Tick(); diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp index c76bc2fe8..981ab3ab1 100644 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp @@ -8,16 +8,25 @@ #include "WinsockNetLayer.h" #include "..\..\Common\Network\PlatformNetworkManagerStub.h" #include "..\..\..\Minecraft.World\Socket.h" +#if defined(MINECRAFT_SERVER_BUILD) +#include "..\..\..\Minecraft.Server\Access\Access.h" +#include "..\..\..\Minecraft.Server\ServerLogManager.h" +#endif #include "..\..\..\Minecraft.World\DisconnectPacket.h" #include "..\..\Minecraft.h" #include "..\4JLibs\inc\4J_Profile.h" +#include + static bool RecvExact(SOCKET sock, BYTE* buf, int len); +#if defined(MINECRAFT_SERVER_BUILD) +static bool TryGetNumericRemoteIp(const sockaddr_in &remoteAddress, std::string *outIp); +#endif SOCKET WinsockNetLayer::s_listenSocket = INVALID_SOCKET; SOCKET WinsockNetLayer::s_hostConnectionSocket = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_acceptThread = NULL; -HANDLE WinsockNetLayer::s_clientRecvThread = NULL; +HANDLE WinsockNetLayer::s_acceptThread = nullptr; +HANDLE WinsockNetLayer::s_clientRecvThread = nullptr; bool WinsockNetLayer::s_isHost = false; bool WinsockNetLayer::s_connected = false; @@ -26,7 +35,7 @@ bool WinsockNetLayer::s_initialized = false; BYTE WinsockNetLayer::s_localSmallId = 0; BYTE WinsockNetLayer::s_hostSmallId = 0; -unsigned int WinsockNetLayer::s_nextSmallId = 1; +unsigned int WinsockNetLayer::s_nextSmallId = XUSER_MAX_COUNT; CRITICAL_SECTION WinsockNetLayer::s_sendLock; CRITICAL_SECTION WinsockNetLayer::s_connectionsLock; @@ -34,14 +43,14 @@ CRITICAL_SECTION WinsockNetLayer::s_connectionsLock; std::vector WinsockNetLayer::s_connections; SOCKET WinsockNetLayer::s_advertiseSock = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_advertiseThread = NULL; +HANDLE WinsockNetLayer::s_advertiseThread = nullptr; volatile bool WinsockNetLayer::s_advertising = false; Win64LANBroadcast WinsockNetLayer::s_advertiseData = {}; CRITICAL_SECTION WinsockNetLayer::s_advertiseLock; int WinsockNetLayer::s_hostGamePort = WIN64_NET_DEFAULT_PORT; SOCKET WinsockNetLayer::s_discoverySock = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_discoveryThread = NULL; +HANDLE WinsockNetLayer::s_discoveryThread = nullptr; volatile bool WinsockNetLayer::s_discovering = false; CRITICAL_SECTION WinsockNetLayer::s_discoveryLock; std::vector WinsockNetLayer::s_discoveredSessions; @@ -54,6 +63,10 @@ std::vector WinsockNetLayer::s_freeSmallIds; SOCKET WinsockNetLayer::s_smallIdToSocket[256]; CRITICAL_SECTION WinsockNetLayer::s_smallIdToSocketLock; +SOCKET WinsockNetLayer::s_splitScreenSocket[XUSER_MAX_COUNT] = { INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET }; +BYTE WinsockNetLayer::s_splitScreenSmallId[XUSER_MAX_COUNT] = { 0xFF, 0xFF, 0xFF, 0xFF }; +HANDLE WinsockNetLayer::s_splitScreenRecvThread[XUSER_MAX_COUNT] = {nullptr, nullptr, nullptr, nullptr}; + bool g_Win64MultiplayerHost = false; bool g_Win64MultiplayerJoin = false; int g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT; @@ -61,6 +74,7 @@ char g_Win64MultiplayerIP[256] = "127.0.0.1"; bool g_Win64DedicatedServer = false; int g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT; char g_Win64DedicatedServerBindIP[256] = ""; +bool g_Win64DedicatedServerLanAdvertise = true; bool WinsockNetLayer::Initialize() { @@ -86,7 +100,11 @@ bool WinsockNetLayer::Initialize() s_initialized = true; - StartDiscovery(); + // Dedicated Server does not use LAN session discovery and therefore does not initiate discovery. + if (!g_Win64DedicatedServer) + { + StartDiscovery(); + } return true; } @@ -111,6 +129,15 @@ void WinsockNetLayer::Shutdown() s_hostConnectionSocket = INVALID_SOCKET; } + // Stop accept loop first so no new RecvThread can be created while shutting down. + if (s_acceptThread != nullptr) + { + WaitForSingleObject(s_acceptThread, 2000); + CloseHandle(s_acceptThread); + s_acceptThread = nullptr; + } + + std::vector recvThreads; EnterCriticalSection(&s_connectionsLock); for (size_t i = 0; i < s_connections.size(); i++) { @@ -118,35 +145,66 @@ void WinsockNetLayer::Shutdown() if (s_connections[i].tcpSocket != INVALID_SOCKET) { closesocket(s_connections[i].tcpSocket); + s_connections[i].tcpSocket = INVALID_SOCKET; + } + if (s_connections[i].recvThread != nullptr) + { + recvThreads.push_back(s_connections[i].recvThread); + s_connections[i].recvThread = nullptr; } } + LeaveCriticalSection(&s_connectionsLock); + + // Wait for all host-side receive threads to exit before destroying state. + for (size_t i = 0; i < recvThreads.size(); i++) + { + WaitForSingleObject(recvThreads[i], 2000); + CloseHandle(recvThreads[i]); + } + + EnterCriticalSection(&s_connectionsLock); s_connections.clear(); LeaveCriticalSection(&s_connectionsLock); - if (s_acceptThread != NULL) - { - WaitForSingleObject(s_acceptThread, 2000); - CloseHandle(s_acceptThread); - s_acceptThread = NULL; - } - - if (s_clientRecvThread != NULL) + if (s_clientRecvThread != nullptr) { WaitForSingleObject(s_clientRecvThread, 2000); CloseHandle(s_clientRecvThread); - s_clientRecvThread = NULL; + s_clientRecvThread = nullptr; + } + + for (int i = 0; i < XUSER_MAX_COUNT; i++) + { + if (s_splitScreenSocket[i] != INVALID_SOCKET) + { + closesocket(s_splitScreenSocket[i]); + s_splitScreenSocket[i] = INVALID_SOCKET; + } + if (s_splitScreenRecvThread[i] != nullptr) + { + WaitForSingleObject(s_splitScreenRecvThread[i], 2000); + CloseHandle(s_splitScreenRecvThread[i]); + s_splitScreenRecvThread[i] = nullptr; + } + s_splitScreenSmallId[i] = 0xFF; } if (s_initialized) { + EnterCriticalSection(&s_disconnectLock); + s_disconnectedSmallIds.clear(); + LeaveCriticalSection(&s_disconnectLock); + + EnterCriticalSection(&s_freeSmallIdLock); + s_freeSmallIds.clear(); + LeaveCriticalSection(&s_freeSmallIdLock); + DeleteCriticalSection(&s_sendLock); DeleteCriticalSection(&s_connectionsLock); DeleteCriticalSection(&s_advertiseLock); DeleteCriticalSection(&s_discoveryLock); DeleteCriticalSection(&s_disconnectLock); - s_disconnectedSmallIds.clear(); DeleteCriticalSection(&s_freeSmallIdLock); - s_freeSmallIds.clear(); DeleteCriticalSection(&s_smallIdToSocketLock); WSACleanup(); s_initialized = false; @@ -160,7 +218,7 @@ bool WinsockNetLayer::HostGame(int port, const char* bindIp) s_isHost = true; s_localSmallId = 0; s_hostSmallId = 0; - s_nextSmallId = 1; + s_nextSmallId = XUSER_MAX_COUNT; s_hostGamePort = port; EnterCriticalSection(&s_freeSmallIdLock); @@ -172,22 +230,22 @@ bool WinsockNetLayer::HostGame(int port, const char* bindIp) LeaveCriticalSection(&s_smallIdToSocketLock); struct addrinfo hints = {}; - struct addrinfo* result = NULL; + struct addrinfo* result = nullptr; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; - hints.ai_flags = (bindIp == NULL || bindIp[0] == 0) ? AI_PASSIVE : 0; + hints.ai_flags = (bindIp == nullptr || bindIp[0] == 0) ? AI_PASSIVE : 0; char portStr[16]; sprintf_s(portStr, "%d", port); - const char* resolvedBindIp = (bindIp != NULL && bindIp[0] != 0) ? bindIp : NULL; + const char* resolvedBindIp = (bindIp != nullptr && bindIp[0] != 0) ? bindIp : nullptr; int iResult = getaddrinfo(resolvedBindIp, portStr, &hints, &result); if (iResult != 0) { app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n", - resolvedBindIp != NULL ? resolvedBindIp : "*", + resolvedBindIp != nullptr ? resolvedBindIp : "*", port, iResult); return false; @@ -204,7 +262,7 @@ bool WinsockNetLayer::HostGame(int port, const char* bindIp) int opt = 1; setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); - iResult = ::bind(s_listenSocket, result->ai_addr, (int)result->ai_addrlen); + iResult = ::bind(s_listenSocket, result->ai_addr, static_cast(result->ai_addrlen)); freeaddrinfo(result); if (iResult == SOCKET_ERROR) { @@ -226,10 +284,10 @@ bool WinsockNetLayer::HostGame(int port, const char* bindIp) s_active = true; s_connected = true; - s_acceptThread = CreateThread(NULL, 0, AcceptThreadProc, NULL, 0, NULL); + s_acceptThread = CreateThread(nullptr, 0, AcceptThreadProc, nullptr, 0, nullptr); app.DebugPrintf("Win64 LAN: Hosting on %s:%d\n", - resolvedBindIp != NULL ? resolvedBindIp : "*", + resolvedBindIp != nullptr ? resolvedBindIp : "*", port); return true; } @@ -249,8 +307,19 @@ bool WinsockNetLayer::JoinGame(const char* ip, int port) s_hostConnectionSocket = INVALID_SOCKET; } + // Wait for old client recv thread to fully exit before starting a new connection. + // Without this, the old thread can read from the new socket (s_hostConnectionSocket + // is a global) and steal bytes from the new connection's TCP stream, causing + // packet stream misalignment on reconnect. + if (s_clientRecvThread != nullptr) + { + WaitForSingleObject(s_clientRecvThread, 5000); + CloseHandle(s_clientRecvThread); + s_clientRecvThread = nullptr; + } + struct addrinfo hints = {}; - struct addrinfo* result = NULL; + struct addrinfo* result = nullptr; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; @@ -282,7 +351,7 @@ bool WinsockNetLayer::JoinGame(const char* ip, int port) int noDelay = 1; setsockopt(s_hostConnectionSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); - iResult = connect(s_hostConnectionSocket, result->ai_addr, (int)result->ai_addrlen); + iResult = connect(s_hostConnectionSocket, result->ai_addr, static_cast(result->ai_addrlen)); if (iResult == SOCKET_ERROR) { int err = WSAGetLastError(); @@ -337,27 +406,39 @@ bool WinsockNetLayer::JoinGame(const char* ip, int port) } s_localSmallId = assignedSmallId; + // Save the host IP and port so JoinSplitScreen can connect to the same host + // regardless of how the connection was initiated (UI vs command line). + strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), ip, _TRUNCATE); + g_Win64MultiplayerPort = port; + app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", ip, port, s_localSmallId); s_active = true; s_connected = true; - s_clientRecvThread = CreateThread(NULL, 0, ClientRecvThreadProc, NULL, 0, NULL); + s_clientRecvThread = CreateThread(nullptr, 0, ClientRecvThreadProc, nullptr, 0, nullptr); return true; } bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize) { - if (sock == INVALID_SOCKET || dataSize <= 0) return false; + if (sock == INVALID_SOCKET || dataSize <= 0 || dataSize > WIN64_NET_MAX_PACKET_SIZE) return false; + // TODO: s_sendLock is a single global lock for ALL sockets. If one client's + // send() blocks (TCP window full, slow WiFi), every other write thread stalls + // waiting for this lock — no data flows to any player until the slow send + // completes. This scales badly with player count (8+ players = noticeable). + // Fix: replace with per-socket locks indexed by smallId (s_perSocketSendLock[256]). + // The lock only needs to prevent interleaving of header+payload on the SAME socket; + // sends to different sockets are independent and should never block each other. EnterCriticalSection(&s_sendLock); BYTE header[4]; - header[0] = (BYTE)((dataSize >> 24) & 0xFF); - header[1] = (BYTE)((dataSize >> 16) & 0xFF); - header[2] = (BYTE)((dataSize >> 8) & 0xFF); - header[3] = (BYTE)(dataSize & 0xFF); + header[0] = static_cast((dataSize >> 24) & 0xFF); + header[1] = static_cast((dataSize >> 16) & 0xFF); + header[2] = static_cast((dataSize >> 8) & 0xFF); + header[3] = static_cast(dataSize & 0xFF); int totalSent = 0; int toSend = 4; @@ -375,7 +456,7 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize) totalSent = 0; while (totalSent < dataSize) { - int sent = send(sock, (const char*)data + totalSent, dataSize - totalSent, 0); + int sent = send(sock, static_cast(data) + totalSent, dataSize - totalSent, 0); if (sent == SOCKET_ERROR || sent == 0) { LeaveCriticalSection(&s_sendLock); @@ -445,24 +526,54 @@ static bool RecvExact(SOCKET sock, BYTE* buf, int len) return true; } +#if defined(MINECRAFT_SERVER_BUILD) +static bool TryGetNumericRemoteIp(const sockaddr_in &remoteAddress, std::string *outIp) +{ + if (outIp == nullptr) + { + return false; + } + + outIp->clear(); + char ipBuffer[64] = {}; + const char *ip = inet_ntop(AF_INET, (void *)&remoteAddress.sin_addr, ipBuffer, sizeof(ipBuffer)); + if (ip == nullptr || ip[0] == 0) + { + return false; + } + + *outIp = ip; + return true; +} +#endif + void WinsockNetLayer::HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char* data, unsigned int dataSize) { INetworkPlayer* pPlayerFrom = g_NetworkManager.GetPlayerBySmallId(fromSmallId); INetworkPlayer* pPlayerTo = g_NetworkManager.GetPlayerBySmallId(toSmallId); - if (pPlayerFrom == NULL || pPlayerTo == NULL) return; + if (pPlayerFrom == nullptr || pPlayerTo == nullptr) + { + app.DebugPrintf("NET RECV: DROPPED %u bytes from=%d to=%d (player NULL: from=%p to=%p)\n", + dataSize, fromSmallId, toSmallId, pPlayerFrom, pPlayerTo); + return; + } if (s_isHost) { ::Socket* pSocket = pPlayerFrom->GetSocket(); - if (pSocket != NULL) + if (pSocket != nullptr) pSocket->pushDataToQueue(data, dataSize, false); + else + app.DebugPrintf("NET RECV: DROPPED %u bytes, host pSocket NULL for from=%d\n", dataSize, fromSmallId); } else { ::Socket* pSocket = pPlayerTo->GetSocket(); - if (pSocket != NULL) + if (pSocket != nullptr) pSocket->pushDataToQueue(data, dataSize, true); + else + app.DebugPrintf("NET RECV: DROPPED %u bytes, client pSocket NULL for to=%d\n", dataSize, toSmallId); } } @@ -470,7 +581,10 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) { while (s_active) { - SOCKET clientSocket = accept(s_listenSocket, NULL, NULL); + sockaddr_in remoteAddress; + ZeroMemory(&remoteAddress, sizeof(remoteAddress)); + int remoteAddressLength = sizeof(remoteAddress); + SOCKET clientSocket = accept(s_listenSocket, (sockaddr*)&remoteAddress, &remoteAddressLength); if (clientSocket == INVALID_SOCKET) { if (s_active) @@ -481,18 +595,53 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) int noDelay = 1; setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); +#if defined(MINECRAFT_SERVER_BUILD) + std::string remoteIp; + const bool hasRemoteIp = TryGetNumericRemoteIp(remoteAddress, &remoteIp); + const char *remoteIpForLog = hasRemoteIp ? remoteIp.c_str() : "unknown"; + if (g_Win64DedicatedServer) + { + ServerRuntime::ServerLogManager::OnIncomingTcpConnection(remoteIpForLog); + if (hasRemoteIp && ServerRuntime::Access::IsIpBanned(remoteIp)) + { + ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_BannedIp); + SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_Banned); + closesocket(clientSocket); + continue; + } + } +#endif + extern QNET_STATE _iQNetStubState; if (_iQNetStubState != QNET_STATE_GAME_PLAY) { - app.DebugPrintf("Win64 LAN: Rejecting connection, game not ready\n"); +#if defined(MINECRAFT_SERVER_BUILD) + if (g_Win64DedicatedServer) + { + ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_GameNotReady); + } + else +#endif + { + app.DebugPrintf("Win64 LAN: Rejecting connection, game not ready\n"); + } closesocket(clientSocket); continue; } extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - if (g_pPlatformNetworkManager != NULL && !g_pPlatformNetworkManager->CanAcceptMoreConnections()) + if (g_pPlatformNetworkManager != nullptr && !g_pPlatformNetworkManager->CanAcceptMoreConnections()) { - app.DebugPrintf("Win64 LAN: Rejecting connection, server at max players\n"); +#if defined(MINECRAFT_SERVER_BUILD) + if (g_Win64DedicatedServer) + { + ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_ServerFull); + } + else +#endif + { + app.DebugPrintf("Win64 LAN: Rejecting connection, server at max players\n"); + } SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_ServerFull); closesocket(clientSocket); continue; @@ -512,7 +661,16 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) else { LeaveCriticalSection(&s_freeSmallIdLock); - app.DebugPrintf("Win64 LAN: Server full, rejecting connection\n"); +#if defined(MINECRAFT_SERVER_BUILD) + if (g_Win64DedicatedServer) + { + ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_ServerFull); + } + else +#endif + { + app.DebugPrintf("Win64 LAN: Server full, rejecting connection\n"); + } SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_ServerFull); closesocket(clientSocket); continue; @@ -525,6 +683,7 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) { app.DebugPrintf("Failed to send small ID to client\n"); closesocket(clientSocket); + PushFreeSmallId(assignedSmallId); continue; } @@ -532,14 +691,23 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) conn.tcpSocket = clientSocket; conn.smallId = assignedSmallId; conn.active = true; - conn.recvThread = NULL; + conn.recvThread = nullptr; EnterCriticalSection(&s_connectionsLock); s_connections.push_back(conn); - int connIdx = (int)s_connections.size() - 1; + int connIdx = static_cast(s_connections.size()) - 1; LeaveCriticalSection(&s_connectionsLock); - app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId); +#if defined(MINECRAFT_SERVER_BUILD) + if (g_Win64DedicatedServer) + { + ServerRuntime::ServerLogManager::OnAcceptedTcpConnection(assignedSmallId, remoteIpForLog); + } + else +#endif + { + app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId); + } EnterCriticalSection(&s_smallIdToSocketLock); s_smallIdToSocket[assignedSmallId] = clientSocket; @@ -555,10 +723,10 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) DWORD* threadParam = new DWORD; *threadParam = connIdx; - HANDLE hThread = CreateThread(NULL, 0, RecvThreadProc, threadParam, 0, NULL); + HANDLE hThread = CreateThread(nullptr, 0, RecvThreadProc, threadParam, 0, nullptr); EnterCriticalSection(&s_connectionsLock); - if (connIdx < (int)s_connections.size()) + if (connIdx < static_cast(s_connections.size())) s_connections[connIdx].recvThread = hThread; LeaveCriticalSection(&s_connectionsLock); } @@ -567,11 +735,11 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param) { - DWORD connIdx = *(DWORD*)param; - delete (DWORD*)param; + DWORD connIdx = *static_cast(param); + delete static_cast(param); EnterCriticalSection(&s_connectionsLock); - if (connIdx >= (DWORD)s_connections.size()) + if (connIdx >= static_cast(s_connections.size())) { LeaveCriticalSection(&s_connectionsLock); return 0; @@ -593,10 +761,10 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param) } int packetSize = - ((uint32_t)header[0] << 24) | - ((uint32_t)header[1] << 16) | - ((uint32_t)header[2] << 8) | - ((uint32_t)header[3]); + (static_cast(header[0]) << 24) | + (static_cast(header[1]) << 16) | + (static_cast(header[2]) << 8) | + static_cast(header[3]); if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE) { @@ -607,7 +775,7 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param) break; } - if ((int)recvBuf.size() < packetSize) + if (static_cast(recvBuf.size()) < packetSize) { recvBuf.resize(packetSize); app.DebugPrintf("Win64 LAN: Resized host recv buffer to %d bytes for client smallId=%d\n", packetSize, clientSmallId); @@ -661,8 +829,22 @@ bool WinsockNetLayer::PopDisconnectedSmallId(BYTE* outSmallId) void WinsockNetLayer::PushFreeSmallId(BYTE smallId) { + // SmallIds 0..(XUSER_MAX_COUNT-1) are permanently reserved for the host's + // local pads and must never be recycled to remote clients. + if (smallId < (BYTE)XUSER_MAX_COUNT) + return; + EnterCriticalSection(&s_freeSmallIdLock); - s_freeSmallIds.push_back(smallId); + // Guard against double-recycle: the reconnect path (queueSmallIdForRecycle) and + // the DoWork disconnect path can both push the same smallId. If we allow duplicates, + // AcceptThread will hand out the same smallId to two different connections. + bool alreadyFree = false; + for (size_t i = 0; i < s_freeSmallIds.size(); i++) + { + if (s_freeSmallIds[i] == smallId) { alreadyFree = true; break; } + } + if (!alreadyFree) + s_freeSmallIds.push_back(smallId); LeaveCriticalSection(&s_freeSmallIdLock); } @@ -682,6 +864,171 @@ void WinsockNetLayer::CloseConnectionBySmallId(BYTE smallId) LeaveCriticalSection(&s_connectionsLock); } +BYTE WinsockNetLayer::GetSplitScreenSmallId(int padIndex) +{ + if (padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) return 0xFF; + return s_splitScreenSmallId[padIndex]; +} + +SOCKET WinsockNetLayer::GetLocalSocket(BYTE senderSmallId) +{ + if (senderSmallId == s_localSmallId) + return s_hostConnectionSocket; + for (int i = 1; i < XUSER_MAX_COUNT; i++) + { + if (s_splitScreenSmallId[i] == senderSmallId && s_splitScreenSocket[i] != INVALID_SOCKET) + return s_splitScreenSocket[i]; + } + return INVALID_SOCKET; +} + +bool WinsockNetLayer::JoinSplitScreen(int padIndex, BYTE* outSmallId) +{ + if (!s_active || s_isHost || padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) + return false; + + if (s_splitScreenSocket[padIndex] != INVALID_SOCKET) + { + return false; + } + + struct addrinfo hints = {}; + struct addrinfo* result = nullptr; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + char portStr[16]; + sprintf_s(portStr, "%d", g_Win64MultiplayerPort); + if (getaddrinfo(g_Win64MultiplayerIP, portStr, &hints, &result) != 0 || result == nullptr) + { + app.DebugPrintf("Win64 LAN: Split-screen getaddrinfo failed for %s:%d\n", g_Win64MultiplayerIP, g_Win64MultiplayerPort); + return false; + } + + SOCKET sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol); + if (sock == INVALID_SOCKET) + { + freeaddrinfo(result); + return false; + } + + int noDelay = 1; + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); + + if (connect(sock, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) + { + app.DebugPrintf("Win64 LAN: Split-screen connect() failed: %d\n", WSAGetLastError()); + closesocket(sock); + freeaddrinfo(result); + return false; + } + freeaddrinfo(result); + + BYTE assignBuf[1]; + if (!RecvExact(sock, assignBuf, 1)) + { + app.DebugPrintf("Win64 LAN: Split-screen failed to receive smallId\n"); + closesocket(sock); + return false; + } + + if (assignBuf[0] == WIN64_SMALLID_REJECT) + { + BYTE rejectBuf[5]; + RecvExact(sock, rejectBuf, 5); + app.DebugPrintf("Win64 LAN: Split-screen connection rejected\n"); + closesocket(sock); + return false; + } + + BYTE assignedSmallId = assignBuf[0]; + s_splitScreenSocket[padIndex] = sock; + s_splitScreenSmallId[padIndex] = assignedSmallId; + *outSmallId = assignedSmallId; + + app.DebugPrintf("Win64 LAN: Split-screen pad %d connected, assigned smallId=%d\n", padIndex, assignedSmallId); + + int* threadParam = new int; + *threadParam = padIndex; + s_splitScreenRecvThread[padIndex] = CreateThread(nullptr, 0, SplitScreenRecvThreadProc, threadParam, 0, nullptr); + if (s_splitScreenRecvThread[padIndex] == nullptr) + { + delete threadParam; + closesocket(sock); + s_splitScreenSocket[padIndex] = INVALID_SOCKET; + s_splitScreenSmallId[padIndex] = 0xFF; + app.DebugPrintf("Win64 LAN: CreateThread failed for split-screen pad %d\n", padIndex); + return false; + } + + return true; +} + +void WinsockNetLayer::CloseSplitScreenConnection(int padIndex) +{ + if (padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) return; + + if (s_splitScreenSocket[padIndex] != INVALID_SOCKET) + { + closesocket(s_splitScreenSocket[padIndex]); + s_splitScreenSocket[padIndex] = INVALID_SOCKET; + } + s_splitScreenSmallId[padIndex] = 0xFF; + if (s_splitScreenRecvThread[padIndex] != nullptr) + { + WaitForSingleObject(s_splitScreenRecvThread[padIndex], 2000); + CloseHandle(s_splitScreenRecvThread[padIndex]); + s_splitScreenRecvThread[padIndex] = nullptr; + } +} + +DWORD WINAPI WinsockNetLayer::SplitScreenRecvThreadProc(LPVOID param) +{ + int padIndex = *(int*)param; + delete (int*)param; + + SOCKET sock = s_splitScreenSocket[padIndex]; + BYTE localSmallId = s_splitScreenSmallId[padIndex]; + std::vector recvBuf; + recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE); + + while (s_active && s_splitScreenSocket[padIndex] != INVALID_SOCKET) + { + BYTE header[4]; + if (!RecvExact(sock, header, 4)) + { + app.DebugPrintf("Win64 LAN: Split-screen pad %d disconnected from host\n", padIndex); + break; + } + + int packetSize = ((uint32_t)header[0] << 24) | ((uint32_t)header[1] << 16) | + ((uint32_t)header[2] << 8) | ((uint32_t)header[3]); + if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE) + { + app.DebugPrintf("Win64 LAN: Split-screen pad %d invalid packet size %d\n", padIndex, packetSize); + break; + } + + if ((int)recvBuf.size() < packetSize) + recvBuf.resize(packetSize); + + if (!RecvExact(sock, &recvBuf[0], packetSize)) + { + app.DebugPrintf("Win64 LAN: Split-screen pad %d disconnected from host (body)\n", padIndex); + break; + } + + HandleDataReceived(s_hostSmallId, localSmallId, &recvBuf[0], packetSize); + } + + EnterCriticalSection(&s_disconnectLock); + s_disconnectedSmallIds.push_back(localSmallId); + LeaveCriticalSection(&s_disconnectLock); + + return 0; +} + DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param) { std::vector recvBuf; @@ -706,7 +1053,7 @@ DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param) break; } - if ((int)recvBuf.size() < packetSize) + if (static_cast(recvBuf.size()) < packetSize) { recvBuf.resize(packetSize); app.DebugPrintf("Win64 LAN: Resized client recv buffer to %d bytes\n", packetSize); @@ -734,7 +1081,7 @@ bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t* hostName, un memset(&s_advertiseData, 0, sizeof(s_advertiseData)); s_advertiseData.magic = WIN64_LAN_BROADCAST_MAGIC; s_advertiseData.netVersion = netVer; - s_advertiseData.gamePort = (WORD)gamePort; + s_advertiseData.gamePort = static_cast(gamePort); wcsncpy_s(s_advertiseData.hostName, 32, hostName, _TRUNCATE); s_advertiseData.playerCount = 1; s_advertiseData.maxPlayers = MINECRAFT_NET_MAX_PLAYERS; @@ -756,7 +1103,7 @@ bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t* hostName, un setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); s_advertising = true; - s_advertiseThread = CreateThread(NULL, 0, AdvertiseThreadProc, NULL, 0, NULL); + s_advertiseThread = CreateThread(nullptr, 0, AdvertiseThreadProc, nullptr, 0, nullptr); app.DebugPrintf("Win64 LAN: Started advertising on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); return true; @@ -772,11 +1119,11 @@ void WinsockNetLayer::StopAdvertising() s_advertiseSock = INVALID_SOCKET; } - if (s_advertiseThread != NULL) + if (s_advertiseThread != nullptr) { WaitForSingleObject(s_advertiseThread, 2000); CloseHandle(s_advertiseThread); - s_advertiseThread = NULL; + s_advertiseThread = nullptr; } } @@ -862,7 +1209,7 @@ bool WinsockNetLayer::StartDiscovery() setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); s_discovering = true; - s_discoveryThread = CreateThread(NULL, 0, DiscoveryThreadProc, NULL, 0, NULL); + s_discoveryThread = CreateThread(nullptr, 0, DiscoveryThreadProc, nullptr, 0, nullptr); app.DebugPrintf("Win64 LAN: Listening for LAN games on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); return true; @@ -878,11 +1225,11 @@ void WinsockNetLayer::StopDiscovery() s_discoverySock = INVALID_SOCKET; } - if (s_discoveryThread != NULL) + if (s_discoveryThread != nullptr) { WaitForSingleObject(s_discoveryThread, 2000); CloseHandle(s_discoveryThread); - s_discoveryThread = NULL; + s_discoveryThread = nullptr; } EnterCriticalSection(&s_discoveryLock); @@ -916,7 +1263,7 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param) continue; } - if (recvLen < (int)sizeof(Win64LANBroadcast)) + if (recvLen < static_cast(sizeof(Win64LANBroadcast))) continue; Win64LANBroadcast* broadcast = (Win64LANBroadcast*)recvBuf; @@ -934,7 +1281,7 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param) for (size_t i = 0; i < s_discoveredSessions.size(); i++) { if (strcmp(s_discoveredSessions[i].hostIP, senderIP) == 0 && - s_discoveredSessions[i].hostPort == (int)broadcast->gamePort) + s_discoveredSessions[i].hostPort == static_cast(broadcast->gamePort)) { s_discoveredSessions[i].netVersion = broadcast->netVersion; wcsncpy_s(s_discoveredSessions[i].hostName, 32, broadcast->hostName, _TRUNCATE); @@ -955,7 +1302,7 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param) Win64LANSession session; memset(&session, 0, sizeof(session)); strncpy_s(session.hostIP, sizeof(session.hostIP), senderIP, _TRUNCATE); - session.hostPort = (int)broadcast->gamePort; + session.hostPort = static_cast(broadcast->gamePort); session.netVersion = broadcast->netVersion; wcsncpy_s(session.hostName, 32, broadcast->hostName, _TRUNCATE); session.playerCount = broadcast->playerCount; diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h index f30240d32..afccbd66e 100644 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h @@ -66,12 +66,18 @@ public: static bool Initialize(); static void Shutdown(); - static bool HostGame(int port, const char* bindIp = NULL); + static bool HostGame(int port, const char* bindIp = nullptr); static bool JoinGame(const char* ip, int port); static bool SendToSmallId(BYTE targetSmallId, const void* data, int dataSize); static bool SendOnSocket(SOCKET sock, const void* data, int dataSize); + // Non-host split-screen: additional TCP connections to host, one per pad + static bool JoinSplitScreen(int padIndex, BYTE* outSmallId); + static void CloseSplitScreenConnection(int padIndex); + static SOCKET GetLocalSocket(BYTE senderSmallId); + static BYTE GetSplitScreenSmallId(int padIndex); + static bool IsHosting() { return s_isHost; } static bool IsConnected() { return s_connected; } static bool IsActive() { return s_active; } @@ -103,6 +109,7 @@ private: static DWORD WINAPI AcceptThreadProc(LPVOID param); static DWORD WINAPI RecvThreadProc(LPVOID param); static DWORD WINAPI ClientRecvThreadProc(LPVOID param); + static DWORD WINAPI SplitScreenRecvThreadProc(LPVOID param); static DWORD WINAPI AdvertiseThreadProc(LPVOID param); static DWORD WINAPI DiscoveryThreadProc(LPVOID param); @@ -147,6 +154,11 @@ private: static SOCKET s_smallIdToSocket[256]; static CRITICAL_SECTION s_smallIdToSocketLock; + // Per-pad split-screen TCP connections (client-side, non-host only) + static SOCKET s_splitScreenSocket[XUSER_MAX_COUNT]; + static BYTE s_splitScreenSmallId[XUSER_MAX_COUNT]; + static HANDLE s_splitScreenRecvThread[XUSER_MAX_COUNT]; + public: static void ClearSocketForSmallId(BYTE smallId); }; @@ -158,5 +170,6 @@ extern char g_Win64MultiplayerIP[256]; extern bool g_Win64DedicatedServer; extern int g_Win64DedicatedServerPort; extern char g_Win64DedicatedServerBindIP[256]; +extern bool g_Win64DedicatedServerLanAdvertise; #endif diff --git a/Minecraft.Client/Windows64/PostProcesser.cpp b/Minecraft.Client/Windows64/PostProcesser.cpp index 4c55d3d98..aabb1f679 100644 --- a/Minecraft.Client/Windows64/PostProcesser.cpp +++ b/Minecraft.Client/Windows64/PostProcesser.cpp @@ -21,13 +21,17 @@ const char* PostProcesser::g_gammaPSCode = "cbuffer GammaCB : register(b0)\n" "{\n" " float gamma;\n" - " float3 pad;\n" + " float _pad;\n" + " float2 uvOffset;\n" + " float2 uvScale;\n" + " float2 _pad2;\n" "};\n" "Texture2D sceneTex : register(t0);\n" "SamplerState sceneSampler : register(s0);\n" "float4 main(float4 pos : SV_Position, float2 uv : TEXCOORD0) : SV_Target\n" "{\n" - " float4 color = sceneTex.Sample(sceneSampler, uv);\n" + " float2 texUV = uvOffset + uv * uvScale;\n" + " float4 color = sceneTex.Sample(sceneSampler, texUV);\n" "\n" " color.rgb = max(color.rgb, 0.0);\n" "\n" @@ -158,7 +162,7 @@ void PostProcesser::Init() cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - GammaCBData initData = {1.0f, {0, 0, 0}}; + GammaCBData initData = {1.0f, 0, 0.0f, 0.0f, 1.0f, 1.0f, {0, 0}}; D3D11_SUBRESOURCE_DATA srData; srData.pSysMem = &initData; srData.SysMemPitch = 0; @@ -237,6 +241,10 @@ void PostProcesser::Apply() const { GammaCBData *cb = static_cast(mapped.pData); cb->gamma = m_gamma; + cb->uvOffsetX = 0.0f; + cb->uvOffsetY = 0.0f; + cb->uvScaleX = 1.0f; + cb->uvScaleY = 1.0f; ctx->Unmap(m_pGammaCB, 0); } @@ -333,27 +341,6 @@ void PostProcesser::ApplyFromCopied() const ID3D11DeviceContext* ctx = g_pImmediateContext; - D3D11_MAPPED_SUBRESOURCE mapped; - const D3D11_MAP mapType = m_wineMode ? D3D11_MAP_WRITE_NO_OVERWRITE : D3D11_MAP_WRITE_DISCARD; - const HRESULT hr = ctx->Map(m_pGammaCB, 0, mapType, 0, &mapped); - if (SUCCEEDED(hr)) - { - const auto cb = static_cast(mapped.pData); - cb->gamma = m_gamma; - ctx->Unmap(m_pGammaCB, 0); - } - - ID3D11RenderTargetView* oldRTV = nullptr; - ID3D11DepthStencilView* oldDSV = nullptr; - ctx->OMGetRenderTargets(1, &oldRTV, &oldDSV); - - UINT numViewports = 1; - D3D11_VIEWPORT oldViewport = {}; - ctx->RSGetViewports(&numViewports, &oldViewport); - - ID3D11RenderTargetView* bbRTV = g_pRenderTargetView; - ctx->OMSetRenderTargets(1, &bbRTV, nullptr); - D3D11_VIEWPORT vp; if (m_useCustomViewport) { @@ -369,6 +356,33 @@ void PostProcesser::ApplyFromCopied() const vp.TopLeftY = 0; } + D3D11_MAPPED_SUBRESOURCE mapped; + const D3D11_MAP mapType = m_wineMode ? D3D11_MAP_WRITE_NO_OVERWRITE : D3D11_MAP_WRITE_DISCARD; + const HRESULT hr = ctx->Map(m_pGammaCB, 0, mapType, 0, &mapped); + if (SUCCEEDED(hr)) + { + const auto cb = static_cast(mapped.pData); + cb->gamma = m_gamma; + const float texW = static_cast(m_gammaTexWidth); + const float texH = static_cast(m_gammaTexHeight); + cb->uvOffsetX = vp.TopLeftX / texW; + cb->uvOffsetY = vp.TopLeftY / texH; + cb->uvScaleX = vp.Width / texW; + cb->uvScaleY = vp.Height / texH; + ctx->Unmap(m_pGammaCB, 0); + } + + ID3D11RenderTargetView* oldRTV = nullptr; + ID3D11DepthStencilView* oldDSV = nullptr; + ctx->OMGetRenderTargets(1, &oldRTV, &oldDSV); + + UINT numViewports = 1; + D3D11_VIEWPORT oldViewport = {}; + ctx->RSGetViewports(&numViewports, &oldViewport); + + ID3D11RenderTargetView* bbRTV = g_pRenderTargetView; + ctx->OMSetRenderTargets(1, &bbRTV, nullptr); + ctx->RSSetViewports(1, &vp); ctx->IASetInputLayout(nullptr); diff --git a/Minecraft.Client/Windows64/Windows64_App.cpp b/Minecraft.Client/Windows64/Windows64_App.cpp index 497808e13..369e29094 100644 --- a/Minecraft.Client/Windows64/Windows64_App.cpp +++ b/Minecraft.Client/Windows64/Windows64_App.cpp @@ -52,8 +52,8 @@ void CConsoleMinecraftApp::GetSaveThumbnail(PBYTE *pbData,DWORD *pdwSize) } else { - // No capture happened (e.g. first save on world creation) leave thumbnail as NULL - if (pbData) *pbData = NULL; + // No capture happened (e.g. first save on world creation) leave thumbnail as nullptr + if (pbData) *pbData = nullptr; if (pdwSize) *pdwSize = 0; } } @@ -69,7 +69,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() { ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit - app.setLevelGenerationOptions(NULL); + app.setLevelGenerationOptions(nullptr); // From CScene_Main::RunPlayGame Minecraft *pMinecraft=Minecraft::GetInstance(); @@ -99,7 +99,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() NetworkGameInitData *param = new NetworkGameInitData(); param->seed = seedValue; - param->saveData = NULL; + param->saveData = nullptr; app.SetGameHostOption(eGameHostOption_Difficulty,0); app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); @@ -125,7 +125,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() LoadingInputParams *loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = (LPVOID)param; + loadingParams->lpParam = static_cast(param); // Reset the autosave time app.SetAutosaveTimerTime(); diff --git a/Minecraft.Client/Windows64/Windows64_App.h b/Minecraft.Client/Windows64/Windows64_App.h index bff916ec7..639cec739 100644 --- a/Minecraft.Client/Windows64/Windows64_App.h +++ b/Minecraft.Client/Windows64/Windows64_App.h @@ -25,9 +25,9 @@ public: virtual int GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT=eFileExtensionType_PNG); // BANNED LEVEL LIST - virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} + virtual void ReadBannedList(int iPad, eTMSAction action=static_cast(0), bool bCallback=false) {} - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable *GetStringTable() { return nullptr;} // original code virtual void TemporaryCreateGameStart(); diff --git a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp index a46d6cd1c..d3ac78a2d 100644 --- a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp +++ b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp @@ -47,6 +47,12 @@ #include "..\GameRenderer.h" #include "Network\WinsockNetLayer.h" #include "Windows64_Xuid.h" +#include "Common/UI/UI.h" + +// Forward-declare the internal Renderer class and its global instance from 4J_Render_PC_d.lib. +// C4JRender (RenderManager) is a stateless wrapper — all D3D state lives in InternalRenderManager. +class Renderer; +extern Renderer InternalRenderManager; #include "Xbox/resource.h" @@ -82,7 +88,6 @@ DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= 0,0,0,0,0 #endif }; - //------------------------------------------------------------------------------------- // 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 @@ -91,10 +96,20 @@ DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= BOOL g_bWidescreen = TRUE; +// Screen resolution — auto-detected from the monitor at startup. +// The 3D world renders at native resolution; Flash UI is 16:9-fitted and centered +// within each viewport (pillarboxed on ultrawide, letterboxed on tall displays). +// ApplyScreenMode() can still override these for debug/test resolutions via launch args. int g_iScreenWidth = 1920; int g_iScreenHeight = 1080; +// Real window dimensions — updated on every WM_SIZE so the 3D perspective +// always matches the current window, even after a resize. +int g_rScreenWidth = 1920; +int g_rScreenHeight = 1080; + float g_iAspectRatio = static_cast(g_iScreenWidth) / g_iScreenHeight; +static bool g_bResizeReady = false; char g_Win64Username[17] = { 0 }; wchar_t g_Win64UsernameW[17] = { 0 }; @@ -103,18 +118,9 @@ wchar_t g_Win64UsernameW[17] = { 0 }; static bool g_isFullscreen = false; static WINDOWPLACEMENT g_wpPrev = { sizeof(g_wpPrev) }; -//-------------------------------------------------------------------------------------- -// Update the Aspect Ratio to support Any Aspect Ratio -//-------------------------------------------------------------------------------------- -void UpdateAspectRatio(int width, int height) -{ - g_iAspectRatio = static_cast(width) / height; -} - struct Win64LaunchOptions { int screenMode; - bool serverMode; bool fullscreen; }; @@ -124,17 +130,17 @@ static void CopyWideArgToAnsi(LPCWSTR source, char* dest, size_t destSize) return; dest[0] = 0; - if (source == NULL) + if (source == nullptr) return; - WideCharToMultiByte(CP_ACP, 0, source, -1, dest, (int)destSize, NULL, NULL); + WideCharToMultiByte(CP_ACP, 0, source, -1, dest, static_cast(destSize), nullptr, nullptr); dest[destSize - 1] = 0; } // ---------- Persistent options (options.txt next to exe) ---------- static void GetOptionsFilePath(char *out, size_t outSize) { - GetModuleFileNameA(NULL, out, (DWORD)outSize); + GetModuleFileNameA(nullptr, out, static_cast(outSize)); char *p = strrchr(out, '\\'); if (p) *(p + 1) = '\0'; strncat_s(out, outSize, "options.txt", _TRUNCATE); @@ -200,17 +206,13 @@ static Win64LaunchOptions ParseLaunchOptions() { Win64LaunchOptions options = {}; options.screenMode = 0; - options.serverMode = false; g_Win64MultiplayerJoin = false; g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT; - g_Win64DedicatedServer = false; - g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT; - g_Win64DedicatedServerBindIP[0] = 0; int argc = 0; LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); - if (argv == NULL) + if (argv == nullptr) return options; if (argc > 1 && lstrlenW(argv[1]) == 1) @@ -219,17 +221,6 @@ static Win64LaunchOptions ParseLaunchOptions() options.screenMode = argv[1][0] - L'0'; } - for (int i = 1; i < argc; ++i) - { - if (_wcsicmp(argv[i], L"-server") == 0) - { - options.serverMode = true; - break; - } - } - - g_Win64DedicatedServer = options.serverMode; - for (int i = 1; i < argc; ++i) { if (_wcsicmp(argv[i], L"-name") == 0 && (i + 1) < argc) @@ -240,26 +231,16 @@ static Win64LaunchOptions ParseLaunchOptions() { char ipBuf[256]; CopyWideArgToAnsi(argv[++i], ipBuf, sizeof(ipBuf)); - if (options.serverMode) - { - strncpy_s(g_Win64DedicatedServerBindIP, sizeof(g_Win64DedicatedServerBindIP), ipBuf, _TRUNCATE); - } - else - { - strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), ipBuf, _TRUNCATE); - g_Win64MultiplayerJoin = true; - } + strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), ipBuf, _TRUNCATE); + g_Win64MultiplayerJoin = true; } else if (_wcsicmp(argv[i], L"-port") == 0 && (i + 1) < argc) { - wchar_t* endPtr = NULL; - long port = wcstol(argv[++i], &endPtr, 10); + wchar_t* endPtr = nullptr; + const long port = wcstol(argv[++i], &endPtr, 10); if (endPtr != argv[i] && *endPtr == 0 && port > 0 && port <= 65535) { - if (options.serverMode) - g_Win64DedicatedServerPort = (int)port; - else - g_Win64MultiplayerPort = (int)port; + g_Win64MultiplayerPort = static_cast(port); } } else if (_wcsicmp(argv[i], L"-fullscreen") == 0) @@ -270,36 +251,6 @@ static Win64LaunchOptions ParseLaunchOptions() return options; } -static BOOL WINAPI HeadlessServerCtrlHandler(DWORD ctrlType) -{ - switch (ctrlType) - { - case CTRL_C_EVENT: - case CTRL_BREAK_EVENT: - case CTRL_CLOSE_EVENT: - case CTRL_SHUTDOWN_EVENT: - app.m_bShutdown = true; - MinecraftServer::HaltServer(); - return TRUE; - default: - return FALSE; - } -} - -static void SetupHeadlessServerConsole() -{ - if (AllocConsole()) - { - FILE* stream = NULL; - freopen_s(&stream, "CONIN$", "r", stdin); - freopen_s(&stream, "CONOUT$", "w", stdout); - freopen_s(&stream, "CONOUT$", "w", stderr); - SetConsoleTitleA("Minecraft Server"); - } - - SetConsoleCtrlHandler(HeadlessServerCtrlHandler, TRUE); -} - void DefineActions(void) { // The app needs to define the actions required, and the possible mappings for these @@ -494,7 +445,7 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, return pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, - NULL, + nullptr, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, pd3dPP, ppDevice ); @@ -512,16 +463,16 @@ void MemSect(int sect) } #endif -HINSTANCE g_hInst = NULL; -HWND g_hWnd = NULL; +HINSTANCE g_hInst = nullptr; +HWND g_hWnd = nullptr; D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; -ID3D11Device* g_pd3dDevice = NULL; -ID3D11DeviceContext* g_pImmediateContext = NULL; -IDXGISwapChain* g_pSwapChain = NULL; -ID3D11RenderTargetView* g_pRenderTargetView = NULL; -ID3D11DepthStencilView* g_pDepthStencilView = NULL; -ID3D11Texture2D* g_pDepthStencilBuffer = NULL; +ID3D11Device* g_pd3dDevice = nullptr; +ID3D11DeviceContext* g_pImmediateContext = nullptr; +IDXGISwapChain* g_pSwapChain = nullptr; +ID3D11RenderTargetView* g_pRenderTargetView = nullptr; +ID3D11DepthStencilView* g_pDepthStencilView = nullptr; +ID3D11Texture2D* g_pDepthStencilBuffer = nullptr; // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) @@ -534,6 +485,11 @@ ID3D11Texture2D* g_pDepthStencilBuffer = NULL; // WM_SIZE - handle resizing logic to support Any Aspect Ratio // // +static bool ResizeD3D(int newW, int newH); // forward declaration +static bool g_bInSizeMove = false; // true while the user is dragging the window border +static int g_pendingResizeW = 0; // deferred resize dimensions +static int g_pendingResizeH = 0; + LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; @@ -589,7 +545,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) if ((lParam & 0x40000000) && vk != VK_LEFT && vk != VK_RIGHT && vk != VK_BACK) break; #ifdef _WINDOWS64 - Minecraft* pm = Minecraft::GetInstance(); + const Minecraft* pm = Minecraft::GetInstance(); ChatScreen* chat = pm && pm->screen ? dynamic_cast(pm->screen) : nullptr; if (chat) { @@ -656,13 +612,13 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) case WM_INPUT: { UINT dwSize = 0; - GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); + GetRawInputData((HRAWINPUT)lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER)); if (dwSize > 0 && dwSize <= 256) { BYTE rawBuffer[256]; if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, rawBuffer, &dwSize, sizeof(RAWINPUTHEADER)) == dwSize) { - RAWINPUT* raw = (RAWINPUT*)rawBuffer; + const RAWINPUT* raw = (RAWINPUT*)rawBuffer; if (raw->header.dwType == RIM_TYPEMOUSE) { g_KBMInput.OnRawMouseDelta(raw->data.mouse.lLastX, raw->data.mouse.lLastY); @@ -671,9 +627,40 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) } } break; + case WM_ENTERSIZEMOVE: + g_bInSizeMove = true; + break; + + case WM_EXITSIZEMOVE: + g_bInSizeMove = false; + if (g_pendingResizeW > 0 && g_pendingResizeH > 0) + { + // g_rScreenWidth/Height updated inside ResizeD3D to backbuffer dims + ResizeD3D(g_pendingResizeW, g_pendingResizeH); + g_pendingResizeW = 0; + g_pendingResizeH = 0; + } + break; + case WM_SIZE: { - UpdateAspectRatio(LOWORD(lParam), HIWORD(lParam)); + int newW = LOWORD(lParam); + int newH = HIWORD(lParam); + if (newW > 0 && newH > 0) + { + if (g_bInSizeMove) + { + // Just store the latest size, resize when dragging ends + g_pendingResizeW = newW; + g_pendingResizeH = newH; + } + else + { + // Immediate resize (maximize, programmatic resize, etc.) + // g_rScreenWidth/Height updated inside ResizeD3D to backbuffer dims + ResizeD3D(newW, newH); + } + } } break; default: @@ -699,7 +686,7 @@ ATOM MyRegisterClass(HINSTANCE hInstance) wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, "Minecraft"); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = "Minecraft"; wcex.lpszClassName = "MinecraftClass"; @@ -722,7 +709,7 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { g_hInst = hInstance; // Store instance handle in our global variable - RECT wr = {0, 0, g_iScreenWidth, g_iScreenHeight}; // set the size, but not the position + RECT wr = {0, 0, g_rScreenWidth, g_rScreenHeight}; // set the size, but not the position AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size g_hWnd = CreateWindow( "MinecraftClass", @@ -732,10 +719,10 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) 0, wr.right - wr.left, // width of the window wr.bottom - wr.top, // height of the window - NULL, - NULL, + nullptr, + nullptr, hInstance, - NULL); + nullptr); if (!g_hWnd) { @@ -808,8 +795,8 @@ HRESULT InitDevice() UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; //app.DebugPrintf("width: %d, height: %d\n", width, height); - width = g_iScreenWidth; - height = g_iScreenHeight; + width = g_rScreenWidth; + height = g_rScreenHeight; //app.DebugPrintf("width: %d, height: %d\n", width, height); UINT createDeviceFlags = 0; @@ -841,7 +828,7 @@ HRESULT InitDevice() sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; @@ -850,7 +837,7 @@ HRESULT InitDevice() for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { g_driverType = driverTypes[driverTypeIndex]; - hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, + hr = D3D11CreateDeviceAndSwapChain( nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); if( HRESULT_SUCCEEDED( hr ) ) break; @@ -859,7 +846,7 @@ HRESULT InitDevice() return hr; // Create a render target view - ID3D11Texture2D* pBackBuffer = NULL; + ID3D11Texture2D* pBackBuffer = nullptr; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; @@ -879,7 +866,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, nullptr, &g_pDepthStencilBuffer); D3D11_DEPTH_STENCIL_VIEW_DESC descDSView; ZeroMemory(&descDSView, sizeof(descDSView)); @@ -889,7 +876,7 @@ HRESULT InitDevice() hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); - hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); + hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &g_pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; @@ -898,8 +885,8 @@ HRESULT InitDevice() // Setup the viewport D3D11_VIEWPORT vp; - vp.Width = (FLOAT)width; - vp.Height = (FLOAT)height; + vp.Width = static_cast(width); + vp.Height = static_cast(height); vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; @@ -919,18 +906,293 @@ HRESULT InitDevice() void Render() { // Just clear the backbuffer - float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red,green,blue,alpha + const float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red,green,blue,alpha g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor ); g_pSwapChain->Present( 0, 0 ); } +//-------------------------------------------------------------------------------------- +// Rebuild D3D11 resources after a window resize +//-------------------------------------------------------------------------------------- +static bool ResizeD3D(int newW, int newH) +{ + if (newW <= 0 || newH <= 0) return false; + if (!g_pSwapChain) return false; + if (!g_bResizeReady) return false; + + int bbW = newW; + int bbH = newH; + + // InternalRenderManager member offsets (from decompiled Renderer.h): + // 0x10 m_pDevice (ID3D11Device*) + // 0x18 m_pDeviceContext (ID3D11DeviceContext*) + // 0x20 m_pSwapChain (IDXGISwapChain*) + // 0x28 renderTargetView (ID3D11RenderTargetView*) — backbuffer RTV + // 0x50 renderTargetShaderResourceView (ID3D11ShaderResourceView*) + // 0x98 depthStencilView (ID3D11DepthStencilView*) + // 0x5138 backBufferWidth (DWORD) — used by StartFrame() for viewport + // 0x513C backBufferHeight (DWORD) — used by StartFrame() for viewport + // + // Strategy: destroy old swap chain, create new one, patch Renderer's internal + // pointers directly. This avoids both ResizeBuffers (outstanding ref issues) + // and Initialise() (which wipes the texture table via memset). + // The Renderer's old RTV/SRV/DSV are intentionally NOT released — they become + // orphaned with the old swap chain. Tiny leak, but avoids fighting unknown refs. + char* pRM = (char*)&InternalRenderManager; + ID3D11RenderTargetView** ppRM_RTV = (ID3D11RenderTargetView**)(pRM + 0x28); + ID3D11ShaderResourceView** ppRM_SRV = (ID3D11ShaderResourceView**)(pRM + 0x50); + ID3D11DepthStencilView** ppRM_DSV = (ID3D11DepthStencilView**)(pRM + 0x98); + IDXGISwapChain** ppRM_SC = (IDXGISwapChain**)(pRM + 0x20); + DWORD* pRM_BBWidth = (DWORD*)(pRM + 0x5138); + DWORD* pRM_BBHeight = (DWORD*)(pRM + 0x513C); + + // Verify offsets by checking device and swap chain pointers + ID3D11Device** ppRM_Device = (ID3D11Device**)(pRM + 0x10); + if (*ppRM_Device != g_pd3dDevice || *ppRM_SC != g_pSwapChain) + { + app.DebugPrintf("[RESIZE] ERROR: RenderManager offset verification failed! " + "device=%p (expected %p) swapchain=%p (expected %p)\n", + *ppRM_Device, g_pd3dDevice, *ppRM_SC, g_pSwapChain); + return false; + } + + // Cross-check backbuffer dimension offsets against swap chain desc + DXGI_SWAP_CHAIN_DESC oldScDesc; + g_pSwapChain->GetDesc(&oldScDesc); + bool bbDimsValid = (*pRM_BBWidth == oldScDesc.BufferDesc.Width && + *pRM_BBHeight == oldScDesc.BufferDesc.Height); + if (!bbDimsValid) + { + app.DebugPrintf("[RESIZE] WARNING: backBuffer dim offsets wrong: " + "stored=%ux%u, swapchain=%ux%u\n", + *pRM_BBWidth, *pRM_BBHeight, oldScDesc.BufferDesc.Width, oldScDesc.BufferDesc.Height); + } + + RenderManager.Suspend(); + while (!RenderManager.Suspended()) { Sleep(1); } + + PostProcesser::GetInstance().Cleanup(); + + g_pImmediateContext->ClearState(); + g_pImmediateContext->Flush(); + + // Release OUR views and depth buffer + if (g_pRenderTargetView) { g_pRenderTargetView->Release(); g_pRenderTargetView = NULL; } + if (g_pDepthStencilView) { g_pDepthStencilView->Release(); g_pDepthStencilView = NULL; } + if (g_pDepthStencilBuffer) { g_pDepthStencilBuffer->Release(); g_pDepthStencilBuffer = NULL; } + + gdraw_D3D11_PreReset(); + + // Get IDXGIFactory from the existing device BEFORE destroying the old swap chain. + // If anything fails before we have a new swap chain, we abort without destroying + // the old one — leaving the Renderer in a valid (old-size) state. + IDXGISwapChain* pOldSwapChain = g_pSwapChain; + bool success = false; + HRESULT hr; + + IDXGIDevice* dxgiDevice = NULL; + IDXGIAdapter* dxgiAdapter = NULL; + IDXGIFactory* dxgiFactory = NULL; + hr = g_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); + if (FAILED(hr)) goto postReset; + hr = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); + if (FAILED(hr)) { dxgiDevice->Release(); goto postReset; } + hr = dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); + dxgiAdapter->Release(); + dxgiDevice->Release(); + if (FAILED(hr)) goto postReset; + + // Create new swap chain at backbuffer size + { + DXGI_SWAP_CHAIN_DESC sd = {}; + sd.BufferCount = 1; + sd.BufferDesc.Width = bbW; + sd.BufferDesc.Height = bbH; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; + sd.OutputWindow = g_hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + + IDXGISwapChain* pNewSwapChain = NULL; + hr = dxgiFactory->CreateSwapChain(g_pd3dDevice, &sd, &pNewSwapChain); + dxgiFactory->Release(); + if (FAILED(hr) || pNewSwapChain == NULL) + { + app.DebugPrintf("[RESIZE] CreateSwapChain FAILED hr=0x%08X — keeping old swap chain\n", (unsigned)hr); + goto postReset; + } + + // New swap chain created successfully — NOW destroy the old one. + // The Renderer's internal RTV/SRV still reference the old backbuffer — + // those COM objects become orphaned (tiny leak, harmless). We DON'T + // release them because unknown code may also hold refs. + pOldSwapChain->Release(); + g_pSwapChain = pNewSwapChain; + } + + // Patch Renderer's swap chain pointer + *ppRM_SC = g_pSwapChain; + + // Create render target views from new backbuffer + { + ID3D11Texture2D* pBackBuffer = NULL; + hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); + if (FAILED(hr)) goto postReset; + + // Our RTV + hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView); + if (FAILED(hr)) { pBackBuffer->Release(); goto postReset; } + + // Renderer's internal RTV (offset 0x28) + hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, ppRM_RTV); + if (FAILED(hr)) { pBackBuffer->Release(); goto postReset; } + + // Renderer's SRV: separate texture matching backbuffer dims (used by CaptureThumbnail) + D3D11_TEXTURE2D_DESC backDesc = {}; + pBackBuffer->GetDesc(&backDesc); + pBackBuffer->Release(); + + D3D11_TEXTURE2D_DESC srvDesc = backDesc; + srvDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; + ID3D11Texture2D* srvTexture = NULL; + hr = g_pd3dDevice->CreateTexture2D(&srvDesc, NULL, &srvTexture); + if (SUCCEEDED(hr)) + { + hr = g_pd3dDevice->CreateShaderResourceView(srvTexture, NULL, ppRM_SRV); + srvTexture->Release(); + } + if (FAILED(hr)) goto postReset; + } + + // Recreate depth stencil at backbuffer size + { + D3D11_TEXTURE2D_DESC descDepth = {}; + descDepth.Width = bbW; + descDepth.Height = bbH; + descDepth.MipLevels = 1; + descDepth.ArraySize = 1; + descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + descDepth.SampleDesc.Count = 1; + descDepth.SampleDesc.Quality = 0; + descDepth.Usage = D3D11_USAGE_DEFAULT; + descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; + hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); + if (FAILED(hr)) goto postReset; + + D3D11_DEPTH_STENCIL_VIEW_DESC descDSView = {}; + descDSView.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + descDSView.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); + if (FAILED(hr)) goto postReset; + } + + // Patch Renderer's DSV (AddRef because both we and the Renderer reference it) + g_pDepthStencilView->AddRef(); + *ppRM_DSV = g_pDepthStencilView; + + // Update Renderer's cached backbuffer dimensions (StartFrame uses these for viewport) + if (bbDimsValid) + { + *pRM_BBWidth = (DWORD)bbW; + *pRM_BBHeight = (DWORD)bbH; + } + + // Rebind render targets and viewport + g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView); + { + D3D11_VIEWPORT vp = {}; + vp.Width = (FLOAT)bbW; + vp.Height = (FLOAT)bbH; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + g_pImmediateContext->RSSetViewports(1, &vp); + } + + ui.updateRenderTargets(g_pRenderTargetView, g_pDepthStencilView); + ui.updateScreenSize(bbW, bbH); + + // Track actual backbuffer dimensions for the rest of the engine + g_rScreenWidth = bbW; + g_rScreenHeight = bbH; + + success = true; + +postReset: + if (!success && g_pSwapChain != NULL) + { + // Failure recovery: recreate our views from whatever swap chain survived + // so ui.m_pRenderTargetView / m_pDepthStencilView don't dangle. + DXGI_SWAP_CHAIN_DESC recoveryDesc; + g_pSwapChain->GetDesc(&recoveryDesc); + int recW = (int)recoveryDesc.BufferDesc.Width; + int recH = (int)recoveryDesc.BufferDesc.Height; + + if (g_pRenderTargetView == NULL) + { + ID3D11Texture2D* pBB = NULL; + if (SUCCEEDED(g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBB))) + { + g_pd3dDevice->CreateRenderTargetView(pBB, NULL, &g_pRenderTargetView); + pBB->Release(); + } + } + if (g_pDepthStencilView == NULL) + { + D3D11_TEXTURE2D_DESC dd = {}; + dd.Width = recW; dd.Height = recH; dd.MipLevels = 1; dd.ArraySize = 1; + dd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + dd.SampleDesc.Count = 1; dd.Usage = D3D11_USAGE_DEFAULT; + dd.BindFlags = D3D11_BIND_DEPTH_STENCIL; + if (g_pDepthStencilBuffer == NULL) + g_pd3dDevice->CreateTexture2D(&dd, NULL, &g_pDepthStencilBuffer); + if (g_pDepthStencilBuffer != NULL) + { + D3D11_DEPTH_STENCIL_VIEW_DESC dsvd = {}; + dsvd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &dsvd, &g_pDepthStencilView); + } + } + if (g_pRenderTargetView != NULL) + g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView); + + ui.updateRenderTargets(g_pRenderTargetView, g_pDepthStencilView); + + // If the surviving swap chain is the OLD one, dims are unchanged. + // If it's the NEW one (partial failure after swap), update to new dims. + if (g_pSwapChain != pOldSwapChain) + { + g_rScreenWidth = recW; + g_rScreenHeight = recH; + ui.updateScreenSize(recW, recH); + } + + app.DebugPrintf("[RESIZE] FAILED but recovered views at %dx%d\n", g_rScreenWidth, g_rScreenHeight); + } + + gdraw_D3D11_PostReset(); + gdraw_D3D11_SetRendertargetSize(g_rScreenWidth, g_rScreenHeight); + if (success) + IggyFlushInstalledFonts(); + RenderManager.Resume(); + + if (success) + PostProcesser::GetInstance().Init(); + + return success; +} + //-------------------------------------------------------------------------------------- // Toggle borderless fullscreen //-------------------------------------------------------------------------------------- void ToggleFullscreen() { - DWORD dwStyle = GetWindowLong(g_hWnd, GWL_STYLE); + const DWORD dwStyle = GetWindowLong(g_hWnd, GWL_STYLE); if (!g_isFullscreen) { MONITORINFO mi = { sizeof(mi) }; @@ -949,7 +1211,7 @@ void ToggleFullscreen() { SetWindowLong(g_hWnd, GWL_STYLE, dwStyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(g_hWnd, &g_wpPrev); - SetWindowPos(g_hWnd, NULL, 0, 0, 0, 0, + SetWindowPos(g_hWnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); } g_isFullscreen = !g_isFullscreen; @@ -966,6 +1228,8 @@ void CleanupDevice() { if( g_pImmediateContext ) g_pImmediateContext->ClearState(); + if( g_pDepthStencilView ) g_pDepthStencilView->Release(); + if( g_pDepthStencilBuffer ) g_pDepthStencilBuffer->Release(); if( g_pRenderTargetView ) g_pRenderTargetView->Release(); if( g_pSwapChain ) g_pSwapChain->Release(); if( g_pImmediateContext ) g_pImmediateContext->Release(); @@ -979,7 +1243,7 @@ static Minecraft* InitialiseMinecraftRuntime() RenderManager.Initialise(g_pd3dDevice, g_pSwapChain); app.loadStringTable(); - ui.init(g_pd3dDevice, g_pImmediateContext, g_pRenderTargetView, g_pDepthStencilView, g_iScreenWidth, g_iScreenHeight); + ui.init(g_pd3dDevice, g_pImmediateContext, g_pRenderTargetView, g_pDepthStencilView, g_rScreenWidth, g_rScreenHeight); InputManager.Initialise(1, 3, MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); g_KBMInput.Init(); @@ -1002,7 +1266,7 @@ static Minecraft* InitialiseMinecraftRuntime() for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) { - IQNet::m_player[i].m_smallId = (BYTE)i; + IQNet::m_player[i].m_smallId = static_cast(i); IQNet::m_player[i].m_isRemote = false; IQNet::m_player[i].m_isHostPlayer = (i == 0); swprintf_s(IQNet::m_player[i].m_gamertag, 32, L"Player%d", i); @@ -1024,8 +1288,8 @@ static Minecraft* InitialiseMinecraftRuntime() Minecraft::main(); Minecraft* pMinecraft = Minecraft::GetInstance(); - if (pMinecraft == NULL) - return NULL; + if (pMinecraft == nullptr) + return nullptr; app.InitGameSettings(); app.InitialiseTips(); @@ -1033,161 +1297,6 @@ static Minecraft* InitialiseMinecraftRuntime() return pMinecraft; } -static int HeadlessServerConsoleThreadProc(void* lpParameter) -{ - UNREFERENCED_PARAMETER(lpParameter); - - std::string line; - while (!app.m_bShutdown) - { - if (!std::getline(std::cin, line)) - { - if (std::cin.eof()) - { - break; - } - - std::cin.clear(); - Sleep(50); - continue; - } - - wstring command = trimString(convStringToWstring(line)); - if (command.empty()) - continue; - - MinecraftServer* server = MinecraftServer::getInstance(); - if (server != NULL) - { - server->handleConsoleInput(command, server); - } - } - - return 0; -} - -static int RunHeadlessServer() -{ - SetupHeadlessServerConsole(); - - Settings serverSettings(new File(L"server.properties")); - wstring configuredBindIp = serverSettings.getString(L"server-ip", L""); - - const char* bindIp = "*"; - if (g_Win64DedicatedServerBindIP[0] != 0) - { - bindIp = g_Win64DedicatedServerBindIP; - } - else if (!configuredBindIp.empty()) - { - bindIp = wstringtochararray(configuredBindIp); - } - - const int port = g_Win64DedicatedServerPort > 0 ? g_Win64DedicatedServerPort : serverSettings.getInt(L"server-port", WIN64_NET_DEFAULT_PORT); - - printf("Starting headless server on %s:%d\n", bindIp, port); - fflush(stdout); - - Minecraft* pMinecraft = InitialiseMinecraftRuntime(); - if (pMinecraft == NULL) - { - fprintf(stderr, "Failed to initialise the Minecraft runtime.\n"); - return 1; - } - - app.SetGameHostOption(eGameHostOption_Difficulty, serverSettings.getInt(L"difficulty", 1)); - app.SetGameHostOption(eGameHostOption_Gamertags, 1); - app.SetGameHostOption(eGameHostOption_GameType, serverSettings.getInt(L"gamemode", 0)); - app.SetGameHostOption(eGameHostOption_LevelType, 0); - app.SetGameHostOption(eGameHostOption_Structures, serverSettings.getBoolean(L"generate-structures", true) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_BonusChest, serverSettings.getBoolean(L"bonus-chest", false) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_PvP, serverSettings.getBoolean(L"pvp", true) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_TrustPlayers, serverSettings.getBoolean(L"trust-players", true) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_FireSpreads, serverSettings.getBoolean(L"fire-spreads", true) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_TNT, serverSettings.getBoolean(L"tnt", true) ? 1 : 0); - app.SetGameHostOption(eGameHostOption_HostCanFly, 1); - app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1); - app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1); - app.SetGameHostOption(eGameHostOption_MobGriefing, 1); - app.SetGameHostOption(eGameHostOption_KeepInventory, 0); - app.SetGameHostOption(eGameHostOption_DoMobSpawning, 1); - app.SetGameHostOption(eGameHostOption_DoMobLoot, 1); - app.SetGameHostOption(eGameHostOption_DoTileDrops, 1); - app.SetGameHostOption(eGameHostOption_NaturalRegeneration, 1); - app.SetGameHostOption(eGameHostOption_DoDaylightCycle, 1); - - MinecraftServer::resetFlags(); - g_NetworkManager.HostGame(0, false, true, MINECRAFT_NET_MAX_PLAYERS, 0); - - if (!WinsockNetLayer::IsActive()) - { - fprintf(stderr, "Failed to bind the server socket on %s:%d.\n", bindIp, port); - return 1; - } - - g_NetworkManager.FakeLocalPlayerJoined(); - - NetworkGameInitData* param = new NetworkGameInitData(); - param->seed = 0; - param->settings = app.GetGameHostOption(eGameHostOption_All); - - g_NetworkManager.ServerStoppedCreate(true); - g_NetworkManager.ServerReadyCreate(true); - - C4JThread* thread = new C4JThread(&CGameNetworkManager::ServerThreadProc, param, "Server", 256 * 1024); - thread->SetProcessor(CPU_CORE_SERVER); - thread->Run(); - - g_NetworkManager.ServerReadyWait(); - g_NetworkManager.ServerReadyDestroy(); - - if (MinecraftServer::serverHalted()) - { - fprintf(stderr, "The server halted during startup.\n"); - g_NetworkManager.LeaveGame(false); - return 1; - } - - app.SetGameStarted(true); - g_NetworkManager.DoWork(); - - printf("Server ready on %s:%d\n", bindIp, port); - printf("Type 'help' for server commands.\n"); - fflush(stdout); - - C4JThread* consoleThread = new C4JThread(&HeadlessServerConsoleThreadProc, NULL, "Server console", 128 * 1024); - consoleThread->Run(); - - MSG msg = { 0 }; - while (WM_QUIT != msg.message && !app.m_bShutdown && !MinecraftServer::serverHalted()) - { - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - continue; - } - - app.UpdateTime(); - ProfileManager.Tick(); - StorageManager.Tick(); - RenderManager.Tick(); - ui.tick(); - g_NetworkManager.DoWork(); - app.HandleXuiActions(); - - Sleep(10); - } - - printf("Stopping server...\n"); - fflush(stdout); - - app.m_bShutdown = true; - MinecraftServer::HaltServer(); - g_NetworkManager.LeaveGame(false); - return 0; -} - int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, @@ -1199,19 +1308,23 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // 4J-Win64: set CWD to exe dir so asset paths resolve correctly { char szExeDir[MAX_PATH] = {}; - GetModuleFileNameA(NULL, szExeDir, MAX_PATH); + GetModuleFileNameA(nullptr, szExeDir, MAX_PATH); char *pSlash = strrchr(szExeDir, '\\'); if (pSlash) { *(pSlash + 1) = '\0'; SetCurrentDirectoryA(szExeDir); } } // Declare DPI awareness so GetSystemMetrics returns physical pixels SetProcessDPIAware(); - g_iScreenWidth = GetSystemMetrics(SM_CXSCREEN); - g_iScreenHeight = GetSystemMetrics(SM_CYSCREEN); + // Use the native monitor resolution for the window and swap chain, + // but keep g_iScreenWidth/Height at 1920x1080 for logical resolution + // (SWF selection, ortho projection, game logic). The real window + // dimensions are tracked by g_rScreenWidth/g_rScreenHeight. + g_rScreenWidth = GetSystemMetrics(SM_CXSCREEN); + g_rScreenHeight = GetSystemMetrics(SM_CYSCREEN); // Load username from username.txt char exePath[MAX_PATH] = {}; - GetModuleFileNameA(NULL, exePath, MAX_PATH); + GetModuleFileNameA(nullptr, exePath, MAX_PATH); char *lastSlash = strrchr(exePath, '\\'); if (lastSlash) { @@ -1227,7 +1340,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, char buf[128] = {}; if (fgets(buf, sizeof(buf), f)) { - int len = (int)strlen(buf); + int len = static_cast(strlen(buf)); while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ')) { buf[--len] = '\0'; @@ -1242,14 +1355,11 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } // Load stuff from launch options, including username - Win64LaunchOptions launchOptions = ParseLaunchOptions(); + const Win64LaunchOptions launchOptions = ParseLaunchOptions(); ApplyScreenMode(launchOptions.screenMode); - // Ensure uid.dat exists from startup in client mode (before any multiplayer/login path). - if (!launchOptions.serverMode) - { - Win64Xuid::ResolvePersistentXuid(); - } + // Ensure uid.dat exists from startup (before any multiplayer/login path). + Win64Xuid::ResolvePersistentXuid(); // If no username, let's fall back if (g_Win64Username[0] == 0) @@ -1330,7 +1440,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, MyRegisterClass(hInstance); // Perform application initialization: - if (!InitInstance (hInstance, launchOptions.serverMode ? SW_HIDE : nCmdShow)) + if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } @@ -1349,19 +1459,12 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, ToggleFullscreen(); } - if (launchOptions.serverMode) - { - int serverResult = RunHeadlessServer(); - CleanupDevice(); - return serverResult; - } - #if 0 // Main message loop MSG msg = {0}; while( WM_QUIT != msg.message ) { - if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) + if( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); @@ -1409,11 +1512,12 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, #endif Minecraft *pMinecraft = InitialiseMinecraftRuntime(); - if (pMinecraft == NULL) + if (pMinecraft == nullptr) { CleanupDevice(); return 1; } + g_bResizeReady = true; //app.TemporaryCreateGameStart(); @@ -1445,7 +1549,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, { g_KBMInput.Tick(); - while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) + while( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); @@ -1453,6 +1557,14 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } if (msg.message == WM_QUIT) break; + // When the window is minimized (e.g. "Show Desktop"), skip rendering entirely + // to avoid pegging the GPU at 100% presenting to a non-visible swap chain. + if (IsIconic(g_hWnd)) + { + Sleep(100); + continue; + } + RenderManager.StartFrame(); #if 0 if(pMinecraft->soundEngine->isStreamingWavebankReady() && @@ -1478,7 +1590,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // Detect KBM vs controller input mode if (InputManager.IsPadConnected(0)) { - bool controllerUsed = InputManager.ButtonPressed(0) || + const bool controllerUsed = InputManager.ButtonPressed(0) || InputManager.GetJoypadStick_LX(0, false) != 0.0f || InputManager.GetJoypadStick_LY(0, false) != 0.0f || InputManager.GetJoypadStick_RX(0, false) != 0.0f || @@ -1540,7 +1652,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); @@ -1637,7 +1749,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // Update mouse grab: grab when in-game and no menu is open { static bool altToggleSuppressCapture = false; - bool shouldCapture = app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL; + const bool shouldCapture = app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == nullptr; // Left Alt key toggles capture on/off for debugging if (g_KBMInput.IsKeyPressed(VK_LMENU) || g_KBMInput.IsKeyPressed(VK_RMENU)) { @@ -1656,18 +1768,18 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } // F1 toggles the HUD - if (g_KBMInput.IsKeyPressed(VK_F1)) + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_TOGGLE_HUD)) { - int primaryPad = ProfileManager.GetPrimaryPad(); - unsigned char displayHud = app.GetGameSettings(primaryPad, eGameSetting_DisplayHUD); + const int primaryPad = ProfileManager.GetPrimaryPad(); + const unsigned char displayHud = app.GetGameSettings(primaryPad, eGameSetting_DisplayHUD); app.SetGameSettings(primaryPad, eGameSetting_DisplayHUD, displayHud ? 0 : 1); app.SetGameSettings(primaryPad, eGameSetting_DisplayHand, displayHud ? 0 : 1); } // F3 toggles onscreen debug info - if (g_KBMInput.IsKeyPressed(VK_F3)) + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_DEBUG_INFO)) { - if (Minecraft* pMinecraft = Minecraft::GetInstance()) + if (const Minecraft* pMinecraft = Minecraft::GetInstance()) { if (pMinecraft->options) { @@ -1678,7 +1790,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, #ifdef _DEBUG_MENUS_ENABLED // F6 Open debug console - if (g_KBMInput.IsKeyPressed(VK_F6)) + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_DEBUG_CONSOLE)) { static bool s_debugConsole = false; s_debugConsole = !s_debugConsole; @@ -1686,14 +1798,14 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } #endif - // F11 Toggle fullscreen - if (g_KBMInput.IsKeyPressed(VK_F11)) + // toggle fullscreen + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_FULLSCREEN)) { ToggleFullscreen(); } // TAB opens game info menu. - Vvis :3 - Updated by detectiveren - if (g_KBMInput.IsKeyPressed(VK_TAB) && !ui.GetMenuDisplayed(0)) + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_HOST_SETTINGS) && !ui.GetMenuDisplayed(0)) { if (Minecraft* pMinecraft = Minecraft::GetInstance()) { @@ -1705,7 +1817,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } // Open chat - if (g_KBMInput.IsKeyPressed('T') && app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL) + if (g_KBMInput.IsKeyPressed(KeyboardMouseInput::KEY_CHAT) && app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL) { g_KBMInput.ClearCharBuffer(); pMinecraft->setScreen(new ChatScreen()); diff --git a/Minecraft.Client/Windows64/Windows64_UIController.cpp b/Minecraft.Client/Windows64/Windows64_UIController.cpp index 10ae20aff..3929aa049 100644 --- a/Minecraft.Client/Windows64/Windows64_UIController.cpp +++ b/Minecraft.Client/Windows64/Windows64_UIController.cpp @@ -82,7 +82,7 @@ void ConsoleUIController::render() example, no resolve targets are required. */ gdraw_D3D11_SetTileOrigin( m_pRenderTargetView, m_pDepthStencilView, - NULL, + nullptr, 0, 0 ); @@ -143,11 +143,17 @@ void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion *region) PIXEndNamedEvent(); } +void ConsoleUIController::updateRenderTargets(ID3D11RenderTargetView* rtv, ID3D11DepthStencilView* dsv) +{ + m_pRenderTargetView = rtv; + m_pDepthStencilView = dsv; +} + void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) { gdraw_D3D11_SetTileOrigin( m_pRenderTargetView, m_pDepthStencilView, - NULL, + nullptr, xPos, yPos ); } @@ -163,7 +169,7 @@ GDrawTexture *ConsoleUIController::getSubstitutionTexture(int textureId) ID3D11ShaderResourceView *tex = RenderManager.TextureGetTexture(textureId); ID3D11Resource *resource; tex->GetResource(&resource); - ID3D11Texture2D *tex2d = (ID3D11Texture2D *)resource; + ID3D11Texture2D *tex2d = static_cast(resource); D3D11_TEXTURE2D_DESC desc; tex2d->GetDesc(&desc); GDrawTexture *gdrawTex = gdraw_D3D11_WrappedTextureCreate(tex); diff --git a/Minecraft.Client/Windows64/Windows64_UIController.h b/Minecraft.Client/Windows64/Windows64_UIController.h index 2b2ccdbac..398e97126 100644 --- a/Minecraft.Client/Windows64/Windows64_UIController.h +++ b/Minecraft.Client/Windows64/Windows64_UIController.h @@ -16,15 +16,15 @@ public: virtual CustomDrawData *calculateCustomDraw(IggyCustomDrawCallbackRegion *region); virtual void endCustomDraw(IggyCustomDrawCallbackRegion *region); + void updateRenderTargets(ID3D11RenderTargetView* rtv, ID3D11DepthStencilView* dsv); + protected: virtual void setTileOrigin(S32 xPos, S32 yPos); -public: +public: GDrawTexture *getSubstitutionTexture(int textureId); void destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle); public: void shutdown(); }; - -extern ConsoleUIController ui; \ No newline at end of file diff --git a/Minecraft.Client/Windows64/Windows64_Xuid.h b/Minecraft.Client/Windows64/Windows64_Xuid.h index aa88f296f..f5fd62b90 100644 --- a/Minecraft.Client/Windows64/Windows64_Xuid.h +++ b/Minecraft.Client/Windows64/Windows64_Xuid.h @@ -186,6 +186,29 @@ namespace Win64Xuid return xuid; } + inline PlayerUID DeriveXuidForPad(PlayerUID baseXuid, int iPad) + { + if (iPad == 0) + return baseXuid; + + // Deterministic per-pad XUID: hash the base XUID with the pad number. + // Produces a fully unique 64-bit value with no risk of overlap. + // Suggested by rtm516 to avoid adjacent-integer collisions from the old "+ iPad" approach. + uint64_t raw = Mix64((uint64_t)baseXuid + (uint64_t)iPad); + raw |= 0x8000000000000000ULL; // keep high bit set like all our XUIDs + + PlayerUID xuid = (PlayerUID)raw; + if (!IsPersistedUidValid(xuid)) + { + raw ^= 0x0100000000000001ULL; + xuid = (PlayerUID)raw; + } + if (!IsPersistedUidValid(xuid)) + xuid = (PlayerUID)(0xD15EA5E000000001ULL + iPad); + + return xuid; + } + inline PlayerUID ResolvePersistentXuid() { // Process-local cache: uid.dat is immutable during runtime and this path is hot. diff --git a/Minecraft.Client/Windows64/XML/ATGXmlParser.h b/Minecraft.Client/Windows64/XML/ATGXmlParser.h index 75142e3e3..12f597372 100644 --- a/Minecraft.Client/Windows64/XML/ATGXmlParser.h +++ b/Minecraft.Client/Windows64/XML/ATGXmlParser.h @@ -138,7 +138,7 @@ private: DWORD m_dwCharsTotal; DWORD m_dwCharsConsumed; - BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing NULL + BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing nullptr WCHAR m_pWriteBuf[ XML_WRITE_BUFFER_SIZE ]; BYTE* m_pReadPtr; diff --git a/Minecraft.Client/Windows64Media/DLC/LittleBigPlanet/Skins.pck b/Minecraft.Client/Windows64Media/DLC/LittleBigPlanet/Skins.pck new file mode 100644 index 000000000..07df720dc Binary files /dev/null and b/Minecraft.Client/Windows64Media/DLC/LittleBigPlanet/Skins.pck differ diff --git a/Minecraft.Client/Windows64Media/Media/languages.loc b/Minecraft.Client/Windows64Media/Media/languages.loc index e3d9162b0..3fb5b1a06 100644 Binary files a/Minecraft.Client/Windows64Media/Media/languages.loc and b/Minecraft.Client/Windows64Media/Media/languages.loc differ diff --git a/Minecraft.Client/Windows64Media/loc/stringsGeneric.xml b/Minecraft.Client/Windows64Media/loc/stringsGeneric.xml index 36b521dd0..b5e58a9b6 100644 --- a/Minecraft.Client/Windows64Media/loc/stringsGeneric.xml +++ b/Minecraft.Client/Windows64Media/loc/stringsGeneric.xml @@ -8811,4 +8811,7 @@ All Ender Chests in a world are linked. Items placed into an Ender Chest are acc Cure + + Exit Minecraft + \ No newline at end of file diff --git a/Minecraft.Client/Windows64Media/strings.h b/Minecraft.Client/Windows64Media/strings.h index 63e3a7f4e..19a50eeeb 100644 --- a/Minecraft.Client/Windows64Media/strings.h +++ b/Minecraft.Client/Windows64Media/strings.h @@ -1,7 +1,7 @@ #pragma once // Auto-generated by StringTable builder — do not edit manually. // Source language: en-US -// Total strings: 2286 +// Total strings: 2287 #define IDS_NULL 0 #define IDS_OK 1 @@ -2165,127 +2165,128 @@ #define IDS_TUTORIAL_TASK_MINECART_PUSHING 2159 #define IDS_CONNECTION_FAILED_NO_SD_SPLITSCREEN 2160 #define IDS_TOOLTIPS_CURE 2161 -#define IDS_LANG_SYSTEM 2162 -#define IDS_LANG_ENGLISH 2163 -#define IDS_LANG_GERMAN 2164 -#define IDS_LANG_SPANISH 2165 -#define IDS_LANG_SPANISH_SPAIN 2166 -#define IDS_LANG_SPANISH_LATIN_AMERICA 2167 -#define IDS_LANG_FRENCH 2168 -#define IDS_LANG_ITALIAN 2169 -#define IDS_LANG_PORTUGUESE 2170 -#define IDS_LANG_PORTUGUESE_PORTUGAL 2171 -#define IDS_LANG_PORTUGUESE_BRAZIL 2172 -#define IDS_LANG_JAPANESE 2173 -#define IDS_LANG_KOREAN 2174 -#define IDS_LANG_CHINESE_TRADITIONAL 2175 -#define IDS_LANG_CHINESE_SIMPLIFIED 2176 -#define IDS_LANG_DANISH 2177 -#define IDS_LANG_FINISH 2178 -#define IDS_LANG_DUTCH 2179 -#define IDS_LANG_POLISH 2180 -#define IDS_LANG_RUSSIAN 2181 -#define IDS_LANG_SWEDISH 2182 -#define IDS_LANG_NORWEGIAN 2183 -#define IDS_LANG_GREEK 2184 -#define IDS_LANG_TURKISH 2185 -#define IDS_LEADERBOARD_KILLS_EASY 2186 -#define IDS_LEADERBOARD_KILLS_NORMAL 2187 -#define IDS_LEADERBOARD_KILLS_HARD 2188 -#define IDS_LEADERBOARD_MINING_BLOCKS_PEACEFUL 2189 -#define IDS_LEADERBOARD_MINING_BLOCKS_EASY 2190 -#define IDS_LEADERBOARD_MINING_BLOCKS_NORMAL 2191 -#define IDS_LEADERBOARD_MINING_BLOCKS_HARD 2192 -#define IDS_LEADERBOARD_FARMING_PEACEFUL 2193 -#define IDS_LEADERBOARD_FARMING_EASY 2194 -#define IDS_LEADERBOARD_FARMING_NORMAL 2195 -#define IDS_LEADERBOARD_FARMING_HARD 2196 -#define IDS_LEADERBOARD_TRAVELLING_PEACEFUL 2197 -#define IDS_LEADERBOARD_TRAVELLING_EASY 2198 -#define IDS_LEADERBOARD_TRAVELLING_NORMAL 2199 -#define IDS_LEADERBOARD_TRAVELLING_HARD 2200 -#define IDS_TIPS_GAMETIP_0 2201 -#define IDS_TIPS_GAMETIP_1 2202 -#define IDS_TIPS_GAMETIP_48 2203 -#define IDS_TIPS_GAMETIP_44 2204 -#define IDS_TIPS_GAMETIP_45 2205 -#define IDS_TIPS_TRIVIA_4 2206 -#define IDS_TIPS_TRIVIA_17 2207 -#define IDS_HOW_TO_PLAY_MULTIPLAYER 2208 -#define IDS_HOW_TO_PLAY_SOCIALMEDIA 2209 -#define IDS_HOW_TO_PLAY_CREATIVE 2210 -#define IDS_TUTORIAL_TASK_FLY 2211 -#define IDS_TOOLTIPS_SELECTDEVICE 2212 -#define IDS_TOOLTIPS_CHANGEDEVICE 2213 -#define IDS_TOOLTIPS_VIEW_GAMERCARD 2214 -#define IDS_TOOLTIPS_VIEW_GAMERPROFILE 2215 -#define IDS_TOOLTIPS_INVITE_PARTY 2216 -#define IDS_CONFIRM_START_CREATIVE 2217 -#define IDS_CONFIRM_START_SAVEDINCREATIVE 2218 -#define IDS_CONFIRM_START_SAVEDINCREATIVE_CONTINUE 2219 -#define IDS_CONFIRM_START_HOST_PRIVILEGES 2220 -#define IDS_CONNECTION_LOST_LIVE 2221 -#define IDS_CONNECTION_LOST_LIVE_NO_EXIT 2222 -#define IDS_AWARD_AVATAR1 2223 -#define IDS_AWARD_AVATAR2 2224 -#define IDS_AWARD_AVATAR3 2225 -#define IDS_AWARD_THEME 2226 -#define IDS_UNLOCK_ACHIEVEMENT_TEXT 2227 -#define IDS_UNLOCK_AVATAR_TEXT 2228 -#define IDS_UNLOCK_GAMERPIC_TEXT 2229 -#define IDS_UNLOCK_THEME_TEXT 2230 -#define IDS_UNLOCK_ACCEPT_INVITE 2231 -#define IDS_UNLOCK_GUEST_TEXT 2232 -#define IDS_LEADERBOARD_GAMERTAG 2233 -#define IDS_GROUPNAME_POTIONS_480 2234 -#define IDS_RETURNEDTOTITLESCREEN_TEXT 2235 -#define IDS_TRIALOVER_TEXT 2236 -#define IDS_FATAL_ERROR_TEXT 2237 -#define IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT 2238 -#define IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT 2239 -#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL 2240 -#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL 2241 -#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_REMOTE 2242 -#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE 2243 -#define IDS_SAVE_ICON_MESSAGE 2244 -#define IDS_GAMEOPTION_HOST_PRIVILEGES 2245 -#define IDS_CHECKBOX_DISPLAY_SPLITSCREENGAMERTAGS 2246 -#define IDS_ACHIEVEMENTS 2247 -#define IDS_LABEL_GAMERTAGS 2248 -#define IDS_IN_GAME_GAMERTAGS 2249 -#define IDS_SOCIAL_DEFAULT_DESCRIPTION 2250 -#define IDS_TITLE_UPDATE_NAME 2251 -#define IDS_PLATFORM_NAME 2252 -#define IDS_BACK_BUTTON 2253 -#define IDS_HOST_OPTION_DISABLES_ACHIEVEMENTS 2254 -#define IDS_KICK_PLAYER_DESCRIPTION 2255 -#define IDS_USING_TRIAL_TEXUREPACK_WARNING 2256 -#define IDS_WORLD_SIZE_TITLE_SMALL 2257 -#define IDS_WORLD_SIZE_TITLE_MEDIUM 2258 -#define IDS_WORLD_SIZE_TITLE_LARGE 2259 -#define IDS_WORLD_SIZE_TITLE_CLASSIC 2260 -#define IDS_WORLD_SIZE 2261 -#define IDS_GAMEOPTION_WORLD_SIZE 2262 -#define IDS_DISABLE_SAVING 2263 -#define IDS_GAMEOPTION_DISABLE_SAVING 2264 -#define IDS_RICHPRESENCE_GAMESTATE 2265 -#define IDS_RICHPRESENCE_IDLE 2266 -#define IDS_RICHPRESENCE_MENUS 2267 -#define IDS_RICHPRESENCE_MULTIPLAYER 2268 -#define IDS_RICHPRESENCE_MULTIPLAYEROFFLINE 2269 -#define IDS_RICHPRESENCE_MULTIPLAYER_1P 2270 -#define IDS_RICHPRESENCE_MULTIPLAYER_1POFFLINE 2271 -#define IDS_RICHPRESENCESTATE_BLANK 2272 -#define IDS_RICHPRESENCESTATE_RIDING_PIG 2273 -#define IDS_RICHPRESENCESTATE_RIDING_MINECART 2274 -#define IDS_RICHPRESENCESTATE_BOATING 2275 -#define IDS_RICHPRESENCESTATE_FISHING 2276 -#define IDS_RICHPRESENCESTATE_CRAFTING 2277 -#define IDS_RICHPRESENCESTATE_FORGING 2278 -#define IDS_RICHPRESENCESTATE_NETHER 2279 -#define IDS_RICHPRESENCESTATE_CD 2280 -#define IDS_RICHPRESENCESTATE_MAP 2281 -#define IDS_RICHPRESENCESTATE_ENCHANTING 2282 -#define IDS_RICHPRESENCESTATE_BREWING 2283 -#define IDS_RICHPRESENCESTATE_ANVIL 2284 -#define IDS_RICHPRESENCESTATE_TRADING 2285 +#define IDS_WINDOWS_EXIT 2162 +#define IDS_LANG_SYSTEM 2163 +#define IDS_LANG_ENGLISH 2164 +#define IDS_LANG_GERMAN 2165 +#define IDS_LANG_SPANISH 2166 +#define IDS_LANG_SPANISH_SPAIN 2167 +#define IDS_LANG_SPANISH_LATIN_AMERICA 2168 +#define IDS_LANG_FRENCH 2169 +#define IDS_LANG_ITALIAN 2170 +#define IDS_LANG_PORTUGUESE 2171 +#define IDS_LANG_PORTUGUESE_PORTUGAL 2172 +#define IDS_LANG_PORTUGUESE_BRAZIL 2173 +#define IDS_LANG_JAPANESE 2174 +#define IDS_LANG_KOREAN 2175 +#define IDS_LANG_CHINESE_TRADITIONAL 2176 +#define IDS_LANG_CHINESE_SIMPLIFIED 2177 +#define IDS_LANG_DANISH 2178 +#define IDS_LANG_FINISH 2179 +#define IDS_LANG_DUTCH 2180 +#define IDS_LANG_POLISH 2181 +#define IDS_LANG_RUSSIAN 2182 +#define IDS_LANG_SWEDISH 2183 +#define IDS_LANG_NORWEGIAN 2184 +#define IDS_LANG_GREEK 2185 +#define IDS_LANG_TURKISH 2186 +#define IDS_LEADERBOARD_KILLS_EASY 2187 +#define IDS_LEADERBOARD_KILLS_NORMAL 2188 +#define IDS_LEADERBOARD_KILLS_HARD 2189 +#define IDS_LEADERBOARD_MINING_BLOCKS_PEACEFUL 2190 +#define IDS_LEADERBOARD_MINING_BLOCKS_EASY 2191 +#define IDS_LEADERBOARD_MINING_BLOCKS_NORMAL 2192 +#define IDS_LEADERBOARD_MINING_BLOCKS_HARD 2193 +#define IDS_LEADERBOARD_FARMING_PEACEFUL 2194 +#define IDS_LEADERBOARD_FARMING_EASY 2195 +#define IDS_LEADERBOARD_FARMING_NORMAL 2196 +#define IDS_LEADERBOARD_FARMING_HARD 2197 +#define IDS_LEADERBOARD_TRAVELLING_PEACEFUL 2198 +#define IDS_LEADERBOARD_TRAVELLING_EASY 2199 +#define IDS_LEADERBOARD_TRAVELLING_NORMAL 2200 +#define IDS_LEADERBOARD_TRAVELLING_HARD 2201 +#define IDS_TIPS_GAMETIP_0 2202 +#define IDS_TIPS_GAMETIP_1 2203 +#define IDS_TIPS_GAMETIP_48 2204 +#define IDS_TIPS_GAMETIP_44 2205 +#define IDS_TIPS_GAMETIP_45 2206 +#define IDS_TIPS_TRIVIA_4 2207 +#define IDS_TIPS_TRIVIA_17 2208 +#define IDS_HOW_TO_PLAY_MULTIPLAYER 2209 +#define IDS_HOW_TO_PLAY_SOCIALMEDIA 2210 +#define IDS_HOW_TO_PLAY_CREATIVE 2211 +#define IDS_TUTORIAL_TASK_FLY 2212 +#define IDS_TOOLTIPS_SELECTDEVICE 2213 +#define IDS_TOOLTIPS_CHANGEDEVICE 2214 +#define IDS_TOOLTIPS_VIEW_GAMERCARD 2215 +#define IDS_TOOLTIPS_VIEW_GAMERPROFILE 2216 +#define IDS_TOOLTIPS_INVITE_PARTY 2217 +#define IDS_CONFIRM_START_CREATIVE 2218 +#define IDS_CONFIRM_START_SAVEDINCREATIVE 2219 +#define IDS_CONFIRM_START_SAVEDINCREATIVE_CONTINUE 2220 +#define IDS_CONFIRM_START_HOST_PRIVILEGES 2221 +#define IDS_CONNECTION_LOST_LIVE 2222 +#define IDS_CONNECTION_LOST_LIVE_NO_EXIT 2223 +#define IDS_AWARD_AVATAR1 2224 +#define IDS_AWARD_AVATAR2 2225 +#define IDS_AWARD_AVATAR3 2226 +#define IDS_AWARD_THEME 2227 +#define IDS_UNLOCK_ACHIEVEMENT_TEXT 2228 +#define IDS_UNLOCK_AVATAR_TEXT 2229 +#define IDS_UNLOCK_GAMERPIC_TEXT 2230 +#define IDS_UNLOCK_THEME_TEXT 2231 +#define IDS_UNLOCK_ACCEPT_INVITE 2232 +#define IDS_UNLOCK_GUEST_TEXT 2233 +#define IDS_LEADERBOARD_GAMERTAG 2234 +#define IDS_GROUPNAME_POTIONS_480 2235 +#define IDS_RETURNEDTOTITLESCREEN_TEXT 2236 +#define IDS_TRIALOVER_TEXT 2237 +#define IDS_FATAL_ERROR_TEXT 2238 +#define IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT 2239 +#define IDS_NO_MULTIPLAYER_PRIVILEGE_HOST_TEXT 2240 +#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL 2241 +#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL 2242 +#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_REMOTE 2243 +#define IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_CREATE 2244 +#define IDS_SAVE_ICON_MESSAGE 2245 +#define IDS_GAMEOPTION_HOST_PRIVILEGES 2246 +#define IDS_CHECKBOX_DISPLAY_SPLITSCREENGAMERTAGS 2247 +#define IDS_ACHIEVEMENTS 2248 +#define IDS_LABEL_GAMERTAGS 2249 +#define IDS_IN_GAME_GAMERTAGS 2250 +#define IDS_SOCIAL_DEFAULT_DESCRIPTION 2251 +#define IDS_TITLE_UPDATE_NAME 2252 +#define IDS_PLATFORM_NAME 2253 +#define IDS_BACK_BUTTON 2254 +#define IDS_HOST_OPTION_DISABLES_ACHIEVEMENTS 2255 +#define IDS_KICK_PLAYER_DESCRIPTION 2256 +#define IDS_USING_TRIAL_TEXUREPACK_WARNING 2257 +#define IDS_WORLD_SIZE_TITLE_SMALL 2258 +#define IDS_WORLD_SIZE_TITLE_MEDIUM 2259 +#define IDS_WORLD_SIZE_TITLE_LARGE 2260 +#define IDS_WORLD_SIZE_TITLE_CLASSIC 2261 +#define IDS_WORLD_SIZE 2262 +#define IDS_GAMEOPTION_WORLD_SIZE 2263 +#define IDS_DISABLE_SAVING 2264 +#define IDS_GAMEOPTION_DISABLE_SAVING 2265 +#define IDS_RICHPRESENCE_GAMESTATE 2266 +#define IDS_RICHPRESENCE_IDLE 2267 +#define IDS_RICHPRESENCE_MENUS 2268 +#define IDS_RICHPRESENCE_MULTIPLAYER 2269 +#define IDS_RICHPRESENCE_MULTIPLAYEROFFLINE 2270 +#define IDS_RICHPRESENCE_MULTIPLAYER_1P 2271 +#define IDS_RICHPRESENCE_MULTIPLAYER_1POFFLINE 2272 +#define IDS_RICHPRESENCESTATE_BLANK 2273 +#define IDS_RICHPRESENCESTATE_RIDING_PIG 2274 +#define IDS_RICHPRESENCESTATE_RIDING_MINECART 2275 +#define IDS_RICHPRESENCESTATE_BOATING 2276 +#define IDS_RICHPRESENCESTATE_FISHING 2277 +#define IDS_RICHPRESENCESTATE_CRAFTING 2278 +#define IDS_RICHPRESENCESTATE_FORGING 2279 +#define IDS_RICHPRESENCESTATE_NETHER 2280 +#define IDS_RICHPRESENCESTATE_CD 2281 +#define IDS_RICHPRESENCESTATE_MAP 2282 +#define IDS_RICHPRESENCESTATE_ENCHANTING 2283 +#define IDS_RICHPRESENCESTATE_BREWING 2284 +#define IDS_RICHPRESENCESTATE_ANVIL 2285 +#define IDS_RICHPRESENCESTATE_TRADING 2286 diff --git a/Minecraft.Client/WitchRenderer.cpp b/Minecraft.Client/WitchRenderer.cpp index 5e0f2b103..ec2b8a76f 100644 --- a/Minecraft.Client/WitchRenderer.cpp +++ b/Minecraft.Client/WitchRenderer.cpp @@ -18,7 +18,7 @@ void WitchRenderer::render(shared_ptr entity, double x, double y, double shared_ptr item = mob->getCarriedItem(); - witchModel->holdingItem = item != NULL; + witchModel->holdingItem = item != nullptr; MobRenderer::render(mob, x, y, z, rot, a); } @@ -38,7 +38,7 @@ void WitchRenderer::additionalRendering(shared_ptr entity, float a shared_ptr item = mob->getCarriedItem(); - if (item != NULL) + if (item != nullptr) { glPushMatrix(); diff --git a/Minecraft.Client/WitherBossRenderer.cpp b/Minecraft.Client/WitherBossRenderer.cpp index 254a00bc7..e358c6dab 100644 --- a/Minecraft.Client/WitherBossRenderer.cpp +++ b/Minecraft.Client/WitherBossRenderer.cpp @@ -48,7 +48,7 @@ void WitherBossRenderer::scale(shared_ptr _mob, float a) int inTicks = mob->getInvulnerableTicks(); if (inTicks > 0) { - float scale = 2.0f - (((float) inTicks - a) / (SharedConstants::TICKS_PER_SECOND * 11)) * .5f; + float scale = 2.0f - ((static_cast(inTicks) - a) / (SharedConstants::TICKS_PER_SECOND * 11)) * .5f; glScalef(scale, scale, scale); } else diff --git a/Minecraft.Client/WitherSkullRenderer.cpp b/Minecraft.Client/WitherSkullRenderer.cpp index 878735740..5f08b5b67 100644 --- a/Minecraft.Client/WitherSkullRenderer.cpp +++ b/Minecraft.Client/WitherSkullRenderer.cpp @@ -19,7 +19,7 @@ void WitherSkullRenderer::render(shared_ptr entity, double x, double y, float headRot = rotlerp(entity->yRotO, entity->yRot, a); float headRotx = entity->xRotO + (entity->xRot - entity->xRotO) * a; - glTranslatef((float) x, (float) y, (float) z); + glTranslatef(static_cast(x), static_cast(y), static_cast(z)); float scale = 1 / 16.0f; glEnable(GL_RESCALE_NORMAL); diff --git a/Minecraft.Client/Xbox/4JLibs/inc/4J_Input.h b/Minecraft.Client/Xbox/4JLibs/inc/4J_Input.h index 120e9c7b5..6d504b63e 100644 --- a/Minecraft.Client/Xbox/4JLibs/inc/4J_Input.h +++ b/Minecraft.Client/Xbox/4JLibs/inc/4J_Input.h @@ -98,8 +98,8 @@ public: void SetMenuDisplayed(int iPad, bool bVal); - EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,CXuiStringTable *pStringTable=NULL); - EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,CXuiStringTable *pStringTable=NULL); + EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,CXuiStringTable *pStringTable=nullptr); + EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,CXuiStringTable *pStringTable=nullptr); // Online check strings against offensive list - TCR 92 // TCR # 092 CMTV Player Text String Verification diff --git a/Minecraft.Client/Xbox/4JLibs/inc/4J_Profile.h b/Minecraft.Client/Xbox/4JLibs/inc/4J_Profile.h index 28e717e8d..524d94173 100644 --- a/Minecraft.Client/Xbox/4JLibs/inc/4J_Profile.h +++ b/Minecraft.Client/Xbox/4JLibs/inc/4J_Profile.h @@ -96,7 +96,7 @@ public: // ACHIEVEMENTS & AWARDS void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); + CXuiStringTable*pStringTable=nullptr, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=nullptr, unsigned int uiThemeSize=0L); int GetAwardId(int iAwardNumber); eAwardType GetAwardType(int iAwardNumber); bool CanBeAwarded(int iQuadrant, int iAwardNumber); diff --git a/Minecraft.Client/Xbox/4JLibs/inc/4J_Render.h b/Minecraft.Client/Xbox/4JLibs/inc/4J_Render.h index 5f113d5d7..613486f0c 100644 --- a/Minecraft.Client/Xbox/4JLibs/inc/4J_Render.h +++ b/Minecraft.Client/Xbox/4JLibs/inc/4J_Render.h @@ -116,7 +116,7 @@ public: void Initialise(IDirect3DDevice9 *pDevice); void InitialiseContext(); void Present(); - void Clear(int flags, D3DRECT *pRect = NULL); + void Clear(int flags, D3DRECT *pRect = nullptr); void SetClearColour(D3DCOLOR colour); bool IsWidescreen(); bool IsHiDef(); diff --git a/Minecraft.Client/Xbox/4JLibs/inc/4J_Storage.h b/Minecraft.Client/Xbox/4JLibs/inc/4J_Storage.h index 2ba905668..7ae051939 100644 --- a/Minecraft.Client/Xbox/4JLibs/inc/4J_Storage.h +++ b/Minecraft.Client/Xbox/4JLibs/inc/4J_Storage.h @@ -217,7 +217,7 @@ public: // Messages C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, - int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=NULL,LPVOID lpParam=NULL, CXuiStringTable *pStringTable=NULL, WCHAR *pwchFormatString=NULL,DWORD dwFocusButton=0); + int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=nullptr,LPVOID lpParam=nullptr, CXuiStringTable *pStringTable=nullptr, WCHAR *pwchFormatString=nullptr,DWORD dwFocusButton=0); void CancelMessageBoxRequest(); C4JStorage::EMessageResult GetMessageBoxResult(); @@ -239,7 +239,7 @@ public: unsigned int GetSaveSize(); void GetSaveData(void *pvData,unsigned int *puiBytes); PVOID AllocateSaveData(unsigned int uiBytes); - void SaveSaveData(unsigned int uiBytes,PBYTE pbThumbnail=NULL,DWORD cbThumbnail=0,PBYTE pbTextData=NULL, DWORD dwTextLen=0); + void SaveSaveData(unsigned int uiBytes,PBYTE pbThumbnail=nullptr,DWORD cbThumbnail=0,PBYTE pbTextData=nullptr, DWORD dwTextLen=0); void CopySaveDataToNewSave(PBYTE pbThumbnail,DWORD cbThumbnail,WCHAR *wchNewName,int ( *Func)(LPVOID lpParam, bool), LPVOID lpParam); void SetSaveDeviceSelected(unsigned int uiPad,bool bSelected); bool GetSaveDeviceSelected(unsigned int iPad); @@ -271,27 +271,27 @@ public: C4JStorage::EDLCStatus GetInstalledDLC(int iPad,int( *Func)(LPVOID, int, int),LPVOID lpParam); XCONTENT_DATA& GetDLC(DWORD dw); - DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive=NULL); - DWORD UnmountInstalledDLC(LPCSTR szMountDrive=NULL); + DWORD MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive=nullptr); + DWORD UnmountInstalledDLC(LPCSTR szMountDrive=nullptr); // Global title storage C4JStorage::ETMSStatus ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType, - WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int)=NULL,LPVOID lpParam=NULL, int iAction=0); + WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int)=nullptr,LPVOID lpParam=nullptr, int iAction=0); bool WriteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename,BYTE *pBuffer,DWORD dwBufferSize); bool DeleteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename); - void StoreTMSPathName(WCHAR *pwchName=NULL); + void StoreTMSPathName(WCHAR *pwchName=nullptr); // TMS++ - C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0); + C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); C4JStorage::ETMSStatus TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam, int iUserData=0); - C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)=NULL,LPVOID lpParam=NULL, int iUserData=0); - C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int iUserData=0); - C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int iUserData=0); + C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); + C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=nullptr,LPVOID lpParam=nullptr, int iUserData=0); + C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=nullptr, int iUserData=0); bool TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const wstring &Filename); unsigned int CRC(unsigned char *buf, int len); - C4JStorage::ETMSStatus TMSPP_WriteFileWithProgress(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0, - int( *CompletionFunc)(LPVOID,float fComplete)=NULL,LPVOID lpCompletionParam=NULL); + C4JStorage::ETMSStatus TMSPP_WriteFileWithProgress(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=nullptr,LPVOID lpParam=nullptr, int iUserData=0, + int( *CompletionFunc)(LPVOID,float fComplete)=nullptr,LPVOID lpCompletionParam=nullptr); void TMSPP_CancelWriteFileWithProgress(int iPad); HRESULT TMSPP_SetTitleGroupID(LPCSTR szGroupID); diff --git a/Minecraft.Client/Xbox/Audio/SoundEngine.cpp b/Minecraft.Client/Xbox/Audio/SoundEngine.cpp index b088150c9..9ba0e4dd8 100644 --- a/Minecraft.Client/Xbox/Audio/SoundEngine.cpp +++ b/Minecraft.Client/Xbox/Audio/SoundEngine.cpp @@ -12,16 +12,16 @@ #include "..\..\DLCTexturePack.h" -IXAudio2* g_pXAudio2 = NULL; // pointer to XAudio2 instance used by QNet and XACT -IXAudio2MasteringVoice* g_pXAudio2MasteringVoice = NULL; // pointer to XAudio2 mastering voice +IXAudio2* g_pXAudio2 = nullptr; // pointer to XAudio2 instance used by QNet and XACT +IXAudio2MasteringVoice* g_pXAudio2MasteringVoice = nullptr; // pointer to XAudio2 mastering voice -IXACT3Engine *SoundEngine::m_pXACT3Engine = NULL; -IXACT3WaveBank *SoundEngine::m_pWaveBank = NULL; -IXACT3WaveBank *SoundEngine::m_pWaveBank2 = NULL; -IXACT3WaveBank *SoundEngine::m_pStreamedWaveBank = NULL; -IXACT3WaveBank *SoundEngine::m_pStreamedWaveBankAdditional = NULL; -IXACT3SoundBank *SoundEngine::m_pSoundBank = NULL; -IXACT3SoundBank *SoundEngine::m_pSoundBank2 = NULL; +IXACT3Engine *SoundEngine::m_pXACT3Engine = nullptr; +IXACT3WaveBank *SoundEngine::m_pWaveBank = nullptr; +IXACT3WaveBank *SoundEngine::m_pWaveBank2 = nullptr; +IXACT3WaveBank *SoundEngine::m_pStreamedWaveBank = nullptr; +IXACT3WaveBank *SoundEngine::m_pStreamedWaveBankAdditional = nullptr; +IXACT3SoundBank *SoundEngine::m_pSoundBank = nullptr; +IXACT3SoundBank *SoundEngine::m_pSoundBank2 = nullptr; CRITICAL_SECTION SoundEngine::m_CS; X3DAUDIO_HANDLE SoundEngine::m_xact3dInstance; @@ -97,9 +97,9 @@ void SoundEngine::init(Options *pOptions) // 4J-PB - move this to the title update, since we've corrected it to allow sounds to be pitch varied when they weren't before HANDLE file; #ifdef _TU_BUILD - file = CreateFile("UPDATE:\\res\\audio\\Minecraft.xgs", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("UPDATE:\\res\\audio\\Minecraft.xgs", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else - file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\Minecraft.xgs", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\Minecraft.xgs", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -107,11 +107,11 @@ void SoundEngine::init(Options *pOptions) assert(false); return; } - DWORD dwFileSize = GetFileSize(file,NULL); + DWORD dwFileSize = GetFileSize(file,nullptr); DWORD bytesRead = 0; DWORD memFlags = MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_PHYSICAL); void *pvGlobalSettings = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvGlobalSettings,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvGlobalSettings,dwFileSize,&bytesRead,nullptr); CloseHandle(file); XACT_RUNTIME_PARAMETERS EngineParameters = {0}; @@ -161,7 +161,7 @@ void SoundEngine::init(Options *pOptions) // Create resident wave bank - leave memory for this managed by xact so it can free it - file = CreateFile("GAME:\\res\\audio\\resident.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\audio\\resident.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { app.FatalLoadError(); @@ -169,9 +169,9 @@ void SoundEngine::init(Options *pOptions) return; } - dwFileSize = GetFileSize(file,NULL); + dwFileSize = GetFileSize(file,nullptr); void *pvWaveBank = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvWaveBank,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvWaveBank,dwFileSize,&bytesRead,nullptr); CloseHandle(file); if ( FAILED( hr = m_pXACT3Engine->CreateInMemoryWaveBank( pvWaveBank, dwFileSize, XACT_FLAG_ENGINE_CREATE_MANAGEDATA, memFlags, &m_pWaveBank ) ) ) @@ -183,9 +183,9 @@ void SoundEngine::init(Options *pOptions) // 4J-PB - add new sounds wavebank #ifdef _TU_BUILD - file = CreateFile("UPDATE:\\res\\audio\\additional.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("UPDATE:\\res\\audio\\additional.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else - file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\additional.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\additional.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -194,9 +194,9 @@ void SoundEngine::init(Options *pOptions) return; } - dwFileSize = GetFileSize(file,NULL); + dwFileSize = GetFileSize(file,nullptr); void *pvWaveBank2 = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvWaveBank2,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvWaveBank2,dwFileSize,&bytesRead,nullptr); CloseHandle(file); if ( FAILED( hr = m_pXACT3Engine->CreateInMemoryWaveBank( pvWaveBank2, dwFileSize, XACT_FLAG_ENGINE_CREATE_MANAGEDATA, memFlags, &m_pWaveBank2 ) ) ) @@ -208,7 +208,7 @@ void SoundEngine::init(Options *pOptions) // Create streamed sound bank - file = CreateFile("GAME:\\res\\audio\\streamed.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL); + file = CreateFile("GAME:\\res\\audio\\streamed.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, nullptr); if( file == INVALID_HANDLE_VALUE ) { @@ -232,11 +232,11 @@ void SoundEngine::init(Options *pOptions) // Create streamed sound bank - //file = CreateFile("GAME:\\res\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL); + //file = CreateFile("GAME:\\res\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, nullptr); #ifdef _TU_BUILD - file = CreateFile("UPDATE:\\res\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("UPDATE:\\res\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else - file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\AdditionalMusic.xwb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -259,11 +259,11 @@ void SoundEngine::init(Options *pOptions) // Create sound bank - leave memory for this managed by xact so it can free it // 4J-PB - updated for the TU - //file = CreateFile("GAME:\\res\\audio\\minecraft.xsb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + //file = CreateFile("GAME:\\res\\audio\\minecraft.xsb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #ifdef _TU_BUILD - file = CreateFile("UPDATE:\\res\\audio\\minecraft.xsb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("UPDATE:\\res\\audio\\minecraft.xsb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else - file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\minecraft.xsb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\minecraft.xsb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -271,9 +271,9 @@ void SoundEngine::init(Options *pOptions) assert(false); return; } - dwFileSize = GetFileSize(file,NULL); + dwFileSize = GetFileSize(file,nullptr); void *pvSoundBank = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvSoundBank,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvSoundBank,dwFileSize,&bytesRead,nullptr); CloseHandle(file); if ( FAILED( hr = m_pXACT3Engine->CreateSoundBank( pvSoundBank, dwFileSize, XACT_FLAG_ENGINE_CREATE_MANAGEDATA, memFlags, &m_pSoundBank ) ) ) @@ -286,9 +286,9 @@ void SoundEngine::init(Options *pOptions) // Create sound bank2 - leave memory for this managed by xact so it can free it #ifdef _TU_BUILD - file = CreateFile("UPDATE:\\res\\audio\\additional.xsb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("UPDATE:\\res\\audio\\additional.xsb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else - file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\additional.xsb", GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + file = CreateFile("GAME:\\res\\TitleUpdate\\audio\\additional.xsb", GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if( file == INVALID_HANDLE_VALUE ) { @@ -296,9 +296,9 @@ void SoundEngine::init(Options *pOptions) assert(false); return; } - dwFileSize = GetFileSize(file,NULL); + dwFileSize = GetFileSize(file,nullptr); void *pvSoundBank2 = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvSoundBank2,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvSoundBank2,dwFileSize,&bytesRead,nullptr); CloseHandle(file); if ( FAILED( hr = m_pXACT3Engine->CreateSoundBank( pvSoundBank2, dwFileSize, XACT_FLAG_ENGINE_CREATE_MANAGEDATA, memFlags, &m_pSoundBank2 ) ) ) @@ -324,7 +324,7 @@ void SoundEngine::CreateStreamingWavebank(const char *pchName, IXACT3WaveBank ** // Create streamed sound bank HRESULT hr; - HANDLE file = CreateFile(pchName, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL); + HANDLE file = CreateFile(pchName, GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, nullptr); if( file == INVALID_HANDLE_VALUE ) { @@ -350,7 +350,7 @@ void SoundEngine::CreateStreamingWavebank(const char *pchName, IXACT3WaveBank ** void SoundEngine::CreateSoundbank(const char *pchName, IXACT3SoundBank **ppSoundBank) { HRESULT hr; - HANDLE file = CreateFile(pchName, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFile(pchName, GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if( file == INVALID_HANDLE_VALUE ) { @@ -358,11 +358,11 @@ void SoundEngine::CreateSoundbank(const char *pchName, IXACT3SoundBank **ppSound assert(false); return; } - DWORD dwFileSize = GetFileSize(file,NULL); + DWORD dwFileSize = GetFileSize(file,nullptr); DWORD bytesRead = 0; DWORD memFlags = MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_PHYSICAL); void *pvSoundBank = XMemAlloc(dwFileSize, memFlags); - ReadFile(file,pvSoundBank,dwFileSize,&bytesRead,NULL); + ReadFile(file,pvSoundBank,dwFileSize,&bytesRead,nullptr); CloseHandle(file); if ( FAILED( hr = m_pXACT3Engine->CreateSoundBank( pvSoundBank, dwFileSize, XACT_FLAG_ENGINE_CREATE_MANAGEDATA, memFlags, ppSoundBank ) ) ) @@ -416,11 +416,11 @@ bool SoundEngine::isStreamingWavebankReady(IXACT3WaveBank *pWaveBank) void SoundEngine::XACTNotificationCallback( const XACT_NOTIFICATION* pNotification ) { - if(pNotification->pvContext!= NULL) + if(pNotification->pvContext!= nullptr) { if(pNotification->type==XACTNOTIFICATIONTYPE_WAVEBANKPREPARED) { - SoundEngine *pSoundEngine=(SoundEngine *)pNotification->pvContext; + SoundEngine *pSoundEngine=static_cast(pNotification->pvContext); if(pNotification->waveBank.pWaveBank==pSoundEngine->m_pStreamedWaveBank) { pSoundEngine->m_bStreamingWaveBank1Ready=true; @@ -446,7 +446,7 @@ char *SoundEngine::ConvertSoundPathToName(const wstring& name, bool bConvertSpac { wchar_t c = name[i]; if(c=='.') c='_'; - buf[i] = (char)c; + buf[i] = static_cast(c); } buf[name.length()] = 0; return buf; @@ -462,7 +462,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa bool bSoundbank1=(iSound<=eSoundType_STEP_SAND); - if( (m_pSoundBank == NULL ) || (m_pSoundBank2 == NULL))return; + if( (m_pSoundBank == nullptr ) || (m_pSoundBank2 == nullptr))return; if( currentSounds.size() > MAX_POLYPHONY ) { @@ -541,7 +541,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa soundInfo *info = new soundInfo(); info->idx = idx; - info->eSoundID = (eSOUND_TYPE)iSound; + info->eSoundID = static_cast(iSound); info->iSoundBank = bSoundbank1?0:1; info->x = x; info->y = y; @@ -570,7 +570,7 @@ void SoundEngine::playUI(int iSound, float, float) { bool bSoundBank1=(iSound<=eSoundType_STEP_SAND); - if( (m_pSoundBank == NULL ) || (m_pSoundBank2 == NULL)) return; + if( (m_pSoundBank == nullptr ) || (m_pSoundBank2 == nullptr)) return; if( currentSounds.size() > MAX_POLYPHONY ) { @@ -578,7 +578,7 @@ void SoundEngine::playUI(int iSound, float, float) } wstring name = wchSoundNames[iSound]; - char *xboxName = (char *)ConvertSoundPathToName(name); + char *xboxName = static_cast(ConvertSoundPathToName(name)); XACTINDEX idx = m_pSoundBank->GetCueIndex(xboxName); @@ -618,7 +618,7 @@ void SoundEngine::playUI(int iSound, float, float) // Add sound info just so we can detect end of this sound soundInfo *info = new soundInfo(); - info->eSoundID = (eSOUND_TYPE)0; + info->eSoundID = static_cast(0); info->iSoundBank = bSoundBank1?0:1; info->idx =idx; info->x = 0.0f; @@ -637,15 +637,15 @@ void SoundEngine::playUI(int iSound, float, float) void SoundEngine::playStreaming(const wstring& name, float x, float y, float z, float vol, float pitch, bool bMusicDelay) { - IXACT3SoundBank *pSoundBank=NULL; + IXACT3SoundBank *pSoundBank=nullptr; bool bSoundBank2=false; MemSect(34); - if(m_MusicInfo.pCue!=NULL) + if(m_MusicInfo.pCue!=nullptr) { m_MusicInfo.pCue->Stop(0); m_MusicInfo.pCue->Destroy(); - m_MusicInfo.pCue = NULL; + m_MusicInfo.pCue = nullptr; } m_MusicInfo.volume = 1.0f;//m_fMusicVolume; @@ -673,7 +673,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y, float z, for(unsigned int i=0;ilocalplayers[i]!=NULL) + if(pMinecraft->localplayers[i]!=nullptr) { if(pMinecraft->localplayers[i]->dimension==LevelData::DIMENSION_END) { @@ -701,7 +701,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y, float z, else { // get the dlc texture pack - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)pTexPack; + DLCTexturePack *pDLCTexPack=static_cast(pTexPack); pSoundBank=pDLCTexPack->m_pSoundBank; // check we can play the sound @@ -743,7 +743,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y, float z, { // printf("Sound prep failed\n"); m_musicIDX = XACTINDEX_INVALID; // don't do anything in the tick - m_MusicInfo.pCue=NULL; + m_MusicInfo.pCue=nullptr; MemSect(0); return; } @@ -774,7 +774,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y, float z, } void SoundEngine::playMusicTick() { - if( (m_pSoundBank == NULL ) || (m_pSoundBank2 == NULL)) return; + if( (m_pSoundBank == nullptr ) || (m_pSoundBank2 == nullptr)) return; if( m_musicIDX == XACTINDEX_INVALID ) { @@ -785,7 +785,7 @@ void SoundEngine::playMusicTick() // check to see if the sound has stopped playing DWORD state; HRESULT hr; - if(m_MusicInfo.pCue!=NULL) + if(m_MusicInfo.pCue!=nullptr) { if( FAILED( hr = m_MusicInfo.pCue->GetState(&state) ) ) { @@ -804,14 +804,14 @@ void SoundEngine::playMusicTick() if(GetIsPlayingStreamingGameMusic()) { - if(m_MusicInfo.pCue!=NULL) + if(m_MusicInfo.pCue!=nullptr) { bool playerInEnd = false; bool playerInNether=false; Minecraft *pMinecraft = Minecraft::GetInstance(); for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { - if(pMinecraft->localplayers[i]!=NULL) + if(pMinecraft->localplayers[i]!=nullptr) { if(pMinecraft->localplayers[i]->dimension==LevelData::DIMENSION_END) { @@ -852,7 +852,7 @@ void SoundEngine::playMusicTick() return; } - if(m_MusicInfo.pCue!=NULL) + if(m_MusicInfo.pCue!=nullptr) { update3DPosition(&m_MusicInfo, true); SetIsPlayingStreamingGameMusic(true); @@ -986,7 +986,7 @@ void SoundEngine::update3DPosition(SoundEngine::soundInfo *pInfo, bool bPlaceEmi void SoundEngine::tick(shared_ptr *players, float a) { - if( m_pXACT3Engine == NULL ) return; + if( m_pXACT3Engine == nullptr ) return; // Creater listener array from the local players int listenerCount = 0; @@ -995,13 +995,13 @@ void SoundEngine::tick(shared_ptr *players, float a) { for( int i = 0; i < 4; i++ ) { - if( players[i] != NULL ) + if( players[i] != nullptr ) { float yRot = players[i]->yRotO + (players[i]->yRot - players[i]->yRotO) * a; - m_listeners[listenerCount].Position.x = (float) (players[i]->xo + (players[i]->x - players[i]->xo) * a); - m_listeners[listenerCount].Position.y = (float) (players[i]->yo + (players[i]->y - players[i]->yo) * a); - m_listeners[listenerCount].Position.z = -(float) (players[i]->zo + (players[i]->z - players[i]->zo) * a); // Flipped sign of z as x3daudio is expecting left handed coord system + m_listeners[listenerCount].Position.x = static_cast(players[i]->xo + (players[i]->x - players[i]->xo) * a); + m_listeners[listenerCount].Position.y = static_cast(players[i]->yo + (players[i]->y - players[i]->yo) * a); + m_listeners[listenerCount].Position.z = -static_cast(players[i]->zo + (players[i]->z - players[i]->zo) * a); // Flipped sign of z as x3daudio is expecting left handed coord system float yCos = (float)cos(-yRot * Mth::RAD_TO_GRAD - PI); float ySin = (float)sin(-yRot * Mth::RAD_TO_GRAD - PI); diff --git a/Minecraft.Client/Xbox/Audio/SoundEngine.h b/Minecraft.Client/Xbox/Audio/SoundEngine.h index e2f22869b..77998d20c 100644 --- a/Minecraft.Client/Xbox/Audio/SoundEngine.h +++ b/Minecraft.Client/Xbox/Audio/SoundEngine.h @@ -77,31 +77,32 @@ class SoundEngine : public ConsoleSoundEngine #endif public: SoundEngine(); - virtual void destroy(); - virtual void play(int iSound, float x, float y, float z, float volume, float pitch); - virtual void playStreaming(const wstring& name, float x, float y , float z, float volume, float pitch, bool bMusicDelay=true); - virtual void playUI(int iSound, float volume, float pitch); - virtual void playMusicTick(); - virtual void updateMusicVolume(float fVal); - virtual void updateSystemMusicPlaying(bool isPlaying); - virtual void updateSoundEffectVolume(float fVal); - virtual void init(Options *); - virtual void tick(shared_ptr *players, float a); // 4J - updated to take array of local players rather than single one - virtual void add(const wstring& name, File *file); - virtual void addMusic(const wstring& name, File *file); - virtual void addStreaming(const wstring& name, File *file); + void destroy() override; + void play(int iSound, float x, float y, float z, float volume, float pitch) override; + void playStreaming(const wstring& name, float x, float y , float z, float volume, float pitch, bool bMusicDelay=true) override; + void playUI(int iSound, float volume, float pitch) override; + void playMusicTick() override; + void updateMusicVolume(float fVal) override; + void updateSystemMusicPlaying(bool isPlaying) override; + void updateSoundEffectVolume(float fVal) override; + void init(Options *) override; + void tick(shared_ptr *players, float a) override; // 4J - updated to take array of local players rather than single one + void add(const wstring& name, File *file) override; + void addMusic(const wstring& name, File *file) override; + void addStreaming(const wstring& name, File *file) override; #ifndef __PS3__ static void setXACTEngine( IXACT3Engine *pXACT3Engine); void CreateStreamingWavebank(const char *pchName, IXACT3WaveBank **ppStreamedWaveBank); void CreateSoundbank(const char *pchName, IXACT3SoundBank **ppSoundBank); #endif // __PS3__ - virtual char *ConvertSoundPathToName(const wstring& name, bool bConvertSpaces=false); + char *ConvertSoundPathToName(const wstring& name, bool bConvertSpaces=false) override; bool isStreamingWavebankReady(); // 4J Added #ifdef _XBOX bool isStreamingWavebankReady(IXACT3WaveBank *pWaveBank); #endif - int initAudioHardware(int iMinSpeakers) { return iMinSpeakers;} + int initAudioHardware(int iMinSpeakers) override + { return iMinSpeakers;} private: #ifndef __PS3__ diff --git a/Minecraft.Client/Xbox/Font/XUI_Font.cpp b/Minecraft.Client/Xbox/Font/XUI_Font.cpp index 8b1a624be..2262f3459 100644 --- a/Minecraft.Client/Xbox/Font/XUI_Font.cpp +++ b/Minecraft.Client/Xbox/Font/XUI_Font.cpp @@ -53,8 +53,8 @@ XUI_Font::~XUI_Font() VOID XUI_Font::GetTextExtent( const WCHAR* strText, FLOAT* pWidth, FLOAT* pHeight, BOOL bFirstLineOnly ) const { - assert( pWidth != NULL ); - assert( pHeight != NULL ); + assert( pWidth != nullptr ); + assert( pHeight != nullptr ); // Set default text extent in output parameters int iWidth = 0; @@ -146,8 +146,8 @@ VOID XUI_Font::Begin() //m_pFontTexture->GetLevelDesc( 0, &TextureDesc ); // Get the description // Set render state - assert(m_fontData->m_pFontTexture != NULL || m_fontData->m_iFontTexture > 0); - if(m_fontData->m_pFontTexture != NULL) + assert(m_fontData->m_pFontTexture != nullptr || m_fontData->m_iFontTexture > 0); + if(m_fontData->m_pFontTexture != nullptr) { pD3dDevice->SetTexture( 0, m_fontData->m_pFontTexture ); } @@ -236,7 +236,7 @@ VOID XUI_Font::DrawShadowText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, DW VOID XUI_Font::DrawText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, const WCHAR* strText, DWORD dwFlags, FLOAT fMaxPixelWidth, bool darken /*= false*/ ) { - if( NULL == strText ) return; + if( nullptr == strText ) return; if( L'\0' == strText[0] ) return; // 4J-PB - if we're in 480 widescreen mode, we need to ensure that the font characters are aligned on an even boundary if they are a 2x multiple @@ -244,21 +244,21 @@ VOID XUI_Font::DrawText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, { if(RenderManager.IsWidescreen()) { - int iScaleX=(int)m_fXScaleFactor; + int iScaleX=static_cast(m_fXScaleFactor); int iOriginX; if(iScaleX%2==0) { - iOriginX=(int)fOriginX; + iOriginX=static_cast(fOriginX); if(iOriginX%2==1) { fOriginX+=1.0f; } } - int iScaleY=(int)m_fYScaleFactor; + int iScaleY=static_cast(m_fYScaleFactor); int iOriginY; if(iScaleY%2==0) { - iOriginY=(int)fOriginY; + iOriginY=static_cast(fOriginY); if(iOriginY%2==1) { fOriginY+=1.0f; @@ -268,7 +268,7 @@ VOID XUI_Font::DrawText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, else { // 480 SD mode - y needs to be on a pixel boundary when multiplied by 1.5, so if it's an odd number, subtract 1/3 from it - int iOriginY=(int)fOriginY; + int iOriginY=static_cast(fOriginY); if(iOriginY%2==1) { fOriginY-=1.0f/3.0f; @@ -415,8 +415,8 @@ VOID XUI_Font::DrawText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, // Translate unprintable characters XUI_FontData::SChar sChar = m_fontData->getChar( letter ); - FLOAT fOffset = m_fXScaleFactor * ( FLOAT )sChar.getOffset(); - FLOAT fAdvance = m_fXScaleFactor * ( FLOAT )sChar.getWAdvance(); + FLOAT fOffset = m_fXScaleFactor * static_cast(sChar.getOffset()); + FLOAT fAdvance = m_fXScaleFactor * static_cast(sChar.getWAdvance()); // 4J Use the font max width otherwise scaling doesnt look right FLOAT fWidth = m_fXScaleFactor * (sChar.tu2() - sChar.tu1());//( FLOAT )pGlyph->wWidth; FLOAT fHeight = m_fYScaleFactor * m_fontData->getFontHeight(); @@ -450,10 +450,10 @@ VOID XUI_Font::DrawText( FLOAT fOriginX, FLOAT fOriginY, DWORD dwColor, // Add the vertices to draw this glyph - FLOAT tu1 = sChar.tu1() / (float)m_fontData->getImageWidth(); - FLOAT tv1 = sChar.tv1() / (float)m_fontData->getImageHeight(); - FLOAT tu2 = sChar.tu2() / (float)m_fontData->getImageWidth(); - FLOAT tv2 = sChar.tv2() / (float)m_fontData->getImageHeight(); + FLOAT tu1 = sChar.tu1() / static_cast(m_fontData->getImageWidth()); + FLOAT tv1 = sChar.tv1() / static_cast(m_fontData->getImageHeight()); + FLOAT tu2 = sChar.tu2() / static_cast(m_fontData->getImageWidth()); + FLOAT tv2 = sChar.tv2() / static_cast(m_fontData->getImageHeight()); Tesselator *t = Tesselator::getInstance(); t->begin(); diff --git a/Minecraft.Client/Xbox/Font/XUI_FontData.cpp b/Minecraft.Client/Xbox/Font/XUI_FontData.cpp index 7a70cdfbb..88d77d090 100644 --- a/Minecraft.Client/Xbox/Font/XUI_FontData.cpp +++ b/Minecraft.Client/Xbox/Font/XUI_FontData.cpp @@ -68,7 +68,7 @@ float XUI_FontData::SChar::getMinX() float XUI_FontData::SChar::getMaxX() { - return (float) m_parent->m_fontData->getFontData()->m_uiGlyphWidth; + return static_cast(m_parent->m_fontData->getFontData()->m_uiGlyphWidth); } float XUI_FontData::SChar::getMinY() @@ -83,7 +83,7 @@ float XUI_FontData::SChar::getMaxY() float XUI_FontData::SChar::getAdvance() { - return (float) m_parent->m_fontData->getWidth(m_glyphId); + return static_cast(m_parent->m_fontData->getWidth(m_glyphId)); } int XUI_FontData::SChar::getGlyphId() @@ -157,11 +157,11 @@ XUI_FontData::SChar XUI_FontData::getChar(const wchar_t strChar) //-------------------------------------------------------------------------------------- XUI_FontData::XUI_FontData() { - m_pFontTexture = NULL; + m_pFontTexture = nullptr; m_iFontTexture = -1; m_dwNumGlyphs = 0L; - m_Glyphs = NULL; + m_Glyphs = nullptr; m_cMaxGlyph = 0; @@ -201,12 +201,12 @@ HRESULT XUI_FontData::Create( SFontData &sfontdata ) m_fontData = new CFontData( sfontdata, rawPixels.data ); - if (rawPixels.data != NULL) delete [] rawPixels.data; + if (rawPixels.data != nullptr) delete [] rawPixels.data; #if 0 { // 4J-JEV: Load in FontData (ABC) file, and initialize member variables from it. - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); //wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/font/Mojangles_10.abc"); wsprintfW(szResourceLocator,L"section://%X,%s#%s%s%s",c_ModuleHandle,L"media", L"media/font/",strFontFileName.c_str(),L".abc"); @@ -349,7 +349,7 @@ HRESULT XUI_FontData::Create( int iFontTexture, const VOID* pFontData ) //-------------------------------------------------------------------------------------- VOID XUI_FontData::Destroy() { - if(m_pFontTexture!=NULL) + if(m_pFontTexture!=nullptr) { m_pFontTexture->Release(); delete m_pFontTexture; @@ -357,7 +357,7 @@ VOID XUI_FontData::Destroy() m_fontData->release(); - m_pFontTexture = NULL; + m_pFontTexture = nullptr; m_dwNumGlyphs = 0L; m_cMaxGlyph = 0; diff --git a/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp b/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp index d708af791..f6619fd5f 100644 --- a/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp +++ b/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp @@ -36,7 +36,7 @@ VOID XUI_FontRenderer::Term() HRESULT XUI_FontRenderer::GetCaps( DWORD * pdwCaps ) { - if( pdwCaps != NULL ) + if( pdwCaps != nullptr ) { // setting this means XUI calls the DrawCharsToDevice method *pdwCaps = XUI_FONT_RENDERER_CAP_INTERNAL_GLYPH_CACHE | XUI_FONT_RENDERER_CAP_POINT_SIZE_RESPECTED | XUI_FONT_RENDERER_STYLE_DROPSHADOW; @@ -50,7 +50,7 @@ HRESULT XUI_FontRenderer::CreateFont( const TypefaceDescriptor * pTypefaceDescri //float fXuiSize = fPointSize * ( 16.0f / 16.0f ); fXuiSize /= 4.0f; fXuiSize = floor( fXuiSize ); - int xuiSize = (int)(fXuiSize * 4.0f); + int xuiSize = static_cast(fXuiSize * 4.0f); if( xuiSize < 1 ) xuiSize = 8; // 4J Stu - We have fonts based on multiples of 8 or 12 @@ -60,8 +60,8 @@ HRESULT XUI_FontRenderer::CreateFont( const TypefaceDescriptor * pTypefaceDescri //app.DebugPrintf("point size is: %f, xuiSize is: %d\n", fPointSize, xuiSize); - XUI_Font *font = NULL; - XUI_FontData *fontData = NULL; + XUI_Font *font = nullptr; + XUI_FontData *fontData = nullptr; FLOAT scale = 1; eFontData efontdata; @@ -77,17 +77,17 @@ HRESULT XUI_FontRenderer::CreateFont( const TypefaceDescriptor * pTypefaceDescri } font = m_loadedFonts[efontdata][scale]; - if (font == NULL) + if (font == nullptr) { fontData = m_loadedFontData[efontdata]; - if (fontData == NULL) + if (fontData == nullptr) { SFontData *sfontdata; switch (efontdata) { case eFontData_Mojangles_7: sfontdata = &SFontData::Mojangles_7; break; case eFontData_Mojangles_11: sfontdata = &SFontData::Mojangles_11; break; - default: sfontdata = NULL; break; + default: sfontdata = nullptr; break; } fontData = new XUI_FontData(); @@ -101,14 +101,14 @@ HRESULT XUI_FontRenderer::CreateFont( const TypefaceDescriptor * pTypefaceDescri } font->IncRefCount(); - *phFont = (HFONTOBJ)font; + *phFont = static_cast(font); return S_OK; } VOID XUI_FontRenderer::ReleaseFont( HFONTOBJ hFont ) { - XUI_Font *xuiFont = (XUI_Font*) hFont; - if (xuiFont != NULL) + XUI_Font *xuiFont = static_cast(hFont); + if (xuiFont != nullptr) { xuiFont->DecRefCount(); if (xuiFont->refCount <= 0) @@ -125,7 +125,7 @@ HRESULT XUI_FontRenderer::GetFontMetrics( HFONTOBJ hFont, XUIFontMetrics *pFontM { if( hFont == 0 || pFontMetrics == 0 ) return E_INVALIDARG; - XUI_Font *font = (XUI_Font *)hFont; + XUI_Font *font = static_cast(hFont); pFontMetrics->fLineHeight = (font->m_fontData->getFontYAdvance() + 1) * font->m_fYScaleFactor; pFontMetrics->fMaxAscent = font->m_fontData->getMaxAscent() * font->m_fYScaleFactor; @@ -142,7 +142,7 @@ HRESULT XUI_FontRenderer::GetCharMetrics( HFONTOBJ hFont, WCHAR wch, XUICharMetr { if (hFont == 0 || pCharMetrics == 0) return E_INVALIDARG; - XUI_Font *font = (XUI_Font *)hFont; + XUI_Font *font = static_cast(hFont); XUI_FontData::SChar sChar = font->m_fontData->getChar(wch); pCharMetrics->fMinX = sChar.getMinX() * font->m_fYScaleFactor; @@ -156,7 +156,7 @@ HRESULT XUI_FontRenderer::GetCharMetrics( HFONTOBJ hFont, WCHAR wch, XUICharMetr HRESULT XUI_FontRenderer::DrawCharToTexture( HFONTOBJ hFont, WCHAR wch, HXUIDC hDC, IXuiTexture * pTexture, UINT x, UINT y, UINT width, UINT height, UINT insetX, UINT insetY ) { - if( hFont==0 || pTexture==NULL ) return E_INVALIDARG; + if( hFont==0 || pTexture==nullptr ) return E_INVALIDARG; return( S_OK ); } @@ -169,7 +169,7 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat DWORD SamplerStateA[5]; XMVECTOR vconsts[20]; XMVECTOR pconsts[20]; - XUI_Font *font = (XUI_Font *)hFont; + XUI_Font *font = static_cast(hFont); // 4J-PB - if we're in 480 Widescreen mode, we need to ensure that the font characters are aligned on an even boundary if they are a 2x multiple if(!RenderManager.IsHiDef()) @@ -184,19 +184,19 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat if(iScaleX%2==0) { int iWorldX=pWorldViewProj->_41; - pWorldViewProj->_41 = (float)(iWorldX & -2); + pWorldViewProj->_41 = static_cast(iWorldX & -2); } if(iScaleY%2==0) { int iWorldY=pWorldViewProj->_42; - pWorldViewProj->_42 = (float)(iWorldY & -2); + pWorldViewProj->_42 = static_cast(iWorldY & -2); } } else { // make x an even number for 480 4:3 int iWorldX=pWorldViewProj->_41; - pWorldViewProj->_41 = (float)(iWorldX & -2); + pWorldViewProj->_41 = static_cast(iWorldX & -2); // 480 SD mode - y needs to be on a pixel boundary when multiplied by 1.5, so if it's an odd number, subtract 1/3 from it int iWorldY=pWorldViewProj->_42; diff --git a/Minecraft.Client/Xbox/Leaderboards/XboxLeaderboardManager.cpp b/Minecraft.Client/Xbox/Leaderboards/XboxLeaderboardManager.cpp index efa8a3dae..55967327e 100644 --- a/Minecraft.Client/Xbox/Leaderboards/XboxLeaderboardManager.cpp +++ b/Minecraft.Client/Xbox/Leaderboards/XboxLeaderboardManager.cpp @@ -10,25 +10,25 @@ LeaderboardManager *LeaderboardManager::m_instance = new XboxLeaderboardManager( const XboxLeaderboardManager::LeaderboardDescriptor XboxLeaderboardManager::LEADERBOARD_DESCRIPTORS[XboxLeaderboardManager::NUM_LEADERBOARDS][4] = { { - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_PEACEFUL, 4, STATS_COLUMN_TRAVELLING_PEACEFUL_WALKED, STATS_COLUMN_TRAVELLING_PEACEFUL_FALLEN, STATS_COLUMN_TRAVELLING_PEACEFUL_MINECART, STATS_COLUMN_TRAVELLING_PEACEFUL_BOAT, NULL, NULL, NULL,NULL), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_EASY, 4, STATS_COLUMN_TRAVELLING_EASY_WALKED, STATS_COLUMN_TRAVELLING_EASY_FALLEN, STATS_COLUMN_TRAVELLING_EASY_MINECART, STATS_COLUMN_TRAVELLING_EASY_BOAT, NULL, NULL, NULL,NULL), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_NORMAL, 4, STATS_COLUMN_TRAVELLING_NORMAL_WALKED, STATS_COLUMN_TRAVELLING_NORMAL_FALLEN, STATS_COLUMN_TRAVELLING_NORMAL_MINECART, STATS_COLUMN_TRAVELLING_NORMAL_BOAT, NULL, NULL, NULL,NULL), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_HARD, 4, STATS_COLUMN_TRAVELLING_HARD_WALKED, STATS_COLUMN_TRAVELLING_HARD_FALLEN, STATS_COLUMN_TRAVELLING_HARD_MINECART, STATS_COLUMN_TRAVELLING_HARD_BOAT, NULL, NULL, NULL,NULL), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_PEACEFUL, 4, STATS_COLUMN_TRAVELLING_PEACEFUL_WALKED, STATS_COLUMN_TRAVELLING_PEACEFUL_FALLEN, STATS_COLUMN_TRAVELLING_PEACEFUL_MINECART, STATS_COLUMN_TRAVELLING_PEACEFUL_BOAT, nullptr, nullptr, nullptr,nullptr), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_EASY, 4, STATS_COLUMN_TRAVELLING_EASY_WALKED, STATS_COLUMN_TRAVELLING_EASY_FALLEN, STATS_COLUMN_TRAVELLING_EASY_MINECART, STATS_COLUMN_TRAVELLING_EASY_BOAT, nullptr, nullptr, nullptr,nullptr), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_NORMAL, 4, STATS_COLUMN_TRAVELLING_NORMAL_WALKED, STATS_COLUMN_TRAVELLING_NORMAL_FALLEN, STATS_COLUMN_TRAVELLING_NORMAL_MINECART, STATS_COLUMN_TRAVELLING_NORMAL_BOAT, nullptr, nullptr, nullptr,nullptr), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_TRAVELLING_HARD, 4, STATS_COLUMN_TRAVELLING_HARD_WALKED, STATS_COLUMN_TRAVELLING_HARD_FALLEN, STATS_COLUMN_TRAVELLING_HARD_MINECART, STATS_COLUMN_TRAVELLING_HARD_BOAT, nullptr, nullptr, nullptr,nullptr), }, { - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_PEACEFUL, 7, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_DIRT, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_STONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_SAND, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_CLAY, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_OBSIDIAN, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_EASY, 7, STATS_COLUMN_MINING_BLOCKS_EASY_DIRT, STATS_COLUMN_MINING_BLOCKS_EASY_STONE, STATS_COLUMN_MINING_BLOCKS_EASY_SAND, STATS_COLUMN_MINING_BLOCKS_EASY_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_EASY_GRAVEL, STATS_COLUMN_MINING_BLOCKS_EASY_CLAY, STATS_COLUMN_MINING_BLOCKS_EASY_OBSIDIAN, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_NORMAL, 7, STATS_COLUMN_MINING_BLOCKS_NORMAL_DIRT, STATS_COLUMN_MINING_BLOCKS_NORMAL_STONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_SAND, STATS_COLUMN_MINING_BLOCKS_NORMAL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_NORMAL_CLAY, STATS_COLUMN_MINING_BLOCKS_NORMAL_OBSIDIAN, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_HARD, 7, STATS_COLUMN_MINING_BLOCKS_HARD_DIRT, STATS_COLUMN_MINING_BLOCKS_HARD_STONE, STATS_COLUMN_MINING_BLOCKS_HARD_SAND, STATS_COLUMN_MINING_BLOCKS_HARD_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_HARD_GRAVEL, STATS_COLUMN_MINING_BLOCKS_HARD_CLAY, STATS_COLUMN_MINING_BLOCKS_HARD_OBSIDIAN, NULL ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_PEACEFUL, 7, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_DIRT, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_STONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_SAND, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_CLAY, STATS_COLUMN_MINING_BLOCKS_PEACEFUL_OBSIDIAN, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_EASY, 7, STATS_COLUMN_MINING_BLOCKS_EASY_DIRT, STATS_COLUMN_MINING_BLOCKS_EASY_STONE, STATS_COLUMN_MINING_BLOCKS_EASY_SAND, STATS_COLUMN_MINING_BLOCKS_EASY_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_EASY_GRAVEL, STATS_COLUMN_MINING_BLOCKS_EASY_CLAY, STATS_COLUMN_MINING_BLOCKS_EASY_OBSIDIAN, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_NORMAL, 7, STATS_COLUMN_MINING_BLOCKS_NORMAL_DIRT, STATS_COLUMN_MINING_BLOCKS_NORMAL_STONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_SAND, STATS_COLUMN_MINING_BLOCKS_NORMAL_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_NORMAL_GRAVEL, STATS_COLUMN_MINING_BLOCKS_NORMAL_CLAY, STATS_COLUMN_MINING_BLOCKS_NORMAL_OBSIDIAN, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_MINING_BLOCKS_HARD, 7, STATS_COLUMN_MINING_BLOCKS_HARD_DIRT, STATS_COLUMN_MINING_BLOCKS_HARD_STONE, STATS_COLUMN_MINING_BLOCKS_HARD_SAND, STATS_COLUMN_MINING_BLOCKS_HARD_COBBLESTONE, STATS_COLUMN_MINING_BLOCKS_HARD_GRAVEL, STATS_COLUMN_MINING_BLOCKS_HARD_CLAY, STATS_COLUMN_MINING_BLOCKS_HARD_OBSIDIAN, nullptr ), }, { - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_PEACEFUL, 6, STATS_COLUMN_FARMING_PEACEFUL_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_PEACEFUL_MUSHROOMS,STATS_COLUMN_FARMING_PEACEFUL_SUGARCANE,STATS_COLUMN_FARMING_PEACEFUL_MILK, STATS_COLUMN_FARMING_PEACEFUL_PUMPKINS, NULL, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_EASY, 6, STATS_COLUMN_FARMING_EASY_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_EASY_MUSHROOMS, STATS_COLUMN_FARMING_EASY_SUGARCANE, STATS_COLUMN_FARMING_EASY_MILK, STATS_COLUMN_FARMING_EASY_PUMPKINS, NULL, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_NORMAL, 6, STATS_COLUMN_FARMING_NORMAL_EGGS, STATS_COLUMN_FARMING_NORMAL_WHEAT, STATS_COLUMN_FARMING_NORMAL_MUSHROOMS, STATS_COLUMN_FARMING_NORMAL_SUGARCANE, STATS_COLUMN_FARMING_NORMAL_MILK, STATS_COLUMN_FARMING_NORMAL_PUMPKINS, NULL, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_HARD, 6, STATS_COLUMN_FARMING_HARD_EGGS, STATS_COLUMN_FARMING_HARD_WHEAT, STATS_COLUMN_FARMING_HARD_MUSHROOMS, STATS_COLUMN_FARMING_HARD_SUGARCANE, STATS_COLUMN_FARMING_HARD_MILK, STATS_COLUMN_FARMING_HARD_PUMPKINS, NULL, NULL ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_PEACEFUL, 6, STATS_COLUMN_FARMING_PEACEFUL_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_PEACEFUL_MUSHROOMS,STATS_COLUMN_FARMING_PEACEFUL_SUGARCANE,STATS_COLUMN_FARMING_PEACEFUL_MILK, STATS_COLUMN_FARMING_PEACEFUL_PUMPKINS, nullptr, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_EASY, 6, STATS_COLUMN_FARMING_EASY_EGGS, STATS_COLUMN_FARMING_PEACEFUL_WHEAT, STATS_COLUMN_FARMING_EASY_MUSHROOMS, STATS_COLUMN_FARMING_EASY_SUGARCANE, STATS_COLUMN_FARMING_EASY_MILK, STATS_COLUMN_FARMING_EASY_PUMPKINS, nullptr, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_NORMAL, 6, STATS_COLUMN_FARMING_NORMAL_EGGS, STATS_COLUMN_FARMING_NORMAL_WHEAT, STATS_COLUMN_FARMING_NORMAL_MUSHROOMS, STATS_COLUMN_FARMING_NORMAL_SUGARCANE, STATS_COLUMN_FARMING_NORMAL_MILK, STATS_COLUMN_FARMING_NORMAL_PUMPKINS, nullptr, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_FARMING_HARD, 6, STATS_COLUMN_FARMING_HARD_EGGS, STATS_COLUMN_FARMING_HARD_WHEAT, STATS_COLUMN_FARMING_HARD_MUSHROOMS, STATS_COLUMN_FARMING_HARD_SUGARCANE, STATS_COLUMN_FARMING_HARD_MILK, STATS_COLUMN_FARMING_HARD_PUMPKINS, nullptr, nullptr ), }, { - XboxLeaderboardManager::LeaderboardDescriptor( NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_EASY, 7, STATS_COLUMN_KILLS_EASY_ZOMBIES, STATS_COLUMN_KILLS_EASY_SKELETONS, STATS_COLUMN_KILLS_EASY_CREEPERS, STATS_COLUMN_KILLS_EASY_SPIDERS, STATS_COLUMN_KILLS_EASY_SPIDERJOCKEYS, STATS_COLUMN_KILLS_EASY_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_EASY_SLIME, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_NORMAL, 7, STATS_COLUMN_KILLS_NORMAL_ZOMBIES, STATS_COLUMN_KILLS_NORMAL_SKELETONS, STATS_COLUMN_KILLS_NORMAL_CREEPERS, STATS_COLUMN_KILLS_NORMAL_SPIDERS, STATS_COLUMN_KILLS_NORMAL_SPIDERJOCKEYS, STATS_COLUMN_KILLS_NORMAL_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_NORMAL_SLIME, NULL ), - XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_HARD, 7, STATS_COLUMN_KILLS_HARD_ZOMBIES, STATS_COLUMN_KILLS_HARD_SKELETONS, STATS_COLUMN_KILLS_HARD_CREEPERS, STATS_COLUMN_KILLS_HARD_SPIDERS, STATS_COLUMN_KILLS_HARD_SPIDERJOCKEYS, STATS_COLUMN_KILLS_HARD_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_HARD_SLIME, NULL ), + XboxLeaderboardManager::LeaderboardDescriptor( nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_EASY, 7, STATS_COLUMN_KILLS_EASY_ZOMBIES, STATS_COLUMN_KILLS_EASY_SKELETONS, STATS_COLUMN_KILLS_EASY_CREEPERS, STATS_COLUMN_KILLS_EASY_SPIDERS, STATS_COLUMN_KILLS_EASY_SPIDERJOCKEYS, STATS_COLUMN_KILLS_EASY_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_EASY_SLIME, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_NORMAL, 7, STATS_COLUMN_KILLS_NORMAL_ZOMBIES, STATS_COLUMN_KILLS_NORMAL_SKELETONS, STATS_COLUMN_KILLS_NORMAL_CREEPERS, STATS_COLUMN_KILLS_NORMAL_SPIDERS, STATS_COLUMN_KILLS_NORMAL_SPIDERJOCKEYS, STATS_COLUMN_KILLS_NORMAL_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_NORMAL_SLIME, nullptr ), + XboxLeaderboardManager::LeaderboardDescriptor( STATS_VIEW_KILLS_HARD, 7, STATS_COLUMN_KILLS_HARD_ZOMBIES, STATS_COLUMN_KILLS_HARD_SKELETONS, STATS_COLUMN_KILLS_HARD_CREEPERS, STATS_COLUMN_KILLS_HARD_SPIDERS, STATS_COLUMN_KILLS_HARD_SPIDERJOCKEYS, STATS_COLUMN_KILLS_HARD_ZOMBIEPIGMEN, STATS_COLUMN_KILLS_HARD_SLIME, nullptr ), }, }; @@ -37,9 +37,9 @@ XboxLeaderboardManager::XboxLeaderboardManager() m_eStatsState = eStatsState_Idle; m_statsRead = false; - m_hSession = NULL; - m_spec = NULL; - m_stats = NULL; + m_hSession = nullptr; + m_spec = nullptr; + m_stats = nullptr; m_isQNetSession = false; m_endingSession = false; @@ -53,11 +53,11 @@ void XboxLeaderboardManager::Tick() { /*if( IsStatsReadComplete() ) - if( m_readCompleteCallback != NULL ) + if( m_readCompleteCallback != nullptr ) m_readCompleteCallback(m_readCompleteUserdata);*/ if ( IsStatsReadComplete() ) - if (m_readListener != NULL) + if (m_readListener != nullptr) { // 4J Stu - If the state is other than ready, then we don't have any stats to sort if(m_eFilterMode == LeaderboardManager::eFM_Friends && m_eStatsState == eStatsState_Ready) SortFriendStats(); @@ -83,12 +83,12 @@ bool XboxLeaderboardManager::OpenSession() if (m_endingSession) return false; //We've already got an open session - if (m_hSession != NULL) return true; + if (m_hSession != nullptr) return true; int lockedProfile = ProfileManager.GetLockedProfile(); if( lockedProfile == -1 ) { - m_hSession = NULL; + m_hSession = nullptr; return false; } @@ -112,26 +112,26 @@ bool XboxLeaderboardManager::OpenSession() XSESSION_INFO sessionInfo; ULONGLONG sessionNonce; - DWORD ret = XSessionCreate(XSESSION_CREATE_USES_STATS | XSESSION_CREATE_HOST, lockedProfile, 8, 8, &sessionNonce, &sessionInfo, NULL, &m_hSession); + DWORD ret = XSessionCreate(XSESSION_CREATE_USES_STATS | XSESSION_CREATE_HOST, lockedProfile, 8, 8, &sessionNonce, &sessionInfo, nullptr, &m_hSession); if( ret != ERROR_SUCCESS ) { - m_hSession = NULL; + m_hSession = nullptr; return false; } DWORD userIndices[1] = { lockedProfile }; BOOL privateSlots[1] = { FALSE }; - ret = XSessionJoinLocal(m_hSession, 1, userIndices, privateSlots, NULL); + ret = XSessionJoinLocal(m_hSession, 1, userIndices, privateSlots, nullptr); if( ret != ERROR_SUCCESS ) { - m_hSession = NULL; + m_hSession = nullptr; return false; } - ret = XSessionStart(m_hSession, 0, NULL); + ret = XSessionStart(m_hSession, 0, nullptr); if( ret != ERROR_SUCCESS ) { - m_hSession = NULL; + m_hSession = nullptr; return false; } @@ -151,7 +151,7 @@ void XboxLeaderboardManager::CloseSession() return; } - if (m_hSession == NULL) return; + if (m_hSession == nullptr) return; memset(&m_endSessionOverlapped, 0, sizeof(m_endSessionOverlapped)); @@ -166,15 +166,15 @@ void XboxLeaderboardManager::CloseSession() if (ret != ERROR_SUCCESS) DeleteSession(); } - m_readListener = NULL; + m_readListener = nullptr; } } void XboxLeaderboardManager::DeleteSession() { - XSessionDelete(m_hSession, NULL); + XSessionDelete(m_hSession, nullptr); CloseHandle(m_hSession); - m_hSession = NULL; + m_hSession = nullptr; } bool XboxLeaderboardManager::WriteStats(unsigned int viewCount, ViewIn views) @@ -190,9 +190,9 @@ bool XboxLeaderboardManager::WriteStats(unsigned int viewCount, ViewIn views) if(m_isQNetSession == true) { INetworkPlayer *player = g_NetworkManager.GetPlayerByXuid(m_myXUID); - if(player != NULL) + if(player != nullptr) { - ret = ((NetworkPlayerXbox *)player)->GetQNetPlayer()->WriteStats(viewCount,views); + ret = static_cast(player)->GetQNetPlayer()->WriteStats(viewCount,views); //printf("Wrote stats to QNet player\n"); } else @@ -204,7 +204,7 @@ bool XboxLeaderboardManager::WriteStats(unsigned int viewCount, ViewIn views) } else { - ret = XSessionWriteStats(m_hSession, m_myXUID, viewCount, views, NULL); + ret = XSessionWriteStats(m_hSession, m_myXUID, viewCount, views, nullptr); } if (ret != ERROR_SUCCESS) return false; return true; @@ -213,7 +213,7 @@ bool XboxLeaderboardManager::WriteStats(unsigned int viewCount, ViewIn views) void XboxLeaderboardManager::CancelOperation() { //Need to have a session open - if( m_hSession == NULL ) + if( m_hSession == nullptr ) if( !OpenSession() ) return; @@ -249,7 +249,7 @@ bool XboxLeaderboardManager::ReadStats_MyScore(LeaderboardReadListener *callback //Allocate a buffer for the stats m_stats = (PXUSER_STATS_READ_RESULTS) new BYTE[m_numStats]; - if (m_stats == NULL) return false; + if (m_stats == nullptr) return false; memset(m_stats, 0, m_numStats); memset(&m_overlapped, 0, sizeof(m_overlapped)); @@ -258,7 +258,7 @@ bool XboxLeaderboardManager::ReadStats_MyScore(LeaderboardReadListener *callback hEnumerator, // Enumeration handle m_stats, // Buffer m_numStats, // Size of buffer - NULL, // Number of rows returned; not used for async + nullptr, // Number of rows returned; not used for async &m_overlapped ); // Overlapped structure; not used for sync if ( (ret!=ERROR_SUCCESS) && (ret!=ERROR_IO_PENDING) ) return false; @@ -280,12 +280,12 @@ bool XboxLeaderboardManager::ReadStats_Friends(LeaderboardReadListener *callback getFriends(friendCount, &friends); - if(friendCount == 0 || friends == NULL) + if(friendCount == 0 || friends == nullptr) { app.DebugPrintf("XboxLeaderboardManager::ReadStats_Friends - No friends found. Possibly you are offline?\n"); return false; } - assert(friendCount > 0 && friends != NULL); + assert(friendCount > 0 && friends != nullptr); m_numStats = 0; ret = XUserReadStats( @@ -295,8 +295,8 @@ bool XboxLeaderboardManager::ReadStats_Friends(LeaderboardReadListener *callback 1, //specCount, m_spec, &m_numStats, - NULL, - NULL + nullptr, + nullptr ); //Annoyingly, this returns ERROR_INSUFFICIENT_BUFFER when it is being asked to calculate the size of the buffer by passing zero resultsSize @@ -304,7 +304,7 @@ bool XboxLeaderboardManager::ReadStats_Friends(LeaderboardReadListener *callback //Allocate a buffer for the stats m_stats = (PXUSER_STATS_READ_RESULTS) new BYTE[m_numStats]; - if (m_stats == NULL) return false; + if (m_stats == nullptr) return false; memset(m_stats, 0, m_numStats); memset(&m_overlapped, 0, sizeof(m_overlapped)); @@ -346,7 +346,7 @@ bool XboxLeaderboardManager::ReadStats_TopRank(LeaderboardReadListener *callback //Allocate a buffer for the stats m_stats = (PXUSER_STATS_READ_RESULTS) new BYTE[m_numStats]; - if (m_stats == NULL) return false; + if (m_stats == nullptr) return false; memset(m_stats, 0, m_numStats); memset(&m_overlapped, 0, sizeof(m_overlapped)); @@ -355,7 +355,7 @@ bool XboxLeaderboardManager::ReadStats_TopRank(LeaderboardReadListener *callback hEnumerator, // Enumeration handle m_stats, // Buffer m_numStats, // Size of buffer - NULL, // Number of rows returned; not used for async + nullptr, // Number of rows returned; not used for async &m_overlapped ); // Overlapped structure; not used for sync if( (ret!=ERROR_SUCCESS) && (ret!=ERROR_IO_PENDING) ) return false; @@ -367,7 +367,7 @@ bool XboxLeaderboardManager::ReadStats_TopRank(LeaderboardReadListener *callback bool XboxLeaderboardManager::readStats(int difficulty, EStatsType type) { //Need to have a session open - if (m_hSession==NULL) if(!OpenSession()) return false; + if (m_hSession==nullptr) if(!OpenSession()) return false; m_eStatsState = eStatsState_Failed; m_statsRead = false; @@ -376,17 +376,17 @@ bool XboxLeaderboardManager::readStats(int difficulty, EStatsType type) //Setup the spec structure for the read request m_spec = new XUSER_STATS_SPEC[1]; - m_spec[0].dwViewId = LEADERBOARD_DESCRIPTORS[(int)type][difficulty].m_viewId; - m_spec[0].dwNumColumnIds = LEADERBOARD_DESCRIPTORS[(int)type][difficulty].m_columnCount; + m_spec[0].dwViewId = LEADERBOARD_DESCRIPTORS[static_cast(type)][difficulty].m_viewId; + m_spec[0].dwNumColumnIds = LEADERBOARD_DESCRIPTORS[static_cast(type)][difficulty].m_columnCount; for (unsigned int i=0; i(type)][difficulty].m_columnIds[i]; return true; } void XboxLeaderboardManager::FlushStats() { - if( m_hSession == NULL || m_isQNetSession ) return; + if( m_hSession == nullptr || m_isQNetSession ) return; memset(&m_flushStatsOverlapped, 0, sizeof(m_flushStatsOverlapped)); XSessionFlushStats(m_hSession, &m_flushStatsOverlapped); } @@ -403,7 +403,7 @@ bool XboxLeaderboardManager::IsStatsReadComplete() if( m_stats ) { delete [] m_stats; - m_stats = NULL; + m_stats = nullptr; } } else @@ -415,7 +415,7 @@ bool XboxLeaderboardManager::IsStatsReadComplete() if( m_stats ) { delete [] m_stats; - m_stats = NULL; + m_stats = nullptr; } } else @@ -431,7 +431,7 @@ bool XboxLeaderboardManager::IsStatsReadComplete() int XboxLeaderboardManager::FriendSortFunction(const void* a, const void* b) { - return ((int)((XUSER_STATS_ROW*)a)->dwRank) - ((int)((XUSER_STATS_ROW*)b)->dwRank); + return static_cast(((XUSER_STATS_ROW *)a)->dwRank) - static_cast(((XUSER_STATS_ROW *)b)->dwRank); } void XboxLeaderboardManager::SortFriendStats() @@ -465,10 +465,10 @@ void XboxLeaderboardManager::SortFriendStats() #if 0 void XboxLeaderboardManager::SetStatsRetrieved(bool success) { - if( m_stats != NULL ) + if( m_stats != nullptr ) { delete [] m_stats; - m_stats = NULL; + m_stats = nullptr; } m_statsRead = success; @@ -496,7 +496,7 @@ bool XboxLeaderboardManager::getFriends(unsigned int &friendsCount, PlayerUID** xonlineFriends, resultsSize, &numFriends, - NULL + nullptr ); if (ret!=ERROR_SUCCESS) friendsCount = 0; diff --git a/Minecraft.Client/Xbox/Network/NetworkPlayerXbox.cpp b/Minecraft.Client/Xbox/Network/NetworkPlayerXbox.cpp index 5216d9083..edadfac41 100644 --- a/Minecraft.Client/Xbox/Network/NetworkPlayerXbox.cpp +++ b/Minecraft.Client/Xbox/Network/NetworkPlayerXbox.cpp @@ -4,7 +4,7 @@ NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer *qnetPlayer) { m_qnetPlayer = qnetPlayer; - m_pSocket = NULL; + m_pSocket = nullptr; } unsigned char NetworkPlayerXbox::GetSmallId() @@ -17,7 +17,7 @@ void NetworkPlayerXbox::SendData(INetworkPlayer *player, const void *pvData, int DWORD flags; flags = QNET_SENDDATA_RELIABLE | QNET_SENDDATA_SEQUENTIAL; if( lowPriority ) flags |= QNET_SENDDATA_LOW_PRIORITY | QNET_SENDDATA_SECONDARY; - m_qnetPlayer->SendData(((NetworkPlayerXbox *)player)->m_qnetPlayer, pvData, dataSize, flags); + m_qnetPlayer->SendData(static_cast(player)->m_qnetPlayer, pvData, dataSize, flags); } int NetworkPlayerXbox::GetOutstandingAckCount() @@ -27,21 +27,21 @@ int NetworkPlayerXbox::GetOutstandingAckCount() bool NetworkPlayerXbox::IsSameSystem(INetworkPlayer *player) { - return ( m_qnetPlayer->IsSameSystem(((NetworkPlayerXbox *)player)->m_qnetPlayer) == TRUE ); + return ( m_qnetPlayer->IsSameSystem(static_cast(player)->m_qnetPlayer) == TRUE ); } int NetworkPlayerXbox::GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ) { DWORD flags = QNET_GETSENDQUEUESIZE_BYTES; if( lowPriority ) flags |= QNET_GETSENDQUEUESIZE_SECONDARY_TYPE; - return m_qnetPlayer->GetSendQueueSize(player ? ((NetworkPlayerXbox *)player)->m_qnetPlayer : NULL , flags); + return m_qnetPlayer->GetSendQueueSize(player ? static_cast(player)->m_qnetPlayer : nullptr , flags); } int NetworkPlayerXbox::GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ) { DWORD flags = QNET_GETSENDQUEUESIZE_MESSAGES; if( lowPriority ) flags |= QNET_GETSENDQUEUESIZE_SECONDARY_TYPE; - return m_qnetPlayer->GetSendQueueSize(player ? ((NetworkPlayerXbox *)player)->m_qnetPlayer : NULL , flags); + return m_qnetPlayer->GetSendQueueSize(player ? static_cast(player)->m_qnetPlayer : nullptr , flags); } int NetworkPlayerXbox::GetCurrentRtt() @@ -137,6 +137,6 @@ int NetworkPlayerXbox::GetTimeSinceLastChunkPacket_ms() return INT_MAX; } - int64_t currentTime = System::currentTimeMillis(); - return (int)( currentTime - m_lastChunkPacketTime ); + const int64_t currentTime = System::currentTimeMillis(); + return static_cast(currentTime - m_lastChunkPacketTime); } \ No newline at end of file diff --git a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp index 473171463..f586f4470 100644 --- a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp +++ b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp @@ -109,7 +109,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( bool createFakeSocket = false; bool localPlayer = false; - NetworkPlayerXbox *networkPlayer = (NetworkPlayerXbox *)addNetworkPlayer(pQNetPlayer); + NetworkPlayerXbox *networkPlayer = static_cast(addNetworkPlayer(pQNetPlayer)); if( pQNetPlayer->IsLocal() ) { @@ -187,7 +187,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); } @@ -196,7 +196,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -221,7 +221,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( // Get our wrapper object associated with this player. Socket *socket = networkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { // If we are in game then remove this player from the game as well. // We may get here either from the player requesting to exit the game, @@ -237,14 +237,14 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( // We need this as long as the game server still needs to communicate with the player //delete socket; - networkPlayer->SetSocket( NULL ); + networkPlayer->SetSocket( nullptr ); } if( m_pIQNet->IsHost() && !m_bHostChanged ) { if( isSystemPrimaryPlayer(pQNetPlayer) ) { - IQNetPlayer *pNewQNetPrimaryPlayer = NULL; + IQNetPlayer *pNewQNetPrimaryPlayer = nullptr; for(unsigned int i = 0; i < m_pIQNet->GetPlayerCount(); ++i ) { IQNetPlayer *pQNetPlayer2 = m_pIQNet->GetPlayerByIndex( i ); @@ -261,7 +261,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( m_machineQNetPrimaryPlayers.erase( it ); } - if( pNewQNetPrimaryPlayer != NULL ) + if( pNewQNetPrimaryPlayer != nullptr ) m_machineQNetPrimaryPlayers.push_back( pNewQNetPrimaryPlayer ); } @@ -274,7 +274,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if(playerChangedCallback[idx] != NULL) + if(playerChangedCallback[idx] != nullptr) playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, true ); } @@ -283,7 +283,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( int localPlayerCount = 0; for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { - if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; } float appTime = app.getAppTime(); @@ -349,7 +349,7 @@ VOID CPlatformNetworkManagerXbox::NotifyDataReceived( INetworkPlayer *pPlayerFrom = getNetworkPlayer(pQNetPlayerFrom); Socket *socket = pPlayerFrom->GetSocket(); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(pbData, dwDataSize, false); } else @@ -358,7 +358,7 @@ VOID CPlatformNetworkManagerXbox::NotifyDataReceived( INetworkPlayer *pPlayerTo = getNetworkPlayer(apQNetPlayersTo[dwPlayer]); Socket *socket = pPlayerTo->GetSocket(); //app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", apPlayersTo[dwPlayer]->GetGamertag()); - if(socket != NULL) + if(socket != nullptr) socket->pushDataToQueue(pbData, dwDataSize); } } @@ -380,7 +380,7 @@ VOID CPlatformNetworkManagerXbox::NotifyReadinessChanged( __in BOOL bReady ) { - app.DebugPrintf( "Player 0x%p readiness is now %i.\n", pQNetPlayer, (int) bReady ); + app.DebugPrintf( "Player 0x%p readiness is now %i.\n", pQNetPlayer, static_cast(bReady) ); } @@ -432,7 +432,7 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa g_pPlatformNetworkManager = this; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { - playerChangedCallback[ i ] = NULL; + playerChangedCallback[ i ] = nullptr; } HRESULT hr; @@ -440,7 +440,7 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa DWORD dwResult; // Start up XNet with default settings. - iResult = XNetStartup( NULL ); + iResult = XNetStartup( nullptr ); if( iResult != 0 ) { app.DebugPrintf( "Starting up XNet failed (err = %i)!\n", iResult ); @@ -457,7 +457,7 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa } // Create the QNet object. - hr = QNetCreateUsingXAudio2( QNET_SESSIONTYPE_LIVE_STANDARD, this, NULL, g_pXAudio2, &m_pIQNet ); + hr = QNetCreateUsingXAudio2( QNET_SESSIONTYPE_LIVE_STANDARD, this, nullptr, g_pXAudio2, &m_pIQNet ); if( FAILED( hr ) ) { app.DebugPrintf( "Creating QNet object failed (err = 0x%08x)!\n", hr ); @@ -489,8 +489,8 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa m_bSearchPending = false; m_bIsOfflineGame = false; - m_pSearchParam = NULL; - m_SessionsUpdatedCallback = NULL; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { @@ -498,10 +498,10 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa m_lastSearchStartTime[i] = 0; // The results that will be filled in with the current search - m_pSearchResults[i] = NULL; - m_pQoSResult[i] = NULL; - m_pCurrentSearchResults[i] = NULL; - m_pCurrentQoSResult[i] = NULL; + m_pSearchResults[i] = nullptr; + m_pQoSResult[i] = nullptr; + m_pCurrentSearchResults[i] = nullptr; + m_pCurrentQoSResult[i] = nullptr; m_currentSearchResultsCount[i] = 0; } @@ -629,11 +629,11 @@ bool CPlatformNetworkManagerXbox::RemoveLocalPlayerByUserIndex( int userIndex ) IQNetPlayer *pQNetPlayer = m_pIQNet->GetLocalPlayerByUserIndex(userIndex); INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pQNetPlayer); - if(pNetworkPlayer != NULL) + if(pNetworkPlayer != nullptr) { Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { // We can't remove the player from qnet until we have stopped using it to communicate C4JThread* thread = new C4JThread(&CPlatformNetworkManagerXbox::RemovePlayerOnSocketClosedThreadProc, pNetworkPlayer, "RemovePlayerOnSocketClosed"); @@ -701,11 +701,11 @@ bool CPlatformNetworkManagerXbox::LeaveGame(bool bMigrateHost) IQNetPlayer *pQNetPlayer = m_pIQNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pQNetPlayer); - if(pNetworkPlayer != NULL) + if(pNetworkPlayer != nullptr) { Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); DWORD result = socket->m_socketClosedEvent->WaitForSignal(INFINITE); @@ -717,13 +717,13 @@ bool CPlatformNetworkManagerXbox::LeaveGame(bool bMigrateHost) // 4J Stu - Clear our reference to this socket pQNetPlayer = m_pIQNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); pNetworkPlayer = getNetworkPlayer(pQNetPlayer); - if(pNetworkPlayer) pNetworkPlayer->SetSocket( NULL ); + if(pNetworkPlayer) pNetworkPlayer->SetSocket( nullptr ); } delete socket; } else { - //printf("Socket is already NULL\n"); + //printf("Socket is already nullptr\n"); } } @@ -795,7 +795,7 @@ void CPlatformNetworkManagerXbox::_HostGame(int usersMask, unsigned char publicS publicSlots, // dwPublicSlots privateSlots, // dwPrivateSlots 0, // cProperties - NULL, // pProperties + nullptr, // pProperties ARRAYSIZE( aXUserContexts ), // cContexts aXUserContexts ); // pContexts @@ -899,8 +899,8 @@ void CPlatformNetworkManagerXbox::UnRegisterPlayerChangedCallback(int iPad, void { if(playerChangedCallbackParam[iPad] == callbackParam) { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; + playerChangedCallback[iPad] = nullptr; + playerChangedCallbackParam[iPad] = nullptr; } } @@ -927,14 +927,14 @@ bool CPlatformNetworkManagerXbox::_RunNetworkGame() return true; } -void CPlatformNetworkManagerXbox::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) +void CPlatformNetworkManagerXbox::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= nullptr*/) { DWORD playerCount = m_pIQNet->GetPlayerCount(); if( this->m_bLeavingGame ) return; - if( GetHostPlayer() == NULL ) + if( GetHostPlayer() == nullptr ) return; for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) @@ -946,7 +946,7 @@ void CPlatformNetworkManagerXbox::UpdateAndSetGameSessionData(INetworkPlayer *pN // 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(); + m_hostGameSessionData.players[i] = static_cast(pNetworkPlayer)->GetUID(); char *temp; temp = (char *)wstringtofilename( pNetworkPlayer->GetOnlineName() ); @@ -954,18 +954,18 @@ void CPlatformNetworkManagerXbox::UpdateAndSetGameSessionData(INetworkPlayer *pN } else { - m_hostGameSessionData.players[i] = NULL; + m_hostGameSessionData.players[i] = nullptr; memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); } } else { - m_hostGameSessionData.players[i] = NULL; + m_hostGameSessionData.players[i] = nullptr; memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); } } - m_hostGameSessionData.hostPlayerUID = ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetXuid(); + m_hostGameSessionData.hostPlayerUID = static_cast(GetHostPlayer())->GetQNetPlayer()->GetXuid(); m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); HRESULT hr = S_OK; @@ -978,18 +978,18 @@ void CPlatformNetworkManagerXbox::UpdateAndSetGameSessionData(INetworkPlayer *pN int CPlatformNetworkManagerXbox::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) { - INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; + INetworkPlayer *pNetworkPlayer = static_cast(lpParam); Socket *socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) + if( socket != nullptr ) { //printf("Waiting for socket closed event\n"); socket->m_socketClosedEvent->WaitForSignal(INFINITE); //printf("Socket closed event has fired\n"); // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); + pNetworkPlayer->SetSocket( nullptr ); delete socket; } @@ -1066,7 +1066,7 @@ void CPlatformNetworkManagerXbox::SystemFlagReset() void CPlatformNetworkManagerXbox::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; + if( pNetworkPlayer == nullptr ) return; for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) { @@ -1082,7 +1082,7 @@ void CPlatformNetworkManagerXbox::SystemFlagSet(INetworkPlayer *pNetworkPlayer, bool CPlatformNetworkManagerXbox::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) { if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) + if( pNetworkPlayer == nullptr ) { return false; } @@ -1099,8 +1099,8 @@ bool CPlatformNetworkManagerXbox::SystemFlagGet(INetworkPlayer *pNetworkPlayer, wstring CPlatformNetworkManagerXbox::GatherStats() { - 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 ) ); + return L"Queue messages: " + std::to_wstring(static_cast(GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( nullptr, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + + L" Queue bytes: " + std::to_wstring( static_cast(GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( nullptr, QNET_GETSENDQUEUESIZE_BYTES ) ); } wstring CPlatformNetworkManagerXbox::GatherRTTStats() @@ -1111,7 +1111,7 @@ wstring CPlatformNetworkManagerXbox::GatherRTTStats() for(unsigned int i = 0; i < GetPlayerCount(); ++i) { - IQNetPlayer *pQNetPlayer = ((NetworkPlayerXbox *)GetPlayerByIndex( i ))->GetQNetPlayer(); + IQNetPlayer *pQNetPlayer = static_cast(GetPlayerByIndex(i))->GetQNetPlayer(); if(!pQNetPlayer->IsLocal()) { @@ -1132,23 +1132,23 @@ void CPlatformNetworkManagerXbox::TickSearch() m_currentSearchResultsCount[m_lastSearchPad] = m_searchResultsCount[m_lastSearchPad]; // Store the current search results so that we don't delete them too early - if( m_pCurrentSearchResults[m_lastSearchPad] != NULL ) + if( m_pCurrentSearchResults[m_lastSearchPad] != nullptr ) { delete m_pCurrentSearchResults[m_lastSearchPad]; - m_pCurrentSearchResults[m_lastSearchPad] = NULL; + m_pCurrentSearchResults[m_lastSearchPad] = nullptr; } m_pCurrentSearchResults[m_lastSearchPad] = m_pSearchResults[m_lastSearchPad]; - m_pSearchResults[m_lastSearchPad] = NULL; + m_pSearchResults[m_lastSearchPad] = nullptr; - if( m_pCurrentQoSResult[m_lastSearchPad] != NULL ) + if( m_pCurrentQoSResult[m_lastSearchPad] != nullptr ) { XNetQosRelease(m_pCurrentQoSResult[m_lastSearchPad]); - m_pCurrentQoSResult[m_lastSearchPad] = NULL; + m_pCurrentQoSResult[m_lastSearchPad] = nullptr; } m_pCurrentQoSResult[m_lastSearchPad] = m_pQoSResult[m_lastSearchPad]; - m_pQoSResult[m_lastSearchPad] = NULL; + m_pQoSResult[m_lastSearchPad] = nullptr; - if( m_SessionsUpdatedCallback != NULL ) m_SessionsUpdatedCallback(m_pSearchParam); + if( m_SessionsUpdatedCallback != nullptr ) m_SessionsUpdatedCallback(m_pSearchParam); m_bSearchResultsReady = false; m_bSearchPending = false; } @@ -1156,7 +1156,7 @@ void CPlatformNetworkManagerXbox::TickSearch() else { // Don't start searches unless we have registered a callback - if( m_SessionsUpdatedCallback != NULL && (m_lastSearchStartTime[g_NetworkManager.GetPrimaryPad()] + MINECRAFT_XSESSION_SEARCH_DELAY_MILLISECONDS) < GetTickCount() ) + if( m_SessionsUpdatedCallback != nullptr && (m_lastSearchStartTime[g_NetworkManager.GetPrimaryPad()] + MINECRAFT_XSESSION_SEARCH_DELAY_MILLISECONDS) < GetTickCount() ) { SearchForGames(); } @@ -1180,15 +1180,15 @@ void CPlatformNetworkManagerXbox::SearchForGames() } friendsSessions[m_lastSearchPad].clear(); - if( m_pSearchResults[m_lastSearchPad] != NULL ) + if( m_pSearchResults[m_lastSearchPad] != nullptr ) { delete m_pSearchResults[m_lastSearchPad]; - m_pSearchResults[m_lastSearchPad] = NULL; + m_pSearchResults[m_lastSearchPad] = nullptr; } - if( m_pQoSResult[m_lastSearchPad] != NULL ) + if( m_pQoSResult[m_lastSearchPad] != nullptr ) { XNetQosRelease(m_pQoSResult[m_lastSearchPad]); - m_pQoSResult[m_lastSearchPad] = NULL; + m_pQoSResult[m_lastSearchPad] = nullptr; } bool bMultiplayerAllowed = g_NetworkManager.IsSignedInLive( g_NetworkManager.GetPrimaryPad() ) && g_NetworkManager.AllowedToPlayMultiplayer( g_NetworkManager.GetPrimaryPad() ); @@ -1250,7 +1250,7 @@ void CPlatformNetworkManagerXbox::SearchForGames() buffer, bufferSize, &itemsReturned, - NULL + nullptr ); DWORD flagPlayingOnline = XONLINE_FRIENDSTATE_FLAG_ONLINE; // | XONLINE_FRIENDSTATE_FLAG_PLAYING; @@ -1317,8 +1317,8 @@ void CPlatformNetworkManagerXbox::SearchForGames() sessionIDList, g_NetworkManager.GetPrimaryPad(), &cbResults, // Pass in the address of the size variable - NULL, - NULL // This example uses the synchronous model + nullptr, + nullptr // This example uses the synchronous model ); XOVERLAPPED *pOverlapped = new XOVERLAPPED(); @@ -1386,7 +1386,7 @@ void CPlatformNetworkManagerXbox::SearchForGames() int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) { - SearchForGamesData *threadData = (SearchForGamesData *)lpParameter; + SearchForGamesData *threadData = static_cast(lpParameter); DWORD sessionIDCount = threadData->sessionIDCount; @@ -1423,7 +1423,7 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) } // Create an event object that is autoreset with an initial state of "not signaled". // Pass this event handle to the QoSLookup to receive notification of each QoS lookup. - HANDLE QoSLookupHandle = CreateEvent(NULL, false, false, NULL); + HANDLE QoSLookupHandle = CreateEvent(nullptr, false, false, nullptr); *threadData->ppQos = new XNQOS(); @@ -1433,8 +1433,8 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) 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 - NULL, // Pointer to an array of IN_ADDR structures that contain the IP addresses of the security gateways - NULL, // Pointer to an array of service IDs for the security gateway + nullptr, // Pointer to an array of IN_ADDR structures that contain the IP addresses of the security gateways + nullptr, // Pointer to an array of service IDs for the security gateway 8, // Number of desired probe replies to receive 0, // Maximum upstream bandwidth that the outgoing QoS probe packets can consume 0, // Flags @@ -1489,11 +1489,11 @@ vector *CPlatformNetworkManagerXbox::GetSessionList(int iPa 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; + // 4J Stu - pSearchResult should never be nullptr, but just in case... + if(pSearchResult == nullptr || pSearchResult->dwOpenPublicSlots < localPlayers) continue; bool foundSession = false; - FriendSessionInfo *sessionInfo = NULL; + FriendSessionInfo *sessionInfo = nullptr; auto itFriendSession = friendsSessions[iPad].begin(); for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) { @@ -1595,7 +1595,7 @@ bool CPlatformNetworkManagerXbox::GetGameSessionInfo(int iPad, SessionID session if(memcmp( &pSearchResult->info.sessionID, &sessionId, sizeof(SessionID) ) != 0) continue; bool foundSession = false; - FriendSessionInfo *sessionInfo = NULL; + FriendSessionInfo *sessionInfo = nullptr; auto = itFriendSession, friendsSessions[iPad].begin(); for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) { @@ -1637,7 +1637,7 @@ bool CPlatformNetworkManagerXbox::GetGameSessionInfo(int iPad, SessionID session sessionInfo->data.isJoinable) { foundSessionInfo->data = sessionInfo->data; - if(foundSessionInfo->displayLabel != NULL) delete [] foundSessionInfo->displayLabel; + if(foundSessionInfo->displayLabel != nullptr) delete [] foundSessionInfo->displayLabel; foundSessionInfo->displayLabel = new wchar_t[100]; memcpy(foundSessionInfo->displayLabel, sessionInfo->displayLabel, 100 * sizeof(wchar_t) ); foundSessionInfo->displayLabelLength = sessionInfo->displayLabelLength; @@ -1672,7 +1672,7 @@ void CPlatformNetworkManagerXbox::ForceFriendsSessionRefresh() m_searchResultsCount[i] = 0; m_lastSearchStartTime[i] = 0; delete m_pSearchResults[i]; - m_pSearchResults[i] = NULL; + m_pSearchResults[i] = nullptr; } } @@ -1699,7 +1699,7 @@ void CPlatformNetworkManagerXbox::removeNetworkPlayer(IQNetPlayer *pQNetPlayer) INetworkPlayer *CPlatformNetworkManagerXbox::getNetworkPlayer(IQNetPlayer *pQNetPlayer) { - return pQNetPlayer ? (INetworkPlayer *)(pQNetPlayer->GetCustomDataValue()) : NULL; + return pQNetPlayer ? (INetworkPlayer *)(pQNetPlayer->GetCustomDataValue()) : nullptr; } diff --git a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.h b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.h index 7c6112b4e..2784726c7 100644 --- a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.h +++ b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.h @@ -88,7 +88,7 @@ private: GameSessionData m_hostGameSessionData; CGameNetworkManager *m_pGameNetworkManager; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = nullptr); private: // TODO 4J Stu - Do we need to be able to have more than one of these? diff --git a/Minecraft.Client/Xbox/Sentient/DynamicConfigurations.cpp b/Minecraft.Client/Xbox/Sentient/DynamicConfigurations.cpp index 5d2b97631..086b141ef 100644 --- a/Minecraft.Client/Xbox/Sentient/DynamicConfigurations.cpp +++ b/Minecraft.Client/Xbox/Sentient/DynamicConfigurations.cpp @@ -11,7 +11,7 @@ bool MinecraftDynamicConfigurations::s_bUpdatedConfigs[MinecraftDynamicConfigura MinecraftDynamicConfigurations::EDynamic_Configs MinecraftDynamicConfigurations::s_eCurrentConfig = MinecraftDynamicConfigurations::eDynamic_Config_Max; size_t MinecraftDynamicConfigurations::s_currentConfigSize = 0; size_t MinecraftDynamicConfigurations::s_dataWrittenSize = 0; -byte *MinecraftDynamicConfigurations::s_dataWritten = NULL; +byte *MinecraftDynamicConfigurations::s_dataWritten = nullptr; void MinecraftDynamicConfigurations::Tick() { @@ -43,7 +43,7 @@ void MinecraftDynamicConfigurations::UpdateNextConfiguration() { if(!s_bUpdatedConfigs[i]) { - update = (EDynamic_Configs)i; + update = static_cast(i); break; } } @@ -57,7 +57,7 @@ void MinecraftDynamicConfigurations::UpdateConfiguration(EDynamic_Configs id) { app.DebugPrintf("DynamicConfig: Attempting to update dynamic configuration %d\n", id); - HRESULT hr = Sentient::SenDynamicConfigGetSize( id, &s_currentConfigSize, &MinecraftDynamicConfigurations::GetSizeCompletedCallback, NULL); + HRESULT hr = Sentient::SenDynamicConfigGetSize( id, &s_currentConfigSize, &MinecraftDynamicConfigurations::GetSizeCompletedCallback, nullptr); switch(hr) { @@ -76,7 +76,7 @@ void MinecraftDynamicConfigurations::UpdateConfiguration(EDynamic_Configs id) break; case E_POINTER: app.DebugPrintf("DynamicConfig: Failed to get size for config as pointer is invalid\n"); - //The out_size pointer is NULL. + //The out_size pointer is nullptr. break; } if(FAILED(hr) ) @@ -97,7 +97,7 @@ void MinecraftDynamicConfigurations::GetSizeCompletedCallback(HRESULT taskResult &s_dataWrittenSize, s_dataWritten, &MinecraftDynamicConfigurations::GetDataCompletedCallback, - NULL + nullptr ); switch(hr) @@ -115,8 +115,8 @@ void MinecraftDynamicConfigurations::GetSizeCompletedCallback(HRESULT taskResult //Sentient is not initialized. You must call SentientInitialize before you call this function. break; case E_POINTER: - app.DebugPrintf("DynamicConfig: Failed to get bytes for config as pointer is NULL\n"); - //The out_size pointer is NULL. + app.DebugPrintf("DynamicConfig: Failed to get bytes for config as pointer is nullptr\n"); + //The out_size pointer is nullptr. break; } if(FAILED(hr) ) @@ -160,7 +160,7 @@ void MinecraftDynamicConfigurations::GetDataCompletedCallback(HRESULT taskResu } delete [] s_dataWritten; - s_dataWritten = NULL; + s_dataWritten = nullptr; s_bUpdatedConfigs[s_eCurrentConfig] = true; UpdateNextConfiguration(); diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientAvatar.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientAvatar.h index dfccfd3b7..524c1bdc0 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientAvatar.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientAvatar.h @@ -108,7 +108,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_avatarInfoList is NULL. + /// E_POINTER: out_avatarInfoList is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -149,7 +149,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_avatarInfo is NULL. + /// E_POINTER: out_avatarInfo is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -192,7 +192,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: avatarInfo.resourceID or avatarInfo.[fe]male.metadata is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -235,7 +235,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: avatarInfo.resourceID or avatarInfo.[fe]male.assets is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -278,7 +278,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: avatarInfo.resourceID or avatarInfo.[fe]male.icon is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -316,7 +316,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: avatarInfo.resourceID or avatarInfo.xml is invalid. - /// E_POINTER: out_avatarExtraInfo is NULL. + /// E_POINTER: out_avatarExtraInfo is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -352,14 +352,14 @@ namespace Sentient // First method, filling a fixed-size buffer: // // wchar_t buffer[1234]; - // SenAvatarXMLGetTitle( xml, loc, _countof(buffer), NULL, buffer ); + // SenAvatarXMLGetTitle( xml, loc, _countof(buffer), nullptr, buffer ); // // Second method, filling a dynamically-allocated buffer: // // size_t bufferLength; - // SenAvatarXMLGetTitle( xml, loc, 0, &bufferLength, NULL ); + // SenAvatarXMLGetTitle( xml, loc, 0, &bufferLength, nullptr ); // wchar_t buffer = new wchar_t[bufferLength]; - // SenAvatarXMLGetTitle( xml, loc, bufferLength, NULL, buffer ); + // SenAvatarXMLGetTitle( xml, loc, bufferLength, nullptr, buffer ); // // Note that bufferLength is in wchars, and includes the terminating nul. // The actual length of the _string_ is (*out_bufferLength - 1). diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientBoxArt.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientBoxArt.h index 096622433..95a8c1881 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientBoxArt.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientBoxArt.h @@ -116,7 +116,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_boxArtInfoList is NULL. + /// E_POINTER: out_boxArtInfoList is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -160,7 +160,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: boxArtInfo.resourceID or boxArtInfo.image is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -198,7 +198,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: boxArtInfo.resourceID or boxArtInfo.xml is invalid. - /// E_POINTER: out_boxArtExtraInfo is NULL. + /// E_POINTER: out_boxArtExtraInfo is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -236,7 +236,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: boxArtInfo.resourceID or boxArtInfo.xml is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -263,7 +263,7 @@ namespace Sentient /// /// @param[in] culture /// This is the result of a call to SenCultureFind() or SenCultureGet*(). - /// You may also pass NULL to use the culture set with SenCultureSetCurrent(). + /// You may also pass nullptr to use the culture set with SenCultureSetCurrent(). /// /// @param[in] bufferLength /// Note that bufferLength is in wchars, and needs to _include_ space for the terminating nul. @@ -271,16 +271,16 @@ namespace Sentient /// @param[out] out_bufferLength /// Used to return the actual number of wchars written to the buffer, including the terminating nul. /// The actual length of the _string_ is (*out_bufferLength - 1). - /// Pass @a out_bufferLength = NULL if you don't care about the actual size. + /// Pass @a out_bufferLength = nullptr if you don't care about the actual size. /// /// @param[out] out_buffer /// The buffer to fill in with the string. /// It is assumed that this is preallocated to at least @a bufferLength wchars. - /// Pass @a out_buffer = NULL if you are only interested in finding out the necessary buffer size. + /// Pass @a out_buffer = nullptr if you are only interested in finding out the necessary buffer size. /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_UNEXPECTED: passed a NULL culture without a default culture being set first. + /// E_UNEXPECTED: passed a nullptr culture without a default culture being set first. /// E_INVALIDARG: senXML does not contain parsed XML data. /// E_FAIL: Failed to locate text. /// S_OK: Server call spawned successfully. @@ -291,14 +291,14 @@ namespace Sentient /// First method, filling a fixed-size buffer: /// /// wchar_t buffer[1234]; - /// SenBoxArtXMLGetTitle( xml, culture, _countof(buffer), NULL, buffer ); + /// SenBoxArtXMLGetTitle( xml, culture, _countof(buffer), nullptr, buffer ); /// /// Second method, filling a dynamically-allocated buffer: /// /// size_t bufferLength; - /// SenBoxArtXMLGetTitle( xml, culture, 0, &bufferLength, NULL ); + /// SenBoxArtXMLGetTitle( xml, culture, 0, &bufferLength, nullptr ); /// wchar_t buffer = new wchar_t[bufferLength]; - /// SenBoxArtXMLGetTitle( xml, culture, bufferLength, NULL, buffer ); + /// SenBoxArtXMLGetTitle( xml, culture, bufferLength, nullptr, buffer ); /// /// @related SenBoxArtDownloadXML() /// @related SenXMLParse() @@ -319,7 +319,7 @@ namespace Sentient /// /// @param[in] culture /// This is the result of a call to SenCultureFind() or SenCultureGet*(). - /// You may also pass NULL to use the culture set with SenCultureSetCurrent(). + /// You may also pass nullptr to use the culture set with SenCultureSetCurrent(). /// /// @param[in] bufferLength /// Note that bufferLength is in wchars, and needs to _include_ space for the terminating nul. @@ -327,16 +327,16 @@ namespace Sentient /// @param[out] out_bufferLength /// Used to return the actual number of wchars written to the buffer, including the terminating nul. /// The actual length of the _string_ is (*out_bufferLength - 1). - /// Pass @a out_bufferLength = NULL if you don't care about the actual size. + /// Pass @a out_bufferLength = nullptr if you don't care about the actual size. /// /// @param[out] out_buffer /// The buffer to fill in with the string. /// It is assumed that this is preallocated to at least @a bufferLength wchars. - /// Pass @a out_buffer = NULL if you are only interested in finding out the necessary buffer size. + /// Pass @a out_buffer = nullptr if you are only interested in finding out the necessary buffer size. /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_UNEXPECTED: passed a NULL culture without a default culture being set first. + /// E_UNEXPECTED: passed a nullptr culture without a default culture being set first. /// E_INVALIDARG: senXML does not contain parsed XML data. /// E_FAIL: Failed to locate text. /// S_OK: Server call spawned successfully. @@ -347,14 +347,14 @@ namespace Sentient /// First method, filling a fixed-size buffer: /// /// wchar_t buffer[1234]; - /// SenBoxArtXMLGetDescription( xml, culture, _countof(buffer), NULL, buffer ); + /// SenBoxArtXMLGetDescription( xml, culture, _countof(buffer), nullptr, buffer ); /// /// Second method, filling a dynamically-allocated buffer: /// /// size_t bufferLength; - /// SenBoxArtXMLGetDescription( xml, culture, 0, &bufferLength, NULL ); + /// SenBoxArtXMLGetDescription( xml, culture, 0, &bufferLength, nullptr ); /// wchar_t buffer = new wchar_t[bufferLength]; - /// SenBoxArtXMLGetDescription( xml, culture, bufferLength, NULL, buffer ); + /// SenBoxArtXMLGetDescription( xml, culture, bufferLength, nullptr, buffer ); /// /// @related SenBoxArtDownloadXML() /// @related SenXMLParse() @@ -390,7 +390,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: boxArtInfo.resourceID or boxArtInfo.image is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientConfig.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientConfig.h index 81c2f3cc6..0aca08ef3 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientConfig.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientConfig.h @@ -55,7 +55,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_configInfo is NULL. + /// E_POINTER: out_configInfo is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -95,7 +95,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// E_INVALIDARG: configInfo.resourceID or configInfo.config is invalid. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientCore.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientCore.h index f86eb92ae..4d3815d2a 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientCore.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientCore.h @@ -42,7 +42,7 @@ 3. Many functions are designed for asynchronous use, and will internally create a task that will only finish after feedback from the server. - a. These functions can be either blocking or asynchronous. If the callback pointer is NULL + a. These functions can be either blocking or asynchronous. If the callback pointer is nullptr then it is a blocking call. b. If the call is asynchronous, then it will always return instantly, and will return S_OK if a task has been created. diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientCultureBackCompat_SenClientUGC.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientCultureBackCompat_SenClientUGC.h index b36fd6e5e..02e255e86 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientCultureBackCompat_SenClientUGC.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientCultureBackCompat_SenClientUGC.h @@ -25,8 +25,8 @@ namespace Sentient /// /// @param[in] culture /// This is the result of a call to SenCultureFind() or SenCultureGet*(). - /// You may also pass NULL to use the culture set with SenCultureSetCurrent(). - /// May be NULL for default culture. + /// You may also pass nullptr to use the culture set with SenCultureSetCurrent(). + /// May be nullptr for default culture. /// /// @param[in] maxResults /// Used to indicate the number of items to be returned by @a out_feedInfo. diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientDynamicConfig.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientDynamicConfig.h index d6c5cb648..7b652aaef 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientDynamicConfig.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientDynamicConfig.h @@ -34,7 +34,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: size is NULL. + /// E_POINTER: size is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -66,7 +66,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: size is NULL. + /// E_POINTER: size is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -109,7 +109,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -149,7 +149,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_data is NULL. + /// E_POINTER: out_data is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientFame.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientFame.h index 1e823075f..8f07b1cef 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientFame.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientFame.h @@ -215,7 +215,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_userFameVIPArray is NULL. + /// E_POINTER: out_userFameVIPArray is nullptr. /// SENTIENT_E_TOO_MANY_CALLS: This call has been rejected to avoid excessive server load. Try again later. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. @@ -243,7 +243,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_fameVIPData is NULL. + /// E_POINTER: out_fameVIPData is nullptr. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_fameVIPData has not been filled in. /// S_OK: The operation completed successfully. /// @@ -304,8 +304,8 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_entryArray or out_leaderboardResults is NULL. - /// E_INVALIDARG: userCallback is NULL and out_senHandle is non-NULL. Task handles are not supported for synchronous requests. + /// E_POINTER: out_entryArray or out_leaderboardResults is nullptr. + /// E_INVALIDARG: userCallback is nullptr and out_senHandle is non-nullptr. Task handles are not supported for synchronous requests. /// SENTIENT_E_TOO_MANY_CALLS: This call has been rejected to avoid excessive server load. Try again later. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. @@ -331,7 +331,7 @@ namespace Sentient /// /// @return SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_awardData is NULL. + /// E_POINTER: out_awardData is nullptr. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_awardData has not been filled in. /// S_FALSE: The operation completed successfully but there were no awards to report. out_awardData has not been filled in. /// S_OK: The operation completed successfully and there was a valid award to report. out_awardData contains information about the award. @@ -351,7 +351,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_timeRemaining is NULL. + /// E_POINTER: out_timeRemaining is nullptr. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_timeRemaining has not been filled in. /// E_FAIL: Internal failure. Check log for output. /// S_OK: Call completed successfully and out_timeRemaining has been filled in. @@ -373,7 +373,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_timeRemaining is NULL. + /// E_POINTER: out_timeRemaining is nullptr. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_timeRemaining has not been filled in. /// S_FALSE: The VIP level of the supplied user does not expire. out_timeRemaining has not been filled in. /// E_FAIL: Internal failure. Check log for output. @@ -400,7 +400,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_name is NULL. + /// E_POINTER: out_name is nullptr. /// E_INVALIDARG: vipLevel is outside the range of known VIP levels. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_name has not been filled in. /// S_OK: The operation completed successfully. @@ -423,7 +423,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_count is NULL. + /// E_POINTER: out_count is nullptr. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and out_count has not been filled in. /// E_FAIL: Internal failure. Check log for output. /// S_OK: The operation completed successfully. @@ -456,7 +456,7 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_POINTER: out_dataCount or out_displayData is NULL. + /// E_POINTER: out_dataCount or out_displayData is nullptr. /// E_INVALIDARG: startIndex is greater than the total number of items available. /// SENTIENT_S_OPERATION_IN_PROGRESS: The call could not be completed immediately and output parameters have not been filled in. /// E_FAIL: Internal failure. Check log for output. @@ -553,8 +553,8 @@ namespace Sentient /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. /// SENTIENT_E_GUEST_ACCESS_VIOLATION: A guest may not spawn this call. - /// E_INVALIDARG: Either userCallback is NULL and out_senHandle is non-NULL, or participantCount is less than 2. - /// E_POINTER: participants is NULL. + /// E_INVALIDARG: Either userCallback is nullptr and out_senHandle is non-nullptr, or participantCount is less than 2. + /// E_POINTER: participants is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientResource.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientResource.h index e8405d5e1..b749a1640 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientResource.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientResource.h @@ -45,10 +45,10 @@ namespace Sentient enum SenResourceID : INT32 { /// This is used to indicate a failed search, an invalid resource structure, or sometimes to substitute for a default. - SenResourceID_Invalid = (INT32)SenResourceType_Invalid << 24, + SenResourceID_Invalid = static_cast(SenResourceType_Invalid) << 24, /// This is the first VIP reward costume and there is one for each title. - SenResourceID_Superstar_0 = (INT32)SenResourceType_Avatar << 24, + SenResourceID_Superstar_0 = static_cast(SenResourceType_Avatar) << 24, /// This is the second VIP reward costume and there is one for each title. SenResourceID_Superstar_1, /// This is the third VIP reward costume and there is one for each title. @@ -59,15 +59,15 @@ namespace Sentient SenResourceID_Superstar_4, /// This is used for the cross-sell screen and contains things such as an image, offerID, strings, etc. - SenResourceID_BoxArt_0 = (INT32)SenResourceType_BoxArt << 24, + SenResourceID_BoxArt_0 = static_cast(SenResourceType_BoxArt) << 24, /// This is used for game-private config files, and is only the base of the range. /// Titles may use the entire 24-bit space for various custom config files. - SenResourceID_Config_0 = (INT32)SenResourceType_Config << 24, + SenResourceID_Config_0 = static_cast(SenResourceType_Config) << 24, /// This is used for server-supplied help files/text. /// At the moment, this is not supported. - SenResourceID_Help_0 = (INT32)SenResourceType_Help << 24, + SenResourceID_Help_0 = static_cast(SenResourceType_Help) << 24, }; diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientUGC.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientUGC.h index da1b1f65d..b40245710 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientUGC.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientUGC.h @@ -97,7 +97,7 @@ namespace Sentient // metadata for a lot of UGCs at once. // Note: if a level has been uploaded with main data before, and the creator // wants to just modify the metadata, they can upload the metadata with the - // maindatablobs being NULL. + // maindatablobs being nullptr. // NOTE: for large items, use the SenUGCUploadMainData method with the SenUGCProgressInfo // signature so you can get the running progress and a cancellation token // to abort the upload (allowing UI for the user, etc) @@ -159,7 +159,7 @@ namespace Sentient // be used to abort the upload. This is useful for large uploads where // you may want to allow the user to cancel. // NOTE: This call is asynchronous ONLY and will error for synchronous - // attempts with a NULL param for userCallback. + // attempts with a nullptr param for userCallback. // There are multiple data blobs supported (the exact number is defined in // SenUGCMainData_NrBlobs) on subsequent calls. Slot zero is to be used by a // game to store a preview thumbnail, which can then be downloaded without @@ -172,7 +172,7 @@ namespace Sentient // metadata for a lot of UGCs at once. // NOTE: if a level has been uploaded with main data before, and the creator // wants to just modify the metadata, they can upload the metadata with the - // main data blob being NULL. + // main data blob being nullptr. // NOTE: If a creator uploads a data blob again, it will overwrite the previous // stored blob with the new one. //************************************ @@ -848,8 +848,8 @@ namespace Sentient /// /// @param[in] culture /// This is the result of a call to SenCultureFind() or SenCultureGet*(). - /// You may also pass NULL to use the culture set with SenCultureSetCurrent(). - /// May be NULL for default culture. + /// You may also pass nullptr to use the culture set with SenCultureSetCurrent(). + /// May be nullptr for default culture. /// /// @param[in] maxResults /// Used to indicate the number of items to be returned by @a out_feedInfo. diff --git a/Minecraft.Client/Xbox/Sentient/Include/SenClientUser.h b/Minecraft.Client/Xbox/Sentient/Include/SenClientUser.h index cf3ef0b3e..4c48ee501 100644 --- a/Minecraft.Client/Xbox/Sentient/Include/SenClientUser.h +++ b/Minecraft.Client/Xbox/Sentient/Include/SenClientUser.h @@ -61,7 +61,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_isInRole is NULL. + /// E_POINTER: out_isInRole is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// @@ -91,7 +91,7 @@ namespace Sentient /// /// @return Check SUCCEEDED( hresult ) or FAILED( hresult ) to determine success. Specific values include: /// SENTIENT_E_NOT_INITIALIZED: You did not call SentientInitialize() first. - /// E_POINTER: out_isInRole is NULL. + /// E_POINTER: out_isInRole is nullptr. /// E_FAIL: Failed to spawn server call. /// S_OK: Server call spawned successfully. /// diff --git a/Minecraft.Client/Xbox/Sentient/SentientManager.cpp b/Minecraft.Client/Xbox/Sentient/SentientManager.cpp index aade06bca..49b0c26af 100644 --- a/Minecraft.Client/Xbox/Sentient/SentientManager.cpp +++ b/Minecraft.Client/Xbox/Sentient/SentientManager.cpp @@ -20,7 +20,7 @@ CTelemetryManager *TelemetryManager = new CSentientManager(); HRESULT CSentientManager::Init() { Sentient::SenSysTitleID sentitleID; - sentitleID = (Sentient::SenSysTitleID)TITLEID_MINECRAFT; + sentitleID = static_cast(TITLEID_MINECRAFT); HRESULT hr = SentientInitialize( sentitleID ); @@ -52,7 +52,7 @@ HRESULT CSentientManager::Tick() m_lastHeartbeat = currentTime; for(DWORD i = 0; i < XUSER_MAX_COUNT; ++i) { - if(Minecraft::GetInstance()->localplayers[i] != NULL) + if(Minecraft::GetInstance()->localplayers[i] != nullptr) { SenStatHeartBeat(i, m_lastHeartbeat - m_initialiseTime); } @@ -63,7 +63,7 @@ HRESULT CSentientManager::Tick() { for(DWORD i = 0; i < XUSER_MAX_COUNT; ++i) { - if(Minecraft::GetInstance()->localplayers[i] != NULL && m_fLevelStartTime[i] - currentTime > 60) + if(Minecraft::GetInstance()->localplayers[i] != nullptr && m_fLevelStartTime[i] - currentTime > 60) { Flush(); } @@ -123,7 +123,7 @@ HRESULT CSentientManager::Flush() BOOL CSentientManager::RecordPlayerSessionStart(DWORD dwUserId) { - return SenStatPlayerSessionStart( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetTitleBuildId(), 0, 0, 0, (INT)app.getDeploymentType() ); + return SenStatPlayerSessionStart( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetTitleBuildId(), 0, 0, 0, static_cast(app.getDeploymentType()) ); } BOOL CSentientManager::RecordPlayerSessionExit(DWORD dwUserId, int _) @@ -149,13 +149,13 @@ BOOL CSentientManager::RecordLevelStart(DWORD dwUserId, ESen_FriendOrMatch frien BOOL CSentientManager::RecordLevelExit(DWORD dwUserId, ESen_LevelExitStatus levelExitStatus) { float levelDuration = app.getAppTime() - m_fLevelStartTime[dwUserId]; - return SenStatLevelExit( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetLevelInstanceID(), GetMultiplayerInstanceID(), levelExitStatus, GetLevelExitProgressStat1(), GetLevelExitProgressStat2(), (INT)levelDuration ); + return SenStatLevelExit( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetLevelInstanceID(), GetMultiplayerInstanceID(), levelExitStatus, GetLevelExitProgressStat1(), GetLevelExitProgressStat2(), static_cast(levelDuration) ); } BOOL CSentientManager::RecordLevelSaveOrCheckpoint(DWORD dwUserId, INT saveOrCheckPointID, INT saveSizeInBytes) { float levelDuration = app.getAppTime() - m_fLevelStartTime[dwUserId]; - return SenStatLevelSaveOrCheckpoint( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetLevelInstanceID(), GetMultiplayerInstanceID(), GetLevelExitProgressStat1(), GetLevelExitProgressStat2(), (INT)levelDuration, saveOrCheckPointID, saveSizeInBytes ); + return SenStatLevelSaveOrCheckpoint( dwUserId, GetSecondsSinceInitialize(), GetMode(dwUserId), GetSubMode(dwUserId), GetLevelId(dwUserId), GetSubLevelId(dwUserId), GetLevelInstanceID(), GetMultiplayerInstanceID(), GetLevelExitProgressStat1(), GetLevelExitProgressStat2(), static_cast(levelDuration), saveOrCheckPointID, saveSizeInBytes ); } BOOL CSentientManager::RecordLevelResume(DWORD dwUserId, ESen_FriendOrMatch friendsOrMatch, ESen_CompeteOrCoop competeOrCoop, int difficulty, DWORD numberOfLocalPlayers, DWORD numberOfOnlinePlayers, INT saveOrCheckPointID) @@ -240,7 +240,7 @@ This should be tracked independently of saved games (restoring a save should not */ INT CSentientManager::GetSecondsSinceInitialize() { - return (INT)(app.getAppTime() - m_initialiseTime); + return static_cast(app.getAppTime() - m_initialiseTime); } /* @@ -257,21 +257,21 @@ INT CSentientManager::GetMode(DWORD dwUserId) Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->localplayers[dwUserId] != NULL && pMinecraft->localplayers[dwUserId]->level != NULL && pMinecraft->localplayers[dwUserId]->level->getLevelData() != NULL ) + if( pMinecraft->localplayers[dwUserId] != nullptr && pMinecraft->localplayers[dwUserId]->level != nullptr && pMinecraft->localplayers[dwUserId]->level->getLevelData() != nullptr ) { GameType *gameType = pMinecraft->localplayers[dwUserId]->level->getLevelData()->getGameType(); if (gameType->isSurvival()) { - mode = (INT)eTelem_ModeId_Survival; + mode = static_cast(eTelem_ModeId_Survival); } else if (gameType->isCreative()) { - mode = (INT)eTelem_ModeId_Creative; + mode = static_cast(eTelem_ModeId_Creative); } else { - mode = (INT)eTelem_ModeId_Undefined; + mode = static_cast(eTelem_ModeId_Undefined); } } return mode; @@ -290,11 +290,11 @@ INT CSentientManager::GetSubMode(DWORD dwUserId) if(Minecraft::GetInstance()->isTutorial()) { - subMode = (INT)eTelem_SubModeId_Tutorial; + subMode = static_cast(eTelem_SubModeId_Tutorial); } else { - subMode = (INT)eTelem_SubModeId_Normal; + subMode = static_cast(eTelem_SubModeId_Normal); } return subMode; @@ -312,7 +312,7 @@ INT CSentientManager::GetLevelId(DWORD dwUserId) { INT levelId = (INT)eTelem_LevelId_Undefined; - levelId = (INT)eTelem_LevelId_PlayerGeneratedLevel; + levelId = static_cast(eTelem_LevelId_PlayerGeneratedLevel); return levelId; } @@ -329,18 +329,18 @@ INT CSentientManager::GetSubLevelId(DWORD dwUserId) Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localplayers[dwUserId] != NULL) + if(pMinecraft->localplayers[dwUserId] != nullptr) { switch(pMinecraft->localplayers[dwUserId]->dimension) { case 0: - subLevelId = (INT)eTelem_SubLevelId_Overworld; + subLevelId = static_cast(eTelem_SubLevelId_Overworld); break; case -1: - subLevelId = (INT)eTelem_SubLevelId_Nether; + subLevelId = static_cast(eTelem_SubLevelId_Nether); break; case 1: - subLevelId = (INT)eTelem_SubLevelId_End; + subLevelId = static_cast(eTelem_SubLevelId_End); break; }; } @@ -364,7 +364,7 @@ Helps differentiate level attempts when a play plays the same mode/level - espec */ INT CSentientManager::GetLevelInstanceID() { - return (INT)m_levelInstanceID; + return static_cast(m_levelInstanceID); } /* @@ -403,19 +403,19 @@ INT CSentientManager::GetSingleOrMultiplayer() if(app.GetLocalPlayerCount() == 1 && g_NetworkManager.GetOnlinePlayerCount() == 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Single_Player; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Single_Player); } else if(app.GetLocalPlayerCount() > 1 && g_NetworkManager.GetOnlinePlayerCount() == 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Local; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Local); } else if(app.GetLocalPlayerCount() == 1 && g_NetworkManager.GetOnlinePlayerCount() > 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Live; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Live); } else if(app.GetLocalPlayerCount() > 1 && g_NetworkManager.GetOnlinePlayerCount() > 0) { - singleOrMultiplayer = (INT)eSen_SingleOrMultiplayer_Multiplayer_Both_Local_and_Live; + singleOrMultiplayer = static_cast(eSen_SingleOrMultiplayer_Multiplayer_Both_Local_and_Live); } return singleOrMultiplayer; @@ -432,16 +432,16 @@ INT CSentientManager::GetDifficultyLevel(INT diff) switch(diff) { case 0: - difficultyLevel = (INT)eSen_DifficultyLevel_Easiest; + difficultyLevel = static_cast(eSen_DifficultyLevel_Easiest); break; case 1: - difficultyLevel = (INT)eSen_DifficultyLevel_Easier; + difficultyLevel = static_cast(eSen_DifficultyLevel_Easier); break; case 2: - difficultyLevel = (INT)eSen_DifficultyLevel_Normal; + difficultyLevel = static_cast(eSen_DifficultyLevel_Normal); break; case 3: - difficultyLevel = (INT)eSen_DifficultyLevel_Harder; + difficultyLevel = static_cast(eSen_DifficultyLevel_Harder); break; } @@ -461,11 +461,11 @@ INT CSentientManager::GetLicense() if(ProfileManager.IsFullVersion()) { - license = (INT)eSen_License_Full_Purchased_Title; + license = static_cast(eSen_License_Full_Purchased_Title); } else { - license = (INT)eSen_License_Trial_or_Demo; + license = static_cast(eSen_License_Trial_or_Demo); } return license; } @@ -500,15 +500,15 @@ INT CSentientManager::GetAudioSettings(DWORD dwUserId) if(volume == 0) { - audioSettings = (INT)eSen_AudioSettings_Off; + audioSettings = static_cast(eSen_AudioSettings_Off); } else if(volume == DEFAULT_VOLUME_LEVEL) { - audioSettings = (INT)eSen_AudioSettings_On_Default; + audioSettings = static_cast(eSen_AudioSettings_On_Default); } else { - audioSettings = (INT)eSen_AudioSettings_On_CustomSetting; + audioSettings = static_cast(eSen_AudioSettings_On_CustomSetting); } } return audioSettings; diff --git a/Minecraft.Client/Xbox/Sentient/SentientStats.cpp b/Minecraft.Client/Xbox/Sentient/SentientStats.cpp index 361d18eed..ffa9392d8 100644 --- a/Minecraft.Client/Xbox/Sentient/SentientStats.cpp +++ b/Minecraft.Client/Xbox/Sentient/SentientStats.cpp @@ -37,8 +37,8 @@ BOOL SenStatPlayerSessionStart ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 10; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -67,8 +67,8 @@ BOOL SenStatPlayerSessionExit ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 5; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -93,8 +93,8 @@ BOOL SenStatHeartBeat ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 1; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -136,8 +136,8 @@ BOOL SenStatLevelStart ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 18; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -172,8 +172,8 @@ BOOL SenStatLevelExit ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 11; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -209,8 +209,8 @@ BOOL SenStatLevelSaveOrCheckpoint ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 12; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -253,8 +253,8 @@ BOOL SenStatLevelResume ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 19; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -285,8 +285,8 @@ BOOL SenStatPauseOrInactive ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 7; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -317,8 +317,8 @@ BOOL SenStatUnpauseOrActive ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 7; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -351,8 +351,8 @@ BOOL SenStatMenuShown ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 9; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -385,8 +385,8 @@ BOOL SenStatAchievementUnlocked ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 9; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -419,8 +419,8 @@ BOOL SenStatMediaShareUpload ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 9; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -453,8 +453,8 @@ BOOL SenStatUpsellPresented ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 9; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -488,8 +488,8 @@ BOOL SenStatUpsellResponded ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 10; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -607,8 +607,8 @@ BOOL SenStatSkinChanged ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 8; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -639,8 +639,8 @@ BOOL SenStatBanLevel ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 7; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -671,8 +671,8 @@ BOOL SenStatUnBanLevel ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 7; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing @@ -705,8 +705,8 @@ BOOL SenStatTexturePackChanged ( DWORD dwUserID, INT SecondsSinceI st.dwNumProperties = 9; st.arrProperties = (CHAR*)&LocalStruct; st.dwNumValues = 0; - st.arrValues = NULL; - st.arrValueFlags = NULL; + st.arrValues = nullptr; + st.arrValueFlags = nullptr; #ifdef SEN_LOGTELEMETRY // if we're in debug build with logging then log the stat to a file for testing diff --git a/Minecraft.Client/Xbox/Social/SocialManager.cpp b/Minecraft.Client/Xbox/Social/SocialManager.cpp index b7a108bc7..b89fda709 100644 --- a/Minecraft.Client/Xbox/Social/SocialManager.cpp +++ b/Minecraft.Client/Xbox/Social/SocialManager.cpp @@ -67,14 +67,14 @@ CSocialManager::CSocialManager() // WESTY : Not sure if we even need to get social access key! /* - m_pAccessKeyText = NULL; + m_pAccessKeyText = nullptr; m_dwAccessKeyTextSize = 0; */ - m_pMainImageBuffer = NULL; + m_pMainImageBuffer = nullptr; m_dwMainImageBufferSize = 0; - m_PostPreviewImage.pBytes = NULL; + m_PostPreviewImage.pBytes = nullptr; m_dwCurrRequestUser = -1; ZeroMemory(m_wchTitleA,sizeof(WCHAR)*MAX_SOCIALPOST_CAPTION); @@ -304,14 +304,14 @@ bool CSocialManager::AreAllUsersAllowedToPostImages() void CSocialManager::DestroyMainPostImage() { delete [] m_PostImageParams.pFullImage; - m_PostImageParams.pFullImage=NULL; + m_PostImageParams.pFullImage=nullptr; m_dwMainImageBufferSize=0; } void CSocialManager::DestroyPreviewPostImage() { XPhysicalFree( (void *)m_PostPreviewImage.pBytes ); - m_PostPreviewImage.pBytes = NULL; + m_PostPreviewImage.pBytes = nullptr; } void CSocialManager::SetSocialPostText(LPCWSTR pwchTitle, LPCWSTR pwchCaption, LPCWSTR pwchDesc) @@ -459,7 +459,7 @@ bool CSocialManager::PostImageToSocialNetwork( ESocialNetwork eSocialNetwork, DW bool bResult = false; - PBYTE pbData=NULL; + PBYTE pbData=nullptr; DWORD dwDataSize; app.GetScreenshot(dwUserIndex,&pbData,&dwDataSize); @@ -536,10 +536,10 @@ bool CSocialManager::GetSocialNetworkAccessKey( ESocialNetwork eSocialNetwork, D DWORD dwResult; // Ensure that we free any previously used access key buffer. - if ( m_pAccessKeyText != NULL ) + if ( m_pAccessKeyText != nullptr ) { delete [] m_pAccessKeyText; - m_pAccessKeyText = NULL; + m_pAccessKeyText = nullptr; } // Get social network ID and permissions. @@ -554,39 +554,39 @@ bool CSocialManager::GetSocialNetworkAccessKey( ESocialNetwork eSocialNetwork, D { if ( bUsingKinect ) { - dwResult = XShowNuiSocialGetUserToken( dwUserTrackingIndex, dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XShowNuiSocialGetUserToken( dwUserTrackingIndex, dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); // If buffer for key text was not large enough, reallocate buffer that is large enough and try again. if ( dwResult == ERROR_INSUFFICIENT_BUFFER ) { delete [] m_pAccessKeyText; m_pAccessKeyText = new wchar_t[ m_dwAccessKeyTextSize ]; - dwResult = XShowNuiSocialGetUserToken( dwUserTrackingIndex, dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XShowNuiSocialGetUserToken( dwUserTrackingIndex, dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); } } else // using standard controller interface. { - dwResult = XShowSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XShowSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); // If buffer for key text was not large enough, reallocate buffer that is large enough and try again. if ( dwResult == ERROR_INSUFFICIENT_BUFFER ) { delete [] m_pAccessKeyText; m_pAccessKeyText = new wchar_t[ m_dwAccessKeyTextSize ]; - dwResult = XShowSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XShowSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); } } } else // we are trying to obtain cached user access key. { - dwResult = XSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); // If buffer for key text was not large enough, reallocate buffer that is large enough and try again. if ( dwResult == ERROR_INSUFFICIENT_BUFFER ) { delete [] m_pAccessKeyText; m_pAccessKeyText = new wchar_t[ m_dwAccessKeyTextSize ]; - dwResult = XSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), NULL ); + dwResult = XSocialGetUserToken( dwUserIndex, dwSocialNetworkID, pRequiredPermissions, m_pAccessKeyText, &( m_dwAccessKeyTextSize ), nullptr ); } } diff --git a/Minecraft.Client/Xbox/XML/ATGXmlParser.cpp b/Minecraft.Client/Xbox/XML/ATGXmlParser.cpp index cfa92064f..fd8781ea0 100644 --- a/Minecraft.Client/Xbox/XML/ATGXmlParser.cpp +++ b/Minecraft.Client/Xbox/XML/ATGXmlParser.cpp @@ -27,7 +27,7 @@ XMLParser::XMLParser() { m_pWritePtr = m_pWriteBuf; m_pReadPtr = m_pReadBuf; - m_pISAXCallback = NULL; + m_pISAXCallback = nullptr; m_hFile = INVALID_HANDLE_VALUE; } @@ -49,7 +49,7 @@ VOID XMLParser::FillBuffer() m_pReadPtr = m_pReadBuf; - if( m_hFile == NULL ) + if( m_hFile == nullptr ) { if( m_uInXMLBufferCharsLeft > XML_READ_BUFFER_SIZE ) NChars = XML_READ_BUFFER_SIZE; @@ -62,15 +62,15 @@ VOID XMLParser::FillBuffer() } else { - if( !ReadFile( m_hFile, m_pReadBuf, XML_READ_BUFFER_SIZE, &NChars, NULL )) + if( !ReadFile( m_hFile, m_pReadBuf, XML_READ_BUFFER_SIZE, &NChars, nullptr )) { return; } } m_dwCharsConsumed += NChars; - int64_t iProgress = m_dwCharsTotal ? (( (int64_t)m_dwCharsConsumed * 1000 ) / (int64_t)m_dwCharsTotal) : 0; - m_pISAXCallback->SetParseProgress( (DWORD)iProgress ); + int64_t iProgress = m_dwCharsTotal ? (( static_cast(m_dwCharsConsumed) * 1000 ) / static_cast(m_dwCharsTotal)) : 0; + m_pISAXCallback->SetParseProgress( static_cast(iProgress) ); m_pReadBuf[ NChars ] = '\0'; m_pReadBuf[ NChars + 1] = '\0'; @@ -192,30 +192,29 @@ HRESULT XMLParser::ConvertEscape() // must be an entity reference WCHAR *pEntityRefVal = m_pWritePtr; - UINT EntityRefLen; SkipNextAdvance(); if( FAILED( hr = AdvanceName() ) ) return hr; - EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal ); + const UINT entityRefLen = static_cast(m_pWritePtr - pEntityRefVal); m_pWritePtr = pEntityRefVal; - if ( EntityRefLen == 0 ) + if ( entityRefLen == 0 ) { Error( E_INVALID_XML_SYNTAX, "Expecting entity name after &" ); return E_INVALID_XML_SYNTAX; } - if( !wcsncmp( pEntityRefVal, L"lt", EntityRefLen ) ) + if( !wcsncmp( pEntityRefVal, L"lt", entityRefLen ) ) wVal = '<'; - else if( !wcsncmp( pEntityRefVal, L"gt", EntityRefLen ) ) + else if( !wcsncmp( pEntityRefVal, L"gt", entityRefLen ) ) wVal = '>'; - else if( !wcsncmp( pEntityRefVal, L"amp", EntityRefLen ) ) + else if( !wcsncmp( pEntityRefVal, L"amp", entityRefLen ) ) wVal = '&'; - else if( !wcsncmp( pEntityRefVal, L"apos", EntityRefLen ) ) + else if( !wcsncmp( pEntityRefVal, L"apos", entityRefLen ) ) wVal = '\''; - else if( !wcsncmp( pEntityRefVal, L"quot", EntityRefLen ) ) + else if( !wcsncmp( pEntityRefVal, L"quot", entityRefLen ) ) wVal = '"'; else { @@ -359,7 +358,7 @@ HRESULT XMLParser::AdvanceCharacter( BOOL bOkToFail ) // Read more from the file FillBuffer(); - // We are at EOF if it is still NULL + // We are at EOF if it is still nullptr if ( ( m_pReadPtr[0] == '\0' ) && ( m_pReadPtr[1] == '\0' ) ) { if( !bOkToFail ) @@ -498,7 +497,7 @@ HRESULT XMLParser::AdvanceElement() return hr; if( FAILED( m_pISAXCallback->ElementEnd( pEntityRefVal, - (UINT) ( m_pWritePtr - pEntityRefVal ) ) ) ) + static_cast(m_pWritePtr - pEntityRefVal) ) ) ) return E_ABORT; if( FAILED( hr = ConsumeSpace() ) ) @@ -541,7 +540,7 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceName() ) ) return hr; - EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal ); + EntityRefLen = static_cast(m_pWritePtr - pEntityRefVal); if( FAILED( hr = ConsumeSpace() ) ) return hr; @@ -565,8 +564,7 @@ HRESULT XMLParser::AdvanceElement() // Attribute name if( FAILED( hr = AdvanceName() ) ) return hr; - - Attributes[ NumAttrs ].NameLen = (UINT)( m_pWritePtr - Attributes[ NumAttrs ].strName ); + Attributes[ NumAttrs ].NameLen = static_cast(m_pWritePtr - Attributes[NumAttrs].strName); if( FAILED( hr = ConsumeSpace() ) ) return hr; @@ -588,9 +586,8 @@ HRESULT XMLParser::AdvanceElement() if( FAILED( hr = AdvanceAttrVal() ) ) return hr; - Attributes[ NumAttrs ].ValueLen = (UINT)( m_pWritePtr - - Attributes[ NumAttrs ].strValue ); - + Attributes[ NumAttrs ].ValueLen = static_cast(m_pWritePtr - + Attributes[NumAttrs].strValue); ++NumAttrs; if( FAILED( hr = ConsumeSpace() ) ) @@ -663,13 +660,13 @@ HRESULT XMLParser::AdvanceCDATA() if( m_pWritePtr - m_pWriteBuf >= XML_WRITE_BUFFER_SIZE ) { - if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), TRUE ) ) ) + if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), TRUE ) ) ) return E_ABORT; m_pWritePtr = m_pWriteBuf; } } - if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; m_pWritePtr = m_pWriteBuf; @@ -782,9 +779,9 @@ HRESULT XMLParser::MainParseLoop() { if( FAILED( AdvanceCharacter( TRUE ) ) ) { - if ( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) ) + if ( ( static_cast(m_pWritePtr - m_pWriteBuf) != 0 ) && ( !bWhiteSpaceOnly ) ) { - if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; bWhiteSpaceOnly = TRUE; @@ -798,9 +795,9 @@ HRESULT XMLParser::MainParseLoop() if( m_Ch == '<' ) { - if( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) ) + if( ( static_cast(m_pWritePtr - m_pWriteBuf) != 0 ) && ( !bWhiteSpaceOnly ) ) { - if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) ) + if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, static_cast(m_pWritePtr - m_pWriteBuf), FALSE ) ) ) return E_ABORT; bWhiteSpaceOnly = TRUE; @@ -838,7 +835,7 @@ HRESULT XMLParser::MainParseLoop() if( !bWhiteSpaceOnly ) { if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, - ( UINT ) ( m_pWritePtr - m_pWriteBuf ), + static_cast(m_pWritePtr - m_pWriteBuf), TRUE ) ) ) { return E_ABORT; @@ -861,7 +858,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) { HRESULT hr; - if( m_pISAXCallback == NULL ) + if( m_pISAXCallback == nullptr ) return E_NOINTERFACE; m_pISAXCallback->m_LineNum = 1; @@ -872,11 +869,12 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) m_pReadPtr = m_pReadBuf; m_pReadBuf[ 0 ] = '\0'; + m_pReadBuf[ 1 ] = '\0'; - m_pInXMLBuffer = NULL; + m_pInXMLBuffer = nullptr; m_uInXMLBufferCharsLeft = 0; - m_hFile = CreateFile( strFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + m_hFile = CreateFile( strFilename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if( m_hFile == INVALID_HANDLE_VALUE ) { @@ -888,7 +886,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) { LARGE_INTEGER iFileSize; GetFileSizeEx( m_hFile, &iFileSize ); - m_dwCharsTotal = (DWORD)iFileSize.QuadPart; + m_dwCharsTotal = static_cast(iFileSize.QuadPart); m_dwCharsConsumed = 0; hr = MainParseLoop(); } @@ -899,7 +897,7 @@ HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename ) m_hFile = INVALID_HANDLE_VALUE; // we no longer own strFilename, so un-set it - m_pISAXCallback->m_strFilename = NULL; + m_pISAXCallback->m_strFilename = nullptr; return hr; } @@ -912,7 +910,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) { HRESULT hr; - if( m_pISAXCallback == NULL ) + if( m_pISAXCallback == nullptr) return E_NOINTERFACE; m_pISAXCallback->m_LineNum = 1; @@ -925,7 +923,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) m_pReadBuf[ 0 ] = '\0'; m_pReadBuf[ 1 ] = '\0'; - m_hFile = NULL; + m_hFile = nullptr; m_pInXMLBuffer = strBuffer; m_uInXMLBufferCharsLeft = uBufferSize; m_dwCharsTotal = uBufferSize; @@ -934,7 +932,7 @@ HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize ) hr = MainParseLoop(); // we no longer own strFilename, so un-set it - m_pISAXCallback->m_strFilename = NULL; + m_pISAXCallback->m_strFilename = nullptr; return hr; } diff --git a/Minecraft.Client/Xbox/XML/ATGXmlParser.h b/Minecraft.Client/Xbox/XML/ATGXmlParser.h index 75142e3e3..12f597372 100644 --- a/Minecraft.Client/Xbox/XML/ATGXmlParser.h +++ b/Minecraft.Client/Xbox/XML/ATGXmlParser.h @@ -138,7 +138,7 @@ private: DWORD m_dwCharsTotal; DWORD m_dwCharsConsumed; - BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing NULL + BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing nullptr WCHAR m_pWriteBuf[ XML_WRITE_BUFFER_SIZE ]; BYTE* m_pReadPtr; diff --git a/Minecraft.Client/Xbox/XML/xmlFilesCallback.h b/Minecraft.Client/Xbox/XML/xmlFilesCallback.h index 2ea670dfb..7571706e3 100644 --- a/Minecraft.Client/Xbox/XML/xmlFilesCallback.h +++ b/Minecraft.Client/Xbox/XML/xmlFilesCallback.h @@ -47,7 +47,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - xuid=_wcstoui64(wTemp,NULL,10); + xuid=_wcstoui64(wTemp,nullptr,10); } } else if (_wcsicmp(wAttName,L"cape")==0) @@ -138,7 +138,7 @@ public: #ifdef _XBOX iValue=_wtoi(wValue); #else - iValue=wcstol(wValue, NULL, 10); + iValue=wcstol(wValue, nullptr, 10); #endif } } @@ -220,7 +220,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - uiSortIndex=wcstoul(wTemp,NULL,16); + uiSortIndex=wcstoul(wTemp,nullptr,16); } } else if (_wcsicmp(wAttName,L"Banner")==0) @@ -236,7 +236,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - ullFull=_wcstoui64(wTemp,NULL,16); + ullFull=_wcstoui64(wTemp,nullptr,16); } } else if (_wcsicmp(wAttName,L"Trial")==0) @@ -245,7 +245,7 @@ public: { ZeroMemory(wTemp,sizeof(WCHAR)*35); wcsncpy_s( wTemp, pAttributes[i].strValue, pAttributes[i].ValueLen); - ullTrial=_wcstoui64(wTemp,NULL,16); + ullTrial=_wcstoui64(wTemp,nullptr,16); } } else if (_wcsicmp(wAttName,L"FirstSkin")==0) @@ -286,7 +286,7 @@ public: #ifdef _XBOX iConfig=_wtoi(wConfig); #else - iConfig=wcstol(wConfig, NULL, 10); + iConfig=wcstol(wConfig, nullptr, 10); #endif } } diff --git a/Minecraft.Client/Xbox/Xbox_App.cpp b/Minecraft.Client/Xbox/Xbox_App.cpp index eebeb827f..a717540bc 100644 --- a/Minecraft.Client/Xbox/Xbox_App.cpp +++ b/Minecraft.Client/Xbox/Xbox_App.cpp @@ -284,10 +284,10 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_bRead_TMS_XUIDS_XML=false; m_bRead_TMS_Config_XML=false; m_bRead_TMS_DLCINFO_XML=false; - m_pXuidsFileBuffer=NULL; + m_pXuidsFileBuffer=nullptr; m_dwXuidsFileSize=0; ZeroMemory(m_ScreenshotBuffer,sizeof(LPD3DXBUFFER)*XUSER_MAX_COUNT); - m_ThumbnailBuffer=NULL; + m_ThumbnailBuffer=nullptr; #ifdef _DEBUG_MENUS_ENABLED debugOverlayCreated = false; #endif @@ -301,12 +301,12 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_bContainerMenuDisplayed[i]=false; m_bIgnoreAutosaveMenuDisplayed[i]=false; m_bIgnorePlayerJoinMenuDisplayed[i]=false; - m_hCurrentScene[i]=NULL; - m_hFirstScene[i]=NULL; + m_hCurrentScene[i]=nullptr; + m_hFirstScene[i]=nullptr; } m_titleDeploymentType = XTITLE_DEPLOYMENT_DOWNLOAD; - DWORD dwResult = XTitleGetDeploymentType(&m_titleDeploymentType, NULL); + DWORD dwResult = XTitleGetDeploymentType(&m_titleDeploymentType, nullptr); if( dwResult == ERROR_SUCCESS ) { switch( m_titleDeploymentType ) @@ -658,7 +658,7 @@ void CConsoleMinecraftApp::GetPreviewImage(int iPad,XSOCIAL_PREVIEWIMAGE *previe preview->pBytes = (BYTE *)XPhysicalAlloc(sizeBytes, MAXULONG_PTR, 0, PAGE_READWRITE | PAGE_WRITECOMBINE ); memcpy( (void *)preview->pBytes, (void *)m_PreviewBuffer[iPad].pBytes, sizeBytes ); XPhysicalFree((LPVOID)m_PreviewBuffer[iPad].pBytes); - m_PreviewBuffer[iPad].pBytes = NULL; + m_PreviewBuffer[iPad].pBytes = nullptr; } void CConsoleMinecraftApp::CaptureScreenshot(int iPad) @@ -678,7 +678,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() HRESULT hr; // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); //#ifdef _CONTENT_PACKAGE @@ -894,7 +894,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() // int iStringC=0; // LPCWSTR lpTempString; // - // while((lpTempString=StringTable.Lookup(iStringC))!=NULL) + // while((lpTempString=StringTable.Lookup(iStringC))!=nullptr) // { // DebugPrintf("STRING %d = ",iStringC); // OutputDebugStringW(lpTempString); @@ -914,17 +914,17 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); if(RenderManager.IsHiDef()) { - hr=LoadFirstScene( szResourceLocator, L"xuiscene_base.xur", NULL, &mainBaseScene ); + hr=LoadFirstScene( szResourceLocator, L"xuiscene_base.xur", nullptr, &mainBaseScene ); } else { if(RenderManager.IsWidescreen()) { - hr=LoadFirstScene( szResourceLocator, L"xuiscene_base.xur", NULL, &mainBaseScene ); + hr=LoadFirstScene( szResourceLocator, L"xuiscene_base.xur", nullptr, &mainBaseScene ); } else { - hr=LoadFirstScene( szResourceLocator, L"xuiscene_base_480.xur", NULL, &mainBaseScene ); + hr=LoadFirstScene( szResourceLocator, L"xuiscene_base_480.xur", nullptr, &mainBaseScene ); } } if( FAILED(hr) ) app.FatalLoadError(); @@ -989,7 +989,7 @@ HRESULT CConsoleMinecraftApp::RegisterFont(eFont eFontLanguage,eFont eFontFallba HRESULT hr=S_OK; 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); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", wchTypefaceLocatorA[eFontLanguage]); // 4J Stu - Check that the font file actually exists @@ -1003,7 +1003,7 @@ HRESULT CConsoleMinecraftApp::RegisterFont(eFont eFontLanguage,eFont eFontFallba { if(eFontFallback!=eFont_None) { - hr = RegisterDefaultTypeface( wchTypefaceA[eFontLanguage],szResourceLocator,NULL,0.0f,wchTypefaceA[eFontFallback]); + hr = RegisterDefaultTypeface( wchTypefaceA[eFontLanguage],szResourceLocator,nullptr,0.0f,wchTypefaceA[eFontFallback]); } else { @@ -1410,7 +1410,7 @@ void CConsoleMinecraftApp::OverrideFontRenderer(bool set, bool immediate) } else { - XuiFontSetRenderer( NULL ); + XuiFontSetRenderer( nullptr ); } m_bFontRendererOverridden = set; @@ -1451,7 +1451,7 @@ void CConsoleMinecraftApp::CaptureSaveThumbnail() void CConsoleMinecraftApp::GetSaveThumbnail(PBYTE *pbData,DWORD *pdwSize) { // on a save caused by a create world, the thumbnail capture won't have happened - if(m_ThumbnailBuffer!=NULL) + if(m_ThumbnailBuffer!=nullptr) { if( pbData ) { @@ -1460,28 +1460,28 @@ void CConsoleMinecraftApp::GetSaveThumbnail(PBYTE *pbData,DWORD *pdwSize) memcpy(*pbData,m_ThumbnailBuffer->GetBufferPointer(),*pdwSize); } m_ThumbnailBuffer->Release(); - m_ThumbnailBuffer=NULL; + m_ThumbnailBuffer=nullptr; } } void CConsoleMinecraftApp::ReleaseSaveThumbnail() { - if(m_ThumbnailBuffer!=NULL) + if(m_ThumbnailBuffer!=nullptr) { m_ThumbnailBuffer->Release(); - m_ThumbnailBuffer=NULL; + m_ThumbnailBuffer=nullptr; } } void CConsoleMinecraftApp::GetScreenshot(int iPad,PBYTE *pbData,DWORD *pdwSize) { // on a save caused by a create world, the thumbnail capture won't have happened - if(m_ScreenshotBuffer[iPad]!=NULL) + if(m_ScreenshotBuffer[iPad]!=nullptr) { *pbData= new BYTE [m_ScreenshotBuffer[iPad]->GetBufferSize()]; *pdwSize=m_ScreenshotBuffer[iPad]->GetBufferSize(); memcpy(*pbData,m_ScreenshotBuffer[iPad]->GetBufferPointer(),*pdwSize); m_ScreenshotBuffer[iPad]->Release(); - m_ScreenshotBuffer[iPad]=NULL; + m_ScreenshotBuffer[iPad]=nullptr; } } @@ -1492,13 +1492,13 @@ void CConsoleMinecraftApp::EnableDebugOverlay(bool enable,int iPad) if(enable && !debugOverlayCreated) { - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); 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/"); - hr = XuiSceneCreate(szResourceLocator, L"xuiscene_debugoverlay.xur", NULL, &m_hDebugOverlay); + hr = XuiSceneCreate(szResourceLocator, L"xuiscene_debugoverlay.xur", nullptr, &m_hDebugOverlay); debugContainerScene.AddChild(m_hDebugOverlay); debugContainerScene.SetShow(false); @@ -1644,7 +1644,7 @@ WCHAR *CConsoleMinecraftApp::GetSceneName(EUIScene eScene,bool bAppendToName,boo return m_SceneName; } -HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *initData /* = NULL */, bool forceUsePad /*= false*/, BOOL bStayVisible /* = FALSE */, HXUIOBJ *phResultingScene /*= NULL*/ ) +HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *initData /* = nullptr */, bool forceUsePad /*= false*/, BOOL bStayVisible /* = FALSE */, HXUIOBJ *phResultingScene /*= nullptr*/ ) { ASSERT(m_bDefaultTypefaceRegistered); ASSERT(m_bSkinLoaded); @@ -1690,7 +1690,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in } // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(nullptr); HXUIOBJ hScene; HRESULT hr; @@ -1701,7 +1701,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in // If the init data is null, put the player pad in there - if(initData==NULL) + if(initData==nullptr) { initData = &iPad; } @@ -1843,7 +1843,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in m_bPauseMenuDisplayed[iPad] = true; Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; @@ -1883,7 +1883,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in break; } - if(phResultingScene!=NULL) + if(phResultingScene!=nullptr) { *phResultingScene=hScene; } @@ -1997,7 +1997,7 @@ HRESULT CConsoleMinecraftApp::CloseXuiScenes(int iPad, bool forceUsePad /*= fals } Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft != NULL && pMinecraft->localgameModes[iPad] != NULL ) + if(pMinecraft != nullptr && pMinecraft->localgameModes[iPad] != nullptr ) { TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[iPad]; @@ -2132,7 +2132,7 @@ HRESULT CConsoleMinecraftApp::RemoveBackScene(int iPad) } } - XuiSceneSetBackScene(hBack, NULL); + XuiSceneSetBackScene(hBack, nullptr); XuiDestroyObject( hBack ); } } @@ -2163,7 +2163,7 @@ HRESULT CConsoleMinecraftApp::NavigateToHomeMenu() // unload any texture pack audio // if there is audio in use, clear out the audio, and unmount the pack TexturePack *pTexPack=Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=NULL; + DLCTexturePack *pDLCTexPack=nullptr; if(pTexPack->hasAudio()) { @@ -2179,11 +2179,11 @@ HRESULT CConsoleMinecraftApp::NavigateToHomeMenu() // need to stop the streaming audio - by playing streaming audio from the default texture pack now pMinecraft->soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); - if(pDLCTexPack->m_pStreamedWaveBank!=NULL) + if(pDLCTexPack->m_pStreamedWaveBank!=nullptr) { pDLCTexPack->m_pStreamedWaveBank->Destroy(); } - if(pDLCTexPack->m_pSoundBank!=NULL) + if(pDLCTexPack->m_pSoundBank!=nullptr) { pDLCTexPack->m_pSoundBank->Destroy(); } @@ -2193,7 +2193,7 @@ HRESULT CConsoleMinecraftApp::NavigateToHomeMenu() g_NetworkManager.ForceFriendsSessionRefresh(); - hr = NavigateToScene(XUSER_INDEX_ANY,eUIScene_MainMenu,NULL); + hr = NavigateToScene(XUSER_INDEX_ANY,eUIScene_MainMenu,nullptr); return hr; } @@ -2217,7 +2217,7 @@ void CConsoleMinecraftApp::SetChatTextDisplayed(int iPad, bool bVal) void CConsoleMinecraftApp::ReloadChatScene(int iPad, bool bJoining /*= false*/, bool bForce /*= false*/) { - if(m_hFirstChatScene[iPad] == NULL || m_hCurrentChatScene[iPad] == NULL) return; + if(m_hFirstChatScene[iPad] == nullptr || m_hCurrentChatScene[iPad] == nullptr) return; // Re-create the chat scene so it is the correct size. It starts without any visible lines. BOOL chatSceneVisible = FALSE; @@ -2236,7 +2236,7 @@ void CConsoleMinecraftApp::ReloadChatScene(int iPad, bool bJoining /*= false*/, { if( m_hFirstChatScene[iPad] != m_hCurrentChatScene[iPad] ) XuiSceneNavigateBack(m_hCurrentChatScene[iPad], m_hFirstChatScene[iPad],iPad); m_hCurrentChatScene[iPad] = m_hFirstChatScene[iPad]; - app.NavigateToScene(iPad,eUIComponent_Chat,NULL,true); + app.NavigateToScene(iPad,eUIComponent_Chat,nullptr,true); XuiElementSetShow( m_hCurrentChatScene[iPad], chatSceneVisible); } @@ -2298,7 +2298,7 @@ void CConsoleMinecraftApp::ReloadChatScene(int iPad, bool bJoining /*= false*/, void CConsoleMinecraftApp::ReloadHudScene(int iPad, bool bJoining /*= false*/, bool bForce /*= false*/) { - if(m_hFirstHudScene[iPad] == NULL || m_hCurrentHudScene[iPad] == NULL) return; + if(m_hFirstHudScene[iPad] == nullptr || m_hCurrentHudScene[iPad] == nullptr) return; // Re-create the hud scene so it is the correct size. It starts without any visible lines. BOOL hudSceneVisible = FALSE; @@ -2317,7 +2317,7 @@ void CConsoleMinecraftApp::ReloadHudScene(int iPad, bool bJoining /*= false*/, b { if( m_hFirstHudScene[iPad] != m_hCurrentHudScene[iPad] ) XuiSceneNavigateBack(m_hCurrentHudScene[iPad], m_hFirstHudScene[iPad],iPad); m_hCurrentHudScene[iPad] = m_hFirstHudScene[iPad]; - app.NavigateToScene(iPad,eUIScene_HUD,NULL,true); + app.NavigateToScene(iPad,eUIScene_HUD,nullptr,true); XuiElementSetShow( m_hCurrentHudScene[iPad], hudSceneVisible); } @@ -2333,7 +2333,7 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv XuiElementGetPosition(hScene,pvOriginalPosition); vec=*pvOriginalPosition; - if( pMinecraft->localplayers[iPad] != NULL ) + if( pMinecraft->localplayers[iPad] != nullptr ) { switch( pMinecraft->localplayers[iPad]->m_iScreenSection) { @@ -2382,7 +2382,7 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv vec=*pvOriginalPosition; - if( pMinecraft->localplayers[iPad] != NULL ) + if( pMinecraft->localplayers[iPad] != nullptr ) { switch( pMinecraft->localplayers[iPad]->m_iScreenSection) { @@ -2449,7 +2449,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen // 4J Stu - Return S_FALSE to inidicate that the scene has been closed return S_FALSE; } - else if ( pMinecraft->localplayers[iPad] != NULL ) + else if ( pMinecraft->localplayers[iPad] != nullptr ) { // we need to reposition the scenes since the players will have moved around @@ -2510,7 +2510,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen // 4J Stu - Return S_FALSE to inidicate that the scene has been closed return S_FALSE; } - else if ( pMinecraft->localplayers[iPad] != NULL ) + else if ( pMinecraft->localplayers[iPad] != nullptr ) { // we need to reposition the scenes since the players will have moved around @@ -2560,7 +2560,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen void CConsoleMinecraftApp::StoreLaunchData() { - LD_DEMO* pDemoData = NULL; + LD_DEMO* pDemoData = nullptr; DWORD dwStatus = XGetLaunchDataSize( &m_dwLaunchDataSize ); @@ -2578,7 +2578,7 @@ void CConsoleMinecraftApp::StoreLaunchData() void CConsoleMinecraftApp::ExitGame() { - if(m_pLaunchData!=NULL) + if(m_pLaunchData!=nullptr) { LD_DEMO* pDemoData = (LD_DEMO*)( m_pLaunchData ); XSetLaunchData( pDemoData, m_dwLaunchDataSize ); @@ -2605,7 +2605,7 @@ void CConsoleMinecraftApp::FatalLoadError(void) memset(&MessageBoxOverlap, 0, sizeof(MessageBoxOverlap)); - //HANDLE messageBoxThread = CreateThread(NULL, 0, &CMinecraftApp::ShowFatalLoadMessageBoxThreadProc, &MessageBoxOverlap, 0, NULL); + //HANDLE messageBoxThread = CreateThread(nullptr, 0, &CMinecraftApp::ShowFatalLoadMessageBoxThreadProc, &MessageBoxOverlap, 0, nullptr); // //WaitForSingleObjectEx(messageBoxThread, // handle to object // 20000, // time-out interval @@ -2775,7 +2775,7 @@ int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile) if(iTMSFileIndex!=-1) { // can we find the tms file in our xzp? - if(TMSFileA[iTMSFileIndex].pbData==NULL) // if we haven't already loaded it + if(TMSFileA[iTMSFileIndex].pbData==nullptr) // if we haven't already loaded it { swprintf(szResourceLocator, LOCATOR_SIZE, L"%ls#TMSFiles/%ls",m_wchTMSXZP, wchTMSFile); @@ -2793,10 +2793,10 @@ void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) { if((eType==eTMSFileType_All) ||(eType==TMSFileA[i].eTMSType)) { - if(TMSFileA[i].pbData!=NULL) + if(TMSFileA[i].pbData!=nullptr) { XuiFree(TMSFileA[i].pbData); - TMSFileA[i].pbData=NULL; + TMSFileA[i].pbData=nullptr; TMSFileA[i].uiSize=0; } } @@ -2807,148 +2807,148 @@ void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { // skin packs - { L"SP1", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SP2", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SP3", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SP4", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SP5", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SP6", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SPF", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SPB", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SPC", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { L"SPZ", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - { 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}, + { L"SP1", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SP2", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SP3", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SP4", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SP5", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SP6", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPF", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPB", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPC", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPZ", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPM", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPI", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"SPG", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 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}, + { L"ThSt", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"ThIr", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"ThGo", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"ThDi", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, + { L"ThAw", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0}, //gamerpics - { L"GPAn", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPCo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPEn", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPFo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPTo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPBA", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPFa", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { L"GPME", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - { 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"GPAn", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPCo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPEn", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPFo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPTo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPBA", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPFa", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPME", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPMF", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPMM", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPSE", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 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"GPOr", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPMi", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPMB", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPBr", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, nullptr, 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}, + { L"GPM1", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPM2", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0}, + { L"GPM3", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0}, //avatar items - { L"AH_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0008", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AH_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { 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"AH_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0008", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AH_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 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 }, - { L"AT_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0008", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0014", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0015", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0016", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0017", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0018", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0019", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0020", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0021", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0022", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AT_0023", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { 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"AT_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0008", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0014", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0015", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0016", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0017", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0018", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0019", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0020", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0021", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0022", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0023", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0024", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0025", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AT_0026", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 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 }, - { L"AP_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0014", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0015", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { 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_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0004", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0005", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0006", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0007", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0009", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0010", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0014", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0015", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0016", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0017", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0018", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 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 }, - { L"AP_0022", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0023", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0024", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0025", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0026", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0027", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0028", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0029", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"AP_0030", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { 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"AP_0019", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0020", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0021", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0022", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0023", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0024", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0025", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0026", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0027", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0028", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0029", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0030", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0031", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0032", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"AP_0033", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, - { L"AA_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0 }, + { L"AA_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0 , 0 }, // Mash-up Packs - { L"MPMA", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"MPMA", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 1024 }, - { L"MPSR", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"MPSR", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 1025 }, - { L"MPHA", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"MPHA", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 1026 }, + { L"MPMA", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"MPMA", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 1024 }, + { L"MPSR", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"MPSR", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 1025 }, + { L"MPHA", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"MPHA", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 1026 }, // Texture Packs - { L"TP01", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP01", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2049 }, - { L"TP02", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP02", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2053 }, - { L"TP04", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP04", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2051 }, - { L"TP05", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP05", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2054 }, - { L"TP06", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP06", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2050 }, - { L"TP07", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - { L"TP07", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 2055 }, + { L"TP01", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP01", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2049 }, + { L"TP02", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP02", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2053 }, + { L"TP04", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP04", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2051 }, + { L"TP05", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP05", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2054 }, + { L"TP06", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP06", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2050 }, + { L"TP07", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, nullptr, 0, 0 }, + { L"TP07", eFileExtensionType_DAT, eTMSFileType_TexturePack, nullptr, 0, 2055 }, }; diff --git a/Minecraft.Client/Xbox/Xbox_App.h b/Minecraft.Client/Xbox/Xbox_App.h index f64e71423..86dbc2874 100644 --- a/Minecraft.Client/Xbox/Xbox_App.h +++ b/Minecraft.Client/Xbox/Xbox_App.h @@ -121,7 +121,7 @@ private: public: - void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false); + void ReadBannedList(int iPad, eTMSAction action=static_cast(0), bool bCallback=false); // void ReadXuidsFileFromTMS(int iPad,eTMSAction NextAction,bool bCallback); // void ReadDLCFileFromTMS(int iPad,eTMSAction NextAction, bool bCallback); @@ -133,12 +133,12 @@ public: WCHAR *GetSceneName(EUIScene eScene, bool bAppendToName,bool bSplitscreenScene); - virtual HRESULT NavigateToScene(int iPad,EUIScene eScene, void *initData = NULL, bool forceUsePad = false, BOOL bStayVisible=FALSE, HXUIOBJ *phResultingScene=NULL); + virtual HRESULT NavigateToScene(int iPad,EUIScene eScene, void *initData = nullptr, bool forceUsePad = false, BOOL bStayVisible=FALSE, HXUIOBJ *phResultingScene=nullptr); virtual HRESULT NavigateBack(int iPad, bool forceUsePad = false,EUIScene eScene = eUIScene_COUNT); virtual HRESULT TutorialSceneNavigateBack(int iPad, bool forceUsePad = false); virtual HRESULT CloseXuiScenes(int iPad, bool forceUsePad = false); virtual HRESULT CloseAllPlayersXuiScenes(); - virtual HRESULT CloseXuiScenesAndNavigateToScene(int iPad,EUIScene eScene, void *initData=NULL, bool forceUsePad = false); + virtual HRESULT CloseXuiScenesAndNavigateToScene(int iPad,EUIScene eScene, void *initData=nullptr, bool forceUsePad = false); virtual HRESULT RemoveBackScene(int iPad); virtual HRESULT NavigateToHomeMenu(); D3DXVECTOR3 GetElementScreenPosition(HXUIOBJ hObj); diff --git a/Minecraft.Client/Xbox/Xbox_Minecraft.cpp b/Minecraft.Client/Xbox/Xbox_Minecraft.cpp index 19353283f..b066fa1c1 100644 --- a/Minecraft.Client/Xbox/Xbox_Minecraft.cpp +++ b/Minecraft.Client/Xbox/Xbox_Minecraft.cpp @@ -288,7 +288,7 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, return pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, - NULL, + nullptr, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, pd3dPP, ppDevice ); @@ -402,7 +402,7 @@ int __cdecl main() } // Create an XAudio2 mastering voice (utilized by XHV2 when voice data is mixed to main speakers) - hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, NULL); + hr = g_pXAudio2->CreateMasteringVoice(&g_pXAudio2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, nullptr); if ( FAILED( hr ) ) { app.DebugPrintf( "Creating XAudio2 mastering voice failed (err = 0x%08x)!\n", hr ); @@ -674,7 +674,7 @@ int __cdecl main() else { MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); + pMinecraft->soundEngine->tick(nullptr, 0.0f); MemSect(0); pMinecraft->textures->tick(true,false); IntCache::Reset(); diff --git a/Minecraft.Client/Xbox/Xbox_UIController.cpp b/Minecraft.Client/Xbox/Xbox_UIController.cpp index 51d91ca49..669b037ad 100644 --- a/Minecraft.Client/Xbox/Xbox_UIController.cpp +++ b/Minecraft.Client/Xbox/Xbox_UIController.cpp @@ -170,7 +170,7 @@ void ConsoleUIController::HandleDLCInstalled(int iPad) CustomMessage_DLCInstalled( &xuiMsg ); // The DLC message should only happen in the main menus, so it should go to the default xui scenes - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { @@ -188,7 +188,7 @@ void ConsoleUIController::HandleTMSDLCFileRetrieved(int iPad) XUIMessage xuiMsg; CustomMessage_TMS_DLCFileRetrieved( &xuiMsg ); - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { @@ -204,7 +204,7 @@ void ConsoleUIController::HandleTMSBanFileRetrieved(int iPad) { XUIMessage xuiMsg; CustomMessage_TMS_BanFileRetrieved( &xuiMsg ); - bool bNotInGame=(Minecraft::GetInstance()->level==NULL); + bool bNotInGame=(Minecraft::GetInstance()->level==nullptr); if(bNotInGame) { @@ -319,7 +319,7 @@ C4JStorage::EMessageResult ConsoleUIController::RequestMessageBox(UINT uiTitle, return StorageManager.RequestMessageBox(uiTitle, uiText, uiOptionA, uiOptionC, dwPad, Func, lpParam, pStringTable, pwchFormatString, dwFocusButton); } -C4JStorage::EMessageResult ConsoleUIController::RequestUGCMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = NULL*/, LPVOID lpParam/* = NULL*/) +C4JStorage::EMessageResult ConsoleUIController::RequestUGCMessageBox(UINT title/* = -1 */, UINT message/* = -1 */, int iPad/* = -1*/, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)/* = nullptr*/, LPVOID lpParam/* = nullptr*/) { // Default title / messages if (title == -1) @@ -337,5 +337,5 @@ C4JStorage::EMessageResult ConsoleUIController::RequestUGCMessageBox(UINT title/ UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - return ui.RequestMessageBox(title, message, uiIDA, 1, iPad, Func, lpParam, app.GetStringTable(), NULL, 0, false); + return ui.RequestMessageBox(title, message, uiIDA, 1, iPad, Func, lpParam, app.GetStringTable(), nullptr, 0, false); } \ No newline at end of file diff --git a/Minecraft.Client/Xbox/Xbox_UIController.h b/Minecraft.Client/Xbox/Xbox_UIController.h index 2b273ee52..cd4605965 100644 --- a/Minecraft.Client/Xbox/Xbox_UIController.h +++ b/Minecraft.Client/Xbox/Xbox_UIController.h @@ -11,7 +11,7 @@ public: virtual void StartReloadSkinThread(); virtual bool IsReloadingSkin(); virtual void CleanUpSkinReload(); - virtual bool NavigateToScene(int iPad, EUIScene scene, void *initData = NULL, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD); + virtual bool NavigateToScene(int iPad, EUIScene scene, void *initData = nullptr, EUILayer layer = eUILayer_Scene, EUIGroup group = eUIGroup_PAD); virtual bool NavigateBack(int iPad, bool forceUsePad = false, EUIScene eScene = eUIScene_COUNT, EUILayer eLayer = eUILayer_COUNT); virtual void NavigateToHomeMenu(); virtual void CloseUIScenes(int iPad, bool forceIPad = false); @@ -71,9 +71,9 @@ public: virtual void SetWinUserIndex(unsigned int iPad); virtual C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, - int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=NULL,LPVOID lpParam=NULL, CXuiStringTable *pStringTable=NULL, WCHAR *pwchFormatString=NULL,DWORD dwFocusButton=0, bool bIsError = true); + int( *Func)(LPVOID,int,const C4JStorage::EMessageResult)=nullptr,LPVOID lpParam=nullptr, CXuiStringTable *pStringTable=nullptr, WCHAR *pwchFormatString=nullptr,DWORD dwFocusButton=0, bool bIsError = true); - C4JStorage::EMessageResult RequestUGCMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = NULL, LPVOID lpParam = NULL); + C4JStorage::EMessageResult RequestUGCMessageBox(UINT title = -1, UINT message = -1, int iPad = -1, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult) = nullptr, LPVOID lpParam = nullptr); }; extern ConsoleUIController ui; \ No newline at end of file diff --git a/Minecraft.Client/ZombieRenderer.cpp b/Minecraft.Client/ZombieRenderer.cpp index 7fd2d2015..10d13b269 100644 --- a/Minecraft.Client/ZombieRenderer.cpp +++ b/Minecraft.Client/ZombieRenderer.cpp @@ -14,11 +14,11 @@ ZombieRenderer::ZombieRenderer() : HumanoidMobRenderer(new ZombieModel(), .5f, 1 defaultModel = humanoidModel; villagerModel = new VillagerZombieModel(); - defaultArmorParts1 = NULL; - defaultArmorParts2 = NULL; + defaultArmorParts1 = nullptr; + defaultArmorParts2 = nullptr; - villagerArmorParts1 = NULL; - villagerArmorParts2 = NULL; + villagerArmorParts1 = nullptr; + villagerArmorParts2 = nullptr; createArmorParts(); } @@ -98,7 +98,7 @@ void ZombieRenderer::swapArmor(shared_ptr mob) armorParts2 = defaultArmorParts2; } - humanoidModel = (HumanoidModel *) model; + humanoidModel = static_cast(model); } void ZombieRenderer::setupRotations(shared_ptr _mob, float bob, float bodyRot, float a) @@ -106,7 +106,7 @@ void ZombieRenderer::setupRotations(shared_ptr _mob, float bob, fl shared_ptr mob = dynamic_pointer_cast(_mob); if (mob->isConverting()) { - bodyRot += (float) (cos(mob->tickCount * 3.25) * PI * .25f); + bodyRot += static_cast(cos(mob->tickCount * 3.25) * PI * .25f); } HumanoidMobRenderer::setupRotations(mob, bob, bodyRot, a); } \ No newline at end of file diff --git a/Minecraft.Client/glWrapper.cpp b/Minecraft.Client/glWrapper.cpp index a356e674c..d13e1a691 100644 --- a/Minecraft.Client/glWrapper.cpp +++ b/Minecraft.Client/glWrapper.cpp @@ -48,11 +48,12 @@ void glLoadIdentity() RenderManager.MatrixSetIdentity(); } -// AAR - Use calculated aspect ratio to support dynamic resizing -extern float g_iAspectRatio; +// AAR - Use the aspect ratio passed by the caller. For single-player this +// equals g_iAspectRatio (screen width / height), but for split-screen +// getFovAndAspect adjusts it to match the viewport dimensions. void gluPerspective(float fovy, float aspect, float zNear, float zFar) { - RenderManager.MatrixPerspective(fovy, g_iAspectRatio, zNear, zFar); + RenderManager.MatrixPerspective(fovy, aspect, zNear, zFar); } void glOrtho(float left,float right,float bottom,float top,float zNear,float zFar) @@ -62,7 +63,7 @@ void glOrtho(float left,float right,float bottom,float top,float zNear,float zFa void glScaled(double x,double y,double z) { - RenderManager.MatrixScale((float)x,(float)y,(float)z); + RenderManager.MatrixScale(static_cast(x),static_cast(y),static_cast(z)); } void glGetFloat(int type, FloatBuffer *buff) diff --git a/Minecraft.Client/prebuild.ps1 b/Minecraft.Client/prebuild.ps1 index fa2c487c5..0acbf023b 100644 --- a/Minecraft.Client/prebuild.ps1 +++ b/Minecraft.Client/prebuild.ps1 @@ -1,5 +1,18 @@ $sha = (git rev-parse --short=7 HEAD) -$ref = (git symbolic-ref --short HEAD) + +if ($env:GITHUB_REPOSITORY) { + $ref = "$env:GITHUB_REPOSITORY/$(git symbolic-ref --short HEAD)" +} else { + $remoteUrl = (git remote get-url origin) + # handle github urls only, can't predict other origins behavior + if ($remoteUrl -match '(?:github\.com[:/])([^/:]+/[^/]+?)(?:\.git)?$') { + $ref = "$($matches[1])/$(git symbolic-ref --short HEAD)" + }else{ + # fallback to just symbolic ref in case remote isnt what we expect + $ref = "UNKNOWN/$(git symbolic-ref --short HEAD)" + } +} + $build = 560 # Note: Build/network has to stay static for now, as without it builds wont be able to play together. We can change it later when we have a better versioning scheme in place. $suffix = "" @@ -18,7 +31,8 @@ if (git status --porcelain) { #pragma once #define VER_PRODUCTBUILD $build -#define VER_PRODUCTVERSION_STR_W L"$sha$suffix ($ref)" +#define VER_PRODUCTVERSION_STR_W L"$sha$suffix" #define VER_FILEVERSION_STR_W VER_PRODUCTVERSION_STR_W +#define VER_BRANCHVERSION_STR_W L"$ref" #define VER_NETWORK VER_PRODUCTBUILD "@ | Set-Content "Common/BuildVer.h" diff --git a/Minecraft.Client/redist64/binkawin64.asi b/Minecraft.Client/redist64/binkawin64.asi deleted file mode 100644 index f0574d9d8..000000000 Binary files a/Minecraft.Client/redist64/binkawin64.asi and /dev/null differ diff --git a/Minecraft.Client/redist64/mss64dolby.flt b/Minecraft.Client/redist64/mss64dolby.flt deleted file mode 100644 index 1842df34b..000000000 Binary files a/Minecraft.Client/redist64/mss64dolby.flt and /dev/null differ diff --git a/Minecraft.Client/redist64/mss64ds3d.flt b/Minecraft.Client/redist64/mss64ds3d.flt deleted file mode 100644 index 77a0f8aaf..000000000 Binary files a/Minecraft.Client/redist64/mss64ds3d.flt and /dev/null differ diff --git a/Minecraft.Client/redist64/mss64dsp.flt b/Minecraft.Client/redist64/mss64dsp.flt deleted file mode 100644 index 5b47b314e..000000000 Binary files a/Minecraft.Client/redist64/mss64dsp.flt and /dev/null differ diff --git a/Minecraft.Client/redist64/mss64eax.flt b/Minecraft.Client/redist64/mss64eax.flt deleted file mode 100644 index 18d0033db..000000000 Binary files a/Minecraft.Client/redist64/mss64eax.flt and /dev/null differ diff --git a/Minecraft.Client/redist64/mss64srs.flt b/Minecraft.Client/redist64/mss64srs.flt deleted file mode 100644 index 9412318ae..000000000 Binary files a/Minecraft.Client/redist64/mss64srs.flt and /dev/null differ diff --git a/Minecraft.Client/stubs.h b/Minecraft.Client/stubs.h index f4ae056f2..10ba2d053 100644 --- a/Minecraft.Client/stubs.h +++ b/Minecraft.Client/stubs.h @@ -170,15 +170,15 @@ class ZipFile { public: ZipFile(File *file) {} - InputStream *getInputStream(ZipEntry *entry) { return NULL; } - ZipEntry *getEntry(const wstring& name) {return NULL;} + InputStream *getInputStream(ZipEntry *entry) { return nullptr; } + ZipEntry *getEntry(const wstring& name) {return nullptr;} void close() {} }; class ImageIO { public: - static BufferedImage *read(InputStream *in) { return NULL; } + static BufferedImage *read(InputStream *in) { return nullptr; } }; class Keyboard diff --git a/Minecraft.Server/Access/Access.cpp b/Minecraft.Server/Access/Access.cpp new file mode 100644 index 000000000..5767a9555 --- /dev/null +++ b/Minecraft.Server/Access/Access.cpp @@ -0,0 +1,460 @@ +#include "stdafx.h" + +#include "Access.h" + +#include "..\Common\StringUtils.h" +#include "..\ServerLogger.h" + +#include +#include + +namespace ServerRuntime +{ + namespace Access + { + namespace + { + /** + * **Access State** + * + * These features are used extensively from various parts of the code, so safe read/write handling is implemented + * Stores the published BAN manager snapshot plus a writer gate for clone-and-publish updates + * 公開中のBanManagerスナップショットと更新直列化用ロックを保持する + */ + struct AccessState + { + std::mutex stateLock; + std::mutex writeLock; + std::shared_ptr banManager; + std::shared_ptr whitelistManager; + bool whitelistEnabled = false; + }; + + AccessState g_accessState; + + /** + * Copies the currently published manager pointer so readers can work without holding the publish mutex + * 公開中のBanManager共有ポインタを複製取得する + */ + static std::shared_ptr GetBanManagerSnapshot() + { + std::lock_guard stateLock(g_accessState.stateLock); + return g_accessState.banManager; + } + + /** + * Replaces the shared manager pointer with a fully prepared snapshot in one short critical section + * 準備完了したBanManagerスナップショットを短いロックで公開する + */ + static void PublishBanManagerSnapshot(const std::shared_ptr &banManager) + { + std::lock_guard stateLock(g_accessState.stateLock); + g_accessState.banManager = banManager; + } + + static std::shared_ptr GetWhitelistManagerSnapshot() + { + std::lock_guard stateLock(g_accessState.stateLock); + return g_accessState.whitelistManager; + } + + static void PublishWhitelistManagerSnapshot(const std::shared_ptr &whitelistManager) + { + std::lock_guard stateLock(g_accessState.stateLock); + g_accessState.whitelistManager = whitelistManager; + } + } + + std::string FormatXuid(PlayerUID xuid) + { + if (xuid == INVALID_XUID) + { + return ""; + } + + char buffer[32] = {}; + sprintf_s(buffer, sizeof(buffer), "0x%016llx", (unsigned long long)xuid); + return buffer; + } + + bool TryParseXuid(const std::string &text, PlayerUID *outXuid) + { + if (outXuid == nullptr) + { + return false; + } + + unsigned long long parsed = 0; + if (!StringUtils::TryParseUnsignedLongLong(text, &parsed) || parsed == 0ULL) + { + return false; + } + + *outXuid = (PlayerUID)parsed; + return true; + } + + bool Initialize(const std::string &baseDirectory, bool whitelistEnabled) + { + std::lock_guard writeLock(g_accessState.writeLock); + + // Build the replacement manager privately so readers keep using the last published snapshot during disk I/O. + std::shared_ptr banManager = std::make_shared(baseDirectory); + std::shared_ptr whitelistManager = std::make_shared(baseDirectory); + if (!banManager->EnsureBanFilesExist()) + { + LogError("access", "failed to ensure dedicated server ban files exist"); + return false; + } + if (!whitelistManager->EnsureWhitelistFileExists()) + { + LogError("access", "failed to ensure dedicated server whitelist file exists"); + return false; + } + + if (!banManager->Reload()) + { + LogError("access", "failed to load dedicated server ban files"); + return false; + } + if (!whitelistManager->Reload()) + { + LogError("access", "failed to load dedicated server whitelist file"); + return false; + } + + std::vector playerEntries; + std::vector ipEntries; + std::vector whitelistEntries; + banManager->SnapshotBannedPlayers(&playerEntries); + banManager->SnapshotBannedIps(&ipEntries); + whitelistManager->SnapshotWhitelistedPlayers(&whitelistEntries); + PublishBanManagerSnapshot(banManager); + PublishWhitelistManagerSnapshot(whitelistManager); + { + std::lock_guard stateLock(g_accessState.stateLock); + g_accessState.whitelistEnabled = whitelistEnabled; + } + + LogInfof( + "access", + "loaded %u player bans, %u ip bans, and %u whitelist entries (whitelist=%s)", + (unsigned)playerEntries.size(), + (unsigned)ipEntries.size(), + (unsigned)whitelistEntries.size(), + whitelistEnabled ? "enabled" : "disabled"); + return true; + } + + void Shutdown() + { + std::lock_guard writeLock(g_accessState.writeLock); + PublishBanManagerSnapshot(std::shared_ptr{}); + PublishWhitelistManagerSnapshot(std::shared_ptr{}); + std::lock_guard stateLock(g_accessState.stateLock); + g_accessState.whitelistEnabled = false; + } + + bool Reload() + { + std::lock_guard writeLock(g_accessState.writeLock); + std::shared_ptr current = GetBanManagerSnapshot(); + std::shared_ptr currentWhitelist = GetWhitelistManagerSnapshot(); + if (current == nullptr || currentWhitelist == nullptr) + { + return false; + } + + std::shared_ptr banManager = std::make_shared(*current); + std::shared_ptr whitelistManager = std::make_shared(*currentWhitelist); + if (!banManager->EnsureBanFilesExist()) + { + return false; + } + if (!whitelistManager->EnsureWhitelistFileExists()) + { + return false; + } + if (!banManager->Reload()) + { + return false; + } + if (!whitelistManager->Reload()) + { + return false; + } + + PublishBanManagerSnapshot(banManager); + PublishWhitelistManagerSnapshot(whitelistManager); + return true; + } + + bool ReloadWhitelist() + { + std::lock_guard writeLock(g_accessState.writeLock); + const auto current = GetWhitelistManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + auto whitelistManager = std::make_shared(*current); + if (!whitelistManager->EnsureWhitelistFileExists()) + { + return false; + } + if (!whitelistManager->Reload()) + { + return false; + } + + PublishWhitelistManagerSnapshot(whitelistManager); + return true; + } + + bool IsInitialized() + { + return GetBanManagerSnapshot() != nullptr && GetWhitelistManagerSnapshot() != nullptr; + } + + bool IsWhitelistEnabled() + { + std::lock_guard stateLock(g_accessState.stateLock); + return g_accessState.whitelistEnabled; + } + + void SetWhitelistEnabled(bool enabled) + { + std::lock_guard writeLock(g_accessState.writeLock); + std::lock_guard stateLock(g_accessState.stateLock); + g_accessState.whitelistEnabled = enabled; + } + + bool IsPlayerBanned(PlayerUID xuid) + { + const std::string formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::shared_ptr banManager = GetBanManagerSnapshot(); + return (banManager != nullptr) ? banManager->IsPlayerBannedByXuid(formatted) : false; + } + + bool IsIpBanned(const std::string &ip) + { + std::shared_ptr banManager = GetBanManagerSnapshot(); + return (banManager != nullptr) ? banManager->IsIpBanned(ip) : false; + } + + bool IsPlayerWhitelisted(PlayerUID xuid) + { + const std::string formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::shared_ptr whitelistManager = GetWhitelistManagerSnapshot(); + return (whitelistManager != nullptr) ? whitelistManager->IsPlayerWhitelistedByXuid(formatted) : false; + } + + bool AddPlayerBan(PlayerUID xuid, const std::string &name, const BanMetadata &metadata) + { + const std::string formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::lock_guard writeLock(g_accessState.writeLock); + std::shared_ptr current = GetBanManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + std::shared_ptr banManager = std::make_shared(*current); + BannedPlayerEntry entry; + entry.xuid = formatted; + entry.name = name; + entry.metadata = metadata; + if (!banManager->AddPlayerBan(entry)) + { + return false; + } + + PublishBanManagerSnapshot(banManager); + return true; + } + + bool AddIpBan(const std::string &ip, const BanMetadata &metadata) + { + std::lock_guard writeLock(g_accessState.writeLock); + std::shared_ptr current = GetBanManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + std::shared_ptr banManager = std::make_shared(*current); + BannedIpEntry entry; + entry.ip = ip; + entry.metadata = metadata; + if (!banManager->AddIpBan(entry)) + { + return false; + } + + PublishBanManagerSnapshot(banManager); + return true; + } + + bool RemovePlayerBan(PlayerUID xuid) + { + const std::string formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::lock_guard writeLock(g_accessState.writeLock); + std::shared_ptr current = GetBanManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + std::shared_ptr banManager = std::make_shared(*current); + if (!banManager->RemovePlayerBanByXuid(formatted)) + { + return false; + } + + PublishBanManagerSnapshot(banManager); + return true; + } + + bool RemoveIpBan(const std::string &ip) + { + std::lock_guard writeLock(g_accessState.writeLock); + std::shared_ptr current = GetBanManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + std::shared_ptr banManager = std::make_shared(*current); + if (!banManager->RemoveIpBan(ip)) + { + return false; + } + + PublishBanManagerSnapshot(banManager); + return true; + } + + bool AddWhitelistedPlayer(PlayerUID xuid, const std::string &name, const WhitelistMetadata &metadata) + { + const auto formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::lock_guard writeLock(g_accessState.writeLock); + const auto current = GetWhitelistManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + auto whitelistManager = std::make_shared(*current); + const WhitelistedPlayerEntry entry = { formatted, name, metadata }; + if (!whitelistManager->AddPlayer(entry)) + { + return false; + } + + PublishWhitelistManagerSnapshot(whitelistManager); + return true; + } + + bool RemoveWhitelistedPlayer(PlayerUID xuid) + { + const auto formatted = FormatXuid(xuid); + if (formatted.empty()) + { + return false; + } + + std::lock_guard writeLock(g_accessState.writeLock); + const auto current = GetWhitelistManagerSnapshot(); + if (current == nullptr) + { + return false; + } + + auto whitelistManager = std::make_shared(*current); + if (!whitelistManager->RemovePlayerByXuid(formatted)) + { + return false; + } + + PublishWhitelistManagerSnapshot(whitelistManager); + return true; + } + + bool SnapshotBannedPlayers(std::vector *outEntries) + { + if (outEntries == nullptr) + { + return false; + } + + std::shared_ptr banManager = GetBanManagerSnapshot(); + if (banManager == nullptr) + { + outEntries->clear(); + return false; + } + + return banManager->SnapshotBannedPlayers(outEntries); + } + + bool SnapshotBannedIps(std::vector *outEntries) + { + if (outEntries == nullptr) + { + return false; + } + + std::shared_ptr banManager = GetBanManagerSnapshot(); + if (banManager == nullptr) + { + outEntries->clear(); + return false; + } + + return banManager->SnapshotBannedIps(outEntries); + } + + bool SnapshotWhitelistedPlayers(std::vector *outEntries) + { + if (outEntries == nullptr) + { + return false; + } + + const auto whitelistManager = GetWhitelistManagerSnapshot(); + if (whitelistManager == nullptr) + { + outEntries->clear(); + return false; + } + + return whitelistManager->SnapshotWhitelistedPlayers(outEntries); + } + } +} diff --git a/Minecraft.Server/Access/Access.h b/Minecraft.Server/Access/Access.h new file mode 100644 index 000000000..80e61e551 --- /dev/null +++ b/Minecraft.Server/Access/Access.h @@ -0,0 +1,47 @@ +#pragma once + +#include "BanManager.h" +#include "WhitelistManager.h" + +namespace ServerRuntime +{ + /** + * A frontend that will be general-purpose, assuming the implementation of whitelists and ops in the future. + */ + namespace Access + { + bool Initialize(const std::string &baseDirectory = ".", bool whitelistEnabled = false); + void Shutdown(); + bool Reload(); + bool ReloadWhitelist(); + bool IsInitialized(); + bool IsWhitelistEnabled(); + void SetWhitelistEnabled(bool enabled); + + bool IsPlayerBanned(PlayerUID xuid); + bool IsIpBanned(const std::string &ip); + bool IsPlayerWhitelisted(PlayerUID xuid); + + bool AddPlayerBan(PlayerUID xuid, const std::string &name, const BanMetadata &metadata); + bool AddIpBan(const std::string &ip, const BanMetadata &metadata); + bool RemovePlayerBan(PlayerUID xuid); + bool RemoveIpBan(const std::string &ip); + bool AddWhitelistedPlayer(PlayerUID xuid, const std::string &name, const WhitelistMetadata &metadata); + bool RemoveWhitelistedPlayer(PlayerUID xuid); + + /** + * Copies the current cached player bans for inspection or command output + * 現在のプレイヤーBAN一覧を複製取得 + */ + bool SnapshotBannedPlayers(std::vector *outEntries); + /** + * Copies the current cached IP bans for inspection or command output + * 現在のIP BAN一覧を複製取得 + */ + bool SnapshotBannedIps(std::vector *outEntries); + bool SnapshotWhitelistedPlayers(std::vector *outEntries); + + std::string FormatXuid(PlayerUID xuid); + bool TryParseXuid(const std::string &text, PlayerUID *outXuid); + } +} diff --git a/Minecraft.Server/Access/BanManager.cpp b/Minecraft.Server/Access/BanManager.cpp new file mode 100644 index 000000000..59f5bccc0 --- /dev/null +++ b/Minecraft.Server/Access/BanManager.cpp @@ -0,0 +1,631 @@ +#include "stdafx.h" + +#include "BanManager.h" + +#include "..\Common\AccessStorageUtils.h" +#include "..\Common\FileUtils.h" +#include "..\Common\NetworkUtils.h" +#include "..\Common\StringUtils.h" +#include "..\ServerLogger.h" +#include "..\vendor\nlohmann\json.hpp" + +#include +#include + +namespace ServerRuntime +{ + namespace Access + { + using OrderedJson = nlohmann::ordered_json; + + namespace + { + static const char *kBannedPlayersFileName = "banned-players.json"; + static const char *kBannedIpsFileName = "banned-ips.json"; + + static bool TryParseUtcTimestamp(const std::string &text, unsigned long long *outFileTime) + { + if (outFileTime == nullptr) + { + return false; + } + + std::string trimmed = StringUtils::TrimAscii(text); + if (trimmed.empty()) + { + return false; + } + + unsigned year = 0; + unsigned month = 0; + unsigned day = 0; + unsigned hour = 0; + unsigned minute = 0; + unsigned second = 0; + if (sscanf_s(trimmed.c_str(), "%4u-%2u-%2uT%2u:%2u:%2uZ", &year, &month, &day, &hour, &minute, &second) != 6) + { + return false; + } + + SYSTEMTIME utc = {}; + utc.wYear = (WORD)year; + utc.wMonth = (WORD)month; + utc.wDay = (WORD)day; + utc.wHour = (WORD)hour; + utc.wMinute = (WORD)minute; + utc.wSecond = (WORD)second; + + FILETIME fileTime = {}; + if (!SystemTimeToFileTime(&utc, &fileTime)) + { + return false; + } + + ULARGE_INTEGER value = {}; + value.LowPart = fileTime.dwLowDateTime; + value.HighPart = fileTime.dwHighDateTime; + *outFileTime = value.QuadPart; + return true; + } + + static bool IsMetadataExpired(const BanMetadata &metadata, unsigned long long nowFileTime) + { + if (metadata.expires.empty()) + { + return false; + } + + unsigned long long expiresFileTime = 0; + if (!TryParseUtcTimestamp(metadata.expires, &expiresFileTime)) + { + // Keep malformed metadata active instead of silently unbanning a player or address. + return false; + } + + return expiresFileTime <= nowFileTime; + } + } + BanManager::BanManager(const std::string &baseDirectory) + : m_baseDirectory(baseDirectory.empty() ? "." : baseDirectory) + { + } + + bool BanManager::EnsureBanFilesExist() const + { + const std::string playersPath = GetBannedPlayersFilePath(); + const std::string ipsPath = GetBannedIpsFilePath(); + + const bool playersOk = AccessStorageUtils::EnsureJsonListFileExists(playersPath); + const bool ipsOk = AccessStorageUtils::EnsureJsonListFileExists(ipsPath); + if (!playersOk) + { + LogErrorf("access", "failed to create %s", playersPath.c_str()); + } + if (!ipsOk) + { + LogErrorf("access", "failed to create %s", ipsPath.c_str()); + } + return playersOk && ipsOk; + } + + bool BanManager::Reload() + { + std::vector players; + std::vector ips; + + if (!LoadPlayers(&players)) + { + return false; + } + if (!LoadIps(&ips)) + { + return false; + } + + m_bannedPlayers.swap(players); + m_bannedIps.swap(ips); + return true; + } + + bool BanManager::Save() const + { + std::vector players; + std::vector ips; + return SnapshotBannedPlayers(&players) && + SnapshotBannedIps(&ips) && + SavePlayers(players) && + SaveIps(ips); + } + bool BanManager::LoadPlayers(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + outEntries->clear(); + + std::string text; + const std::string path = GetBannedPlayersFilePath(); + if (!FileUtils::ReadTextFile(path, &text)) + { + LogErrorf("access", "failed to read %s", path.c_str()); + return false; + } + if (text.empty()) + { + text = "[]"; + } + + OrderedJson root; + try + { + // Strip an optional UTF-8 BOM because some editors prepend it when rewriting JSON files. + root = OrderedJson::parse(StringUtils::StripUtf8Bom(text)); + } + catch (const nlohmann::json::exception &e) + { + LogErrorf("access", "failed to parse %s: %s", path.c_str(), e.what()); + return false; + } + + if (!root.is_array()) + { + LogErrorf("access", "failed to parse %s: root json value is not an array", path.c_str()); + return false; + } + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + for (const auto &object : root) + { + if (!object.is_object()) + { + LogWarnf("access", "skipping banned player entry that is not an object in %s", path.c_str()); + continue; + } + + std::string rawXuid; + if (!AccessStorageUtils::TryGetStringField(object, "xuid", &rawXuid)) + { + LogWarnf("access", "skipping banned player entry without xuid in %s", path.c_str()); + continue; + } + + BannedPlayerEntry entry; + entry.xuid = AccessStorageUtils::NormalizeXuid(rawXuid); + if (entry.xuid.empty()) + { + LogWarnf("access", "skipping banned player entry with empty xuid in %s", path.c_str()); + continue; + } + + AccessStorageUtils::TryGetStringField(object, "name", &entry.name); + AccessStorageUtils::TryGetStringField(object, "created", &entry.metadata.created); + AccessStorageUtils::TryGetStringField(object, "source", &entry.metadata.source); + AccessStorageUtils::TryGetStringField(object, "expires", &entry.metadata.expires); + AccessStorageUtils::TryGetStringField(object, "reason", &entry.metadata.reason); + NormalizeMetadata(&entry.metadata); + + // Ignore entries that already expired before reload so the in-memory cache starts from the active set. + if (IsMetadataExpired(entry.metadata, nowFileTime)) + { + continue; + } + + outEntries->push_back(entry); + } + + return true; + } + bool BanManager::LoadIps(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + outEntries->clear(); + + std::string text; + const std::string path = GetBannedIpsFilePath(); + if (!FileUtils::ReadTextFile(path, &text)) + { + LogErrorf("access", "failed to read %s", path.c_str()); + return false; + } + if (text.empty()) + { + text = "[]"; + } + + OrderedJson root; + try + { + // Strip an optional UTF-8 BOM because some editors prepend it when rewriting JSON files. + root = OrderedJson::parse(StringUtils::StripUtf8Bom(text)); + } + catch (const nlohmann::json::exception &e) + { + LogErrorf("access", "failed to parse %s: %s", path.c_str(), e.what()); + return false; + } + + if (!root.is_array()) + { + LogErrorf("access", "failed to parse %s: root json value is not an array", path.c_str()); + return false; + } + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + for (const auto &object : root) + { + if (!object.is_object()) + { + LogWarnf("access", "skipping banned ip entry that is not an object in %s", path.c_str()); + continue; + } + + std::string rawIp; + if (!AccessStorageUtils::TryGetStringField(object, "ip", &rawIp)) + { + LogWarnf("access", "skipping banned ip entry without ip in %s", path.c_str()); + continue; + } + + BannedIpEntry entry; + entry.ip = NetworkUtils::NormalizeIpToken(rawIp); + if (entry.ip.empty()) + { + LogWarnf("access", "skipping banned ip entry with empty ip in %s", path.c_str()); + continue; + } + + AccessStorageUtils::TryGetStringField(object, "created", &entry.metadata.created); + AccessStorageUtils::TryGetStringField(object, "source", &entry.metadata.source); + AccessStorageUtils::TryGetStringField(object, "expires", &entry.metadata.expires); + AccessStorageUtils::TryGetStringField(object, "reason", &entry.metadata.reason); + NormalizeMetadata(&entry.metadata); + + // Ignore entries that already expired before reload so the in-memory cache starts from the active set. + if (IsMetadataExpired(entry.metadata, nowFileTime)) + { + continue; + } + + outEntries->push_back(entry); + } + + return true; + } + bool BanManager::SavePlayers(const std::vector &entries) const + { + OrderedJson root = OrderedJson::array(); + for (const auto &entry : entries) + { + OrderedJson object = OrderedJson::object(); + object["xuid"] = AccessStorageUtils::NormalizeXuid(entry.xuid); + object["name"] = entry.name; + object["created"] = entry.metadata.created; + object["source"] = entry.metadata.source; + object["expires"] = entry.metadata.expires; + object["reason"] = entry.metadata.reason; + root.push_back(object); + } + + const std::string path = GetBannedPlayersFilePath(); + const std::string json = root.empty() ? std::string("[]\n") : (root.dump(2) + "\n"); + if (!FileUtils::WriteTextFileAtomic(path, json)) + { + LogErrorf("access", "failed to write %s", path.c_str()); + return false; + } + return true; + } + + bool BanManager::SaveIps(const std::vector &entries) const + { + OrderedJson root = OrderedJson::array(); + for (const auto &entry : entries) + { + OrderedJson object = OrderedJson::object(); + object["ip"] = NetworkUtils::NormalizeIpToken(entry.ip); + object["created"] = entry.metadata.created; + object["source"] = entry.metadata.source; + object["expires"] = entry.metadata.expires; + object["reason"] = entry.metadata.reason; + root.push_back(object); + } + + const std::string path = GetBannedIpsFilePath(); + const std::string json = root.empty() ? std::string("[]\n") : (root.dump(2) + "\n"); + if (!FileUtils::WriteTextFileAtomic(path, json)) + { + LogErrorf("access", "failed to write %s", path.c_str()); + return false; + } + return true; + } + + const std::vector &BanManager::GetBannedPlayers() const + { + return m_bannedPlayers; + } + + const std::vector &BanManager::GetBannedIps() const + { + return m_bannedIps; + } + + bool BanManager::SnapshotBannedPlayers(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + + outEntries->clear(); + outEntries->reserve(m_bannedPlayers.size()); + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + for (const auto &entry : m_bannedPlayers) + { + if (!IsMetadataExpired(entry.metadata, nowFileTime)) + { + outEntries->push_back(entry); + } + } + return true; + } + + bool BanManager::SnapshotBannedIps(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + + outEntries->clear(); + outEntries->reserve(m_bannedIps.size()); + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + for (const auto &entry : m_bannedIps) + { + if (!IsMetadataExpired(entry.metadata, nowFileTime)) + { + outEntries->push_back(entry); + } + } + return true; + } + bool BanManager::IsPlayerBannedByXuid(const std::string &xuid) const + { + const std::string normalized = AccessStorageUtils::NormalizeXuid(xuid); + if (normalized.empty()) + { + return false; + } + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + return std::any_of( + m_bannedPlayers.begin(), + m_bannedPlayers.end(), + [&normalized, nowFileTime](const BannedPlayerEntry &entry) + { + return entry.xuid == normalized && !IsMetadataExpired(entry.metadata, nowFileTime); + }); + } + + bool BanManager::IsIpBanned(const std::string &ip) const + { + const std::string normalized = NetworkUtils::NormalizeIpToken(ip); + if (normalized.empty()) + { + return false; + } + + const unsigned long long nowFileTime = FileUtils::GetCurrentUtcFileTime(); + return std::any_of( + m_bannedIps.begin(), + m_bannedIps.end(), + [&normalized, nowFileTime](const BannedIpEntry &entry) + { + return entry.ip == normalized && !IsMetadataExpired(entry.metadata, nowFileTime); + }); + } + + bool BanManager::AddPlayerBan(const BannedPlayerEntry &entry) + { + std::vector updatedEntries; + if (!SnapshotBannedPlayers(&updatedEntries)) + { + return false; + } + + BannedPlayerEntry normalized = entry; + normalized.xuid = AccessStorageUtils::NormalizeXuid(normalized.xuid); + NormalizeMetadata(&normalized.metadata); + if (normalized.xuid.empty()) + { + return false; + } + + const auto existing = std::find_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const BannedPlayerEntry &candidate) + { + return candidate.xuid == normalized.xuid; + }); + if (existing != updatedEntries.end()) + { + // Update the existing entry in place so the stored list remains unique by canonical XUID. + *existing = normalized; + if (!SavePlayers(updatedEntries)) + { + return false; + } + m_bannedPlayers.swap(updatedEntries); + return true; + } + + updatedEntries.push_back(normalized); + if (!SavePlayers(updatedEntries)) + { + return false; + } + m_bannedPlayers.swap(updatedEntries); + return true; + } + + bool BanManager::AddIpBan(const BannedIpEntry &entry) + { + std::vector updatedEntries; + if (!SnapshotBannedIps(&updatedEntries)) + { + return false; + } + + BannedIpEntry normalized = entry; + normalized.ip = NetworkUtils::NormalizeIpToken(normalized.ip); + NormalizeMetadata(&normalized.metadata); + if (normalized.ip.empty()) + { + return false; + } + + const auto existing = std::find_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const BannedIpEntry &candidate) + { + return candidate.ip == normalized.ip; + }); + if (existing != updatedEntries.end()) + { + // Update the existing entry in place so the stored list remains unique by normalized IP. + *existing = normalized; + if (!SaveIps(updatedEntries)) + { + return false; + } + m_bannedIps.swap(updatedEntries); + return true; + } + + updatedEntries.push_back(normalized); + if (!SaveIps(updatedEntries)) + { + return false; + } + m_bannedIps.swap(updatedEntries); + return true; + } + + bool BanManager::RemovePlayerBanByXuid(const std::string &xuid) + { + const std::string normalized = AccessStorageUtils::NormalizeXuid(xuid); + if (normalized.empty()) + { + return false; + } + + std::vector updatedEntries; + if (!SnapshotBannedPlayers(&updatedEntries)) + { + return false; + } + + size_t oldSize = updatedEntries.size(); + updatedEntries.erase( + std::remove_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const BannedPlayerEntry &entry) { return entry.xuid == normalized; }), + updatedEntries.end()); + + if (updatedEntries.size() == oldSize) + { + return false; + } + if (!SavePlayers(updatedEntries)) + { + return false; + } + m_bannedPlayers.swap(updatedEntries); + return true; + } + + + bool BanManager::RemoveIpBan(const std::string &ip) + { + const std::string normalized = NetworkUtils::NormalizeIpToken(ip); + if (normalized.empty()) + { + return false; + } + + std::vector updatedEntries; + if (!SnapshotBannedIps(&updatedEntries)) + { + return false; + } + + size_t oldSize = updatedEntries.size(); + updatedEntries.erase( + std::remove_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const BannedIpEntry &entry) { return entry.ip == normalized; }), + updatedEntries.end()); + + if (updatedEntries.size() == oldSize) + { + return false; + } + if (!SaveIps(updatedEntries)) + { + return false; + } + m_bannedIps.swap(updatedEntries); + return true; + } + std::string BanManager::GetBannedPlayersFilePath() const + { + return BuildPath(kBannedPlayersFileName); + } + + std::string BanManager::GetBannedIpsFilePath() const + { + return BuildPath(kBannedIpsFileName); + } + + + BanMetadata BanManager::BuildDefaultMetadata(const char *source) + { + BanMetadata metadata; + metadata.created = StringUtils::GetCurrentUtcTimestampIso8601(); + metadata.source = (source != nullptr) ? source : "Server"; + metadata.expires = ""; + metadata.reason = ""; + return metadata; + } + + + void BanManager::NormalizeMetadata(BanMetadata *metadata) + { + if (metadata == nullptr) + { + return; + } + + metadata->created = StringUtils::TrimAscii(metadata->created); + metadata->source = StringUtils::TrimAscii(metadata->source); + metadata->expires = StringUtils::TrimAscii(metadata->expires); + metadata->reason = StringUtils::TrimAscii(metadata->reason); + } + + + std::string BanManager::BuildPath(const char *fileName) const + { + return AccessStorageUtils::BuildPathFromBaseDirectory(m_baseDirectory, fileName); + } + } +} diff --git a/Minecraft.Server/Access/BanManager.h b/Minecraft.Server/Access/BanManager.h new file mode 100644 index 000000000..59103bec7 --- /dev/null +++ b/Minecraft.Server/Access/BanManager.h @@ -0,0 +1,106 @@ +#pragma once + +#include +#include + +namespace ServerRuntime +{ + namespace Access + { + /** + * Information shared with player bans and IP bans + * プレイヤーBANとIP BANで共有する情報 + */ + struct BanMetadata + { + std::string created; + std::string source; + std::string expires; + std::string reason; + }; + + struct BannedPlayerEntry + { + std::string xuid; + std::string name; + BanMetadata metadata; + }; + + struct BannedIpEntry + { + std::string ip; + BanMetadata metadata; + }; + + /** + * Dedicated server BAN file manager. + * + * Files: + * - banned-players.json + * - banned-ips.json + * + * This class only handles storage/caching. + * Connection-time hooks are wired separately. + */ + class BanManager + { + public: + /** + * **Create Ban Manager** + * + * Binds the manager to the directory that stores the dedicated-server access files + * Dedicated Server のアクセスファイル配置先を設定する + */ + explicit BanManager(const std::string &baseDirectory = "."); + + /** + * Creates empty JSON array files when the dedicated server starts without persisted access data + * BANファイルが無い初回起動時に空JSONを用意する + */ + bool EnsureBanFilesExist() const; + bool Reload(); + bool Save() const; + + bool LoadPlayers(std::vector *outEntries) const; + bool LoadIps(std::vector *outEntries) const; + bool SavePlayers(const std::vector &entries) const; + bool SaveIps(const std::vector &entries) const; + + const std::vector &GetBannedPlayers() const; + const std::vector &GetBannedIps() const; + /** + * Copies only currently active player BAN entries so expired metadata does not leak into command output + * 期限切れを除いた有効なプレイヤーBAN一覧を複製取得する + */ + bool SnapshotBannedPlayers(std::vector *outEntries) const; + /** + * Copies only currently active IP BAN entries so expired metadata does not leak into command output + * 期限切れを除いた有効なIP BAN一覧を複製取得する + */ + bool SnapshotBannedIps(std::vector *outEntries) const; + + bool IsPlayerBannedByXuid(const std::string &xuid) const; + bool IsIpBanned(const std::string &ip) const; + + bool AddPlayerBan(const BannedPlayerEntry &entry); + bool AddIpBan(const BannedIpEntry &entry); + bool RemovePlayerBanByXuid(const std::string &xuid); + bool RemoveIpBan(const std::string &ip); + + std::string GetBannedPlayersFilePath() const; + std::string GetBannedIpsFilePath() const; + + static BanMetadata BuildDefaultMetadata(const char *source = "Server"); + + private: + static void NormalizeMetadata(BanMetadata *metadata); + + std::string BuildPath(const char *fileName) const; + + private: + std::string m_baseDirectory; + std::vector m_bannedPlayers; + std::vector m_bannedIps; + }; + } +} diff --git a/Minecraft.Server/Access/WhitelistManager.cpp b/Minecraft.Server/Access/WhitelistManager.cpp new file mode 100644 index 000000000..33ea7e46a --- /dev/null +++ b/Minecraft.Server/Access/WhitelistManager.cpp @@ -0,0 +1,297 @@ +#include "stdafx.h" + +#include "WhitelistManager.h" + +#include "..\Common\AccessStorageUtils.h" +#include "..\Common\FileUtils.h" +#include "..\Common\StringUtils.h" +#include "..\ServerLogger.h" +#include "..\vendor\nlohmann\json.hpp" + +#include + +namespace ServerRuntime +{ + namespace Access + { + using OrderedJson = nlohmann::ordered_json; + + namespace + { + static const char *kWhitelistFileName = "whitelist.json"; + } + + WhitelistManager::WhitelistManager(const std::string &baseDirectory) + : m_baseDirectory(baseDirectory.empty() ? "." : baseDirectory) + { + } + + bool WhitelistManager::EnsureWhitelistFileExists() const + { + const std::string path = GetWhitelistFilePath(); + if (!AccessStorageUtils::EnsureJsonListFileExists(path)) + { + LogErrorf("access", "failed to create %s", path.c_str()); + return false; + } + return true; + } + + bool WhitelistManager::Reload() + { + std::vector players; + if (!LoadPlayers(&players)) + { + return false; + } + + m_whitelistedPlayers.swap(players); + return true; + } + + bool WhitelistManager::Save() const + { + std::vector players; + return SnapshotWhitelistedPlayers(&players) && SavePlayers(players); + } + + bool WhitelistManager::LoadPlayers(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + outEntries->clear(); + + std::string text; + const std::string path = GetWhitelistFilePath(); + if (!FileUtils::ReadTextFile(path, &text)) + { + LogErrorf("access", "failed to read %s", path.c_str()); + return false; + } + + if (text.empty()) + { + text = "[]"; + } + + OrderedJson root; + try + { + root = OrderedJson::parse(StringUtils::StripUtf8Bom(text)); + } + catch (const nlohmann::json::exception &e) + { + LogErrorf("access", "failed to parse %s: %s", path.c_str(), e.what()); + return false; + } + + if (!root.is_array()) + { + LogErrorf("access", "failed to parse %s: root json value is not an array", path.c_str()); + return false; + } + + for (const auto &object : root) + { + if (!object.is_object()) + { + LogWarnf("access", "skipping whitelist entry that is not an object in %s", path.c_str()); + continue; + } + + std::string rawXuid; + if (!AccessStorageUtils::TryGetStringField(object, "xuid", &rawXuid)) + { + LogWarnf("access", "skipping whitelist entry without xuid in %s", path.c_str()); + continue; + } + + WhitelistedPlayerEntry entry; + entry.xuid = AccessStorageUtils::NormalizeXuid(rawXuid); + if (entry.xuid.empty()) + { + LogWarnf("access", "skipping whitelist entry with empty xuid in %s", path.c_str()); + continue; + } + + AccessStorageUtils::TryGetStringField(object, "name", &entry.name); + AccessStorageUtils::TryGetStringField(object, "created", &entry.metadata.created); + AccessStorageUtils::TryGetStringField(object, "source", &entry.metadata.source); + NormalizeMetadata(&entry.metadata); + + outEntries->push_back(entry); + } + + return true; + } + + bool WhitelistManager::SavePlayers(const std::vector &entries) const + { + OrderedJson root = OrderedJson::array(); + for (const auto &entry : entries) + { + OrderedJson object = OrderedJson::object(); + object["xuid"] = AccessStorageUtils::NormalizeXuid(entry.xuid); + object["name"] = entry.name; + object["created"] = entry.metadata.created; + object["source"] = entry.metadata.source; + root.push_back(object); + } + + const std::string path = GetWhitelistFilePath(); + const std::string json = root.empty() ? std::string("[]\n") : (root.dump(2) + "\n"); + if (!FileUtils::WriteTextFileAtomic(path, json)) + { + LogErrorf("access", "failed to write %s", path.c_str()); + return false; + } + return true; + } + + const std::vector &WhitelistManager::GetWhitelistedPlayers() const + { + return m_whitelistedPlayers; + } + + bool WhitelistManager::SnapshotWhitelistedPlayers(std::vector *outEntries) const + { + if (outEntries == nullptr) + { + return false; + } + + *outEntries = m_whitelistedPlayers; + return true; + } + + bool WhitelistManager::IsPlayerWhitelistedByXuid(const std::string &xuid) const + { + const auto normalized = AccessStorageUtils::NormalizeXuid(xuid); + if (normalized.empty()) + { + return false; + } + + return std::any_of( + m_whitelistedPlayers.begin(), + m_whitelistedPlayers.end(), + [&normalized](const WhitelistedPlayerEntry &entry) + { + return entry.xuid == normalized; + }); + } + + bool WhitelistManager::AddPlayer(const WhitelistedPlayerEntry &entry) + { + std::vector updatedEntries; + if (!SnapshotWhitelistedPlayers(&updatedEntries)) + { + return false; + } + + auto normalized = entry; + normalized.xuid = AccessStorageUtils::NormalizeXuid(normalized.xuid); + NormalizeMetadata(&normalized.metadata); + if (normalized.xuid.empty()) + { + return false; + } + + const auto existing = std::find_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const WhitelistedPlayerEntry &candidate) + { + return candidate.xuid == normalized.xuid; + }); + + if (existing != updatedEntries.end()) + { + *existing = normalized; + if (!SavePlayers(updatedEntries)) + { + return false; + } + + m_whitelistedPlayers.swap(updatedEntries); + return true; + } + + updatedEntries.push_back(normalized); + if (!SavePlayers(updatedEntries)) + { + return false; + } + + m_whitelistedPlayers.swap(updatedEntries); + return true; + } + + bool WhitelistManager::RemovePlayerByXuid(const std::string &xuid) + { + const auto normalized = AccessStorageUtils::NormalizeXuid(xuid); + if (normalized.empty()) + { + return false; + } + + std::vector updatedEntries; + if (!SnapshotWhitelistedPlayers(&updatedEntries)) + { + return false; + } + + const auto oldSize = updatedEntries.size(); + updatedEntries.erase( + std::remove_if( + updatedEntries.begin(), + updatedEntries.end(), + [&normalized](const WhitelistedPlayerEntry &entry) { return entry.xuid == normalized; }), + updatedEntries.end()); + + if (updatedEntries.size() == oldSize) + { + return false; + } + + if (!SavePlayers(updatedEntries)) + { + return false; + } + + m_whitelistedPlayers.swap(updatedEntries); + return true; + } + + std::string WhitelistManager::GetWhitelistFilePath() const + { + return BuildPath(kWhitelistFileName); + } + + WhitelistMetadata WhitelistManager::BuildDefaultMetadata(const char *source) + { + WhitelistMetadata metadata; + metadata.created = StringUtils::GetCurrentUtcTimestampIso8601(); + metadata.source = (source != nullptr) ? source : "Server"; + return metadata; + } + + void WhitelistManager::NormalizeMetadata(WhitelistMetadata *metadata) + { + if (metadata == nullptr) + { + return; + } + + metadata->created = StringUtils::TrimAscii(metadata->created); + metadata->source = StringUtils::TrimAscii(metadata->source); + } + + std::string WhitelistManager::BuildPath(const char *fileName) const + { + return AccessStorageUtils::BuildPathFromBaseDirectory(m_baseDirectory, fileName); + } + } +} diff --git a/Minecraft.Server/Access/WhitelistManager.h b/Minecraft.Server/Access/WhitelistManager.h new file mode 100644 index 000000000..1c2c5a0b5 --- /dev/null +++ b/Minecraft.Server/Access/WhitelistManager.h @@ -0,0 +1,64 @@ +#pragma once + +#include +#include + +namespace ServerRuntime +{ + namespace Access + { + struct WhitelistMetadata + { + std::string created; + std::string source; + }; + + struct WhitelistedPlayerEntry + { + std::string xuid; + std::string name; + WhitelistMetadata metadata; + }; + + /** + * whitelist manager + * + * Files: + * - whitelist.json + * + * Stores and normalizes XUID-based allow entries. + */ + class WhitelistManager + { + public: + explicit WhitelistManager(const std::string &baseDirectory = "."); + + bool EnsureWhitelistFileExists() const; + bool Reload(); + bool Save() const; + + bool LoadPlayers(std::vector *outEntries) const; + bool SavePlayers(const std::vector &entries) const; + + const std::vector &GetWhitelistedPlayers() const; + bool SnapshotWhitelistedPlayers(std::vector *outEntries) const; + + bool IsPlayerWhitelistedByXuid(const std::string &xuid) const; + bool AddPlayer(const WhitelistedPlayerEntry &entry); + bool RemovePlayerByXuid(const std::string &xuid); + + std::string GetWhitelistFilePath() const; + + static WhitelistMetadata BuildDefaultMetadata(const char *source = "Server"); + + private: + static void NormalizeMetadata(WhitelistMetadata *metadata); + + std::string BuildPath(const char *fileName) const; + + private: + std::string m_baseDirectory; + std::vector m_whitelistedPlayers; + }; + } +} diff --git a/Minecraft.Server/Common/AccessStorageUtils.h b/Minecraft.Server/Common/AccessStorageUtils.h new file mode 100644 index 000000000..c5d3477c7 --- /dev/null +++ b/Minecraft.Server/Common/AccessStorageUtils.h @@ -0,0 +1,105 @@ +#pragma once + +#include "FileUtils.h" +#include "StringUtils.h" + +#include "..\vendor\nlohmann\json.hpp" + +#include + +namespace ServerRuntime +{ + namespace AccessStorageUtils + { + inline bool IsRegularFile(const std::string &path) + { + const std::wstring widePath = StringUtils::Utf8ToWide(path); + if (widePath.empty()) + { + return false; + } + + const DWORD attributes = GetFileAttributesW(widePath.c_str()); + return (attributes != INVALID_FILE_ATTRIBUTES) && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0); + } + + inline bool EnsureJsonListFileExists(const std::string &path) + { + return IsRegularFile(path) || FileUtils::WriteTextFileAtomic(path, "[]\n"); + } + + inline bool TryGetStringField(const nlohmann::ordered_json &object, const char *key, std::string *outValue) + { + if (key == nullptr || outValue == nullptr || !object.is_object()) + { + return false; + } + + const auto it = object.find(key); + if (it == object.end() || !it->is_string()) + { + return false; + } + + *outValue = it->get(); + return true; + } + + inline std::string NormalizeXuid(const std::string &xuid) + { + const std::string trimmed = StringUtils::TrimAscii(xuid); + if (trimmed.empty()) + { + return ""; + } + + unsigned long long numericXuid = 0; + if (StringUtils::TryParseUnsignedLongLong(trimmed, &numericXuid)) + { + if (numericXuid == 0ULL) + { + return ""; + } + + char buffer[32] = {}; + sprintf_s(buffer, sizeof(buffer), "0x%016llx", numericXuid); + return buffer; + } + + return StringUtils::ToLowerAscii(trimmed); + } + + inline std::string BuildPathFromBaseDirectory(const std::string &baseDirectory, const char *fileName) + { + if (fileName == nullptr || fileName[0] == 0) + { + return ""; + } + + const std::wstring wideFileName = StringUtils::Utf8ToWide(fileName); + if (wideFileName.empty()) + { + return ""; + } + + if (baseDirectory.empty() || baseDirectory == ".") + { + return StringUtils::WideToUtf8(wideFileName); + } + + const std::wstring wideBaseDirectory = StringUtils::Utf8ToWide(baseDirectory); + if (wideBaseDirectory.empty()) + { + return StringUtils::WideToUtf8(wideFileName); + } + + const wchar_t last = wideBaseDirectory[wideBaseDirectory.size() - 1]; + if (last == L'\\' || last == L'/') + { + return StringUtils::WideToUtf8(wideBaseDirectory + wideFileName); + } + + return StringUtils::WideToUtf8(wideBaseDirectory + L"\\" + wideFileName); + } + } +} diff --git a/Minecraft.Server/Common/FileUtils.cpp b/Minecraft.Server/Common/FileUtils.cpp new file mode 100644 index 000000000..50eeeb72e --- /dev/null +++ b/Minecraft.Server/Common/FileUtils.cpp @@ -0,0 +1,146 @@ +#include "stdafx.h" + +#include "FileUtils.h" + +#include "StringUtils.h" + +#include +#include + +namespace ServerRuntime +{ + namespace FileUtils + { + namespace + { + static std::wstring ToWidePath(const std::string &filePath) + { + return StringUtils::Utf8ToWide(filePath); + } + } + + unsigned long long GetCurrentUtcFileTime() + { + FILETIME now = {}; + GetSystemTimeAsFileTime(&now); + + ULARGE_INTEGER value = {}; + value.LowPart = now.dwLowDateTime; + value.HighPart = now.dwHighDateTime; + return value.QuadPart; + } + + bool ReadTextFile(const std::string &filePath, std::string *outText) + { + if (outText == nullptr) + { + return false; + } + + outText->clear(); + + const std::wstring widePath = ToWidePath(filePath); + if (widePath.empty()) + { + return false; + } + + FILE *inFile = nullptr; + if (_wfopen_s(&inFile, widePath.c_str(), L"rb") != 0 || inFile == nullptr) + { + return false; + } + + if (fseek(inFile, 0, SEEK_END) != 0) + { + fclose(inFile); + return false; + } + + long fileSize = ftell(inFile); + if (fileSize < 0) + { + fclose(inFile); + return false; + } + + if (fseek(inFile, 0, SEEK_SET) != 0) + { + fclose(inFile); + return false; + } + + if (fileSize == 0) + { + fclose(inFile); + return true; + } + + outText->resize((size_t)fileSize); + size_t bytesRead = fread(&(*outText)[0], 1, (size_t)fileSize, inFile); + fclose(inFile); + + if (bytesRead != (size_t)fileSize) + { + outText->clear(); + return false; + } + + return true; + } + + bool WriteTextFileAtomic(const std::string &filePath, const std::string &text) + { + const std::wstring widePath = ToWidePath(filePath); + if (widePath.empty()) + { + return false; + } + + const std::wstring tmpPath = widePath + L".tmp"; + + FILE *outFile = nullptr; + if (_wfopen_s(&outFile, tmpPath.c_str(), L"wb") != 0 || outFile == nullptr) + { + return false; + } + + if (!text.empty()) + { + size_t bytesWritten = fwrite(text.data(), 1, text.size(), outFile); + if (bytesWritten != text.size()) + { + fclose(outFile); + DeleteFileW(tmpPath.c_str()); + return false; + } + } + + if (fflush(outFile) != 0 || _commit(_fileno(outFile)) != 0) + { + fclose(outFile); + DeleteFileW(tmpPath.c_str()); + return false; + } + fclose(outFile); + + DWORD attrs = GetFileAttributesW(widePath.c_str()); + if (attrs != INVALID_FILE_ATTRIBUTES && ((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0)) + { + // Replace the destination without deleting the last known-good file first. + if (ReplaceFileW(widePath.c_str(), tmpPath.c_str(), nullptr, REPLACEFILE_IGNORE_MERGE_ERRORS, nullptr, nullptr)) + { + return true; + } + } + + if (MoveFileExW(tmpPath.c_str(), widePath.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + { + return true; + } + + // Keep the temp file on failure so the original file remains recoverable and the caller can inspect the write result. + return false; + } + } +} \ No newline at end of file diff --git a/Minecraft.Server/Common/FileUtils.h b/Minecraft.Server/Common/FileUtils.h new file mode 100644 index 000000000..96e398ccf --- /dev/null +++ b/Minecraft.Server/Common/FileUtils.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +namespace ServerRuntime +{ + namespace FileUtils + { + /** + * Reads the full UTF-8 path target into memory without interpreting JSON or line endings + * UTF-8パスのテキストファイル全体をそのまま読み込む + */ + bool ReadTextFile(const std::string &filePath, std::string *outText); + /** + * Writes text through a same-directory temporary file and publishes it with a single replacement step + * 同一ディレクトリの一時ファイル経由で安全に書き換える + */ + bool WriteTextFileAtomic(const std::string &filePath, const std::string &text); + /** + * Returns the current UTC timestamp encoded in Windows FILETIME units for expiry comparisons + * 期限判定用に現在UTC時刻をWindows FILETIME単位で返す + */ + unsigned long long GetCurrentUtcFileTime(); + } +} \ No newline at end of file diff --git a/Minecraft.Server/Common/NetworkUtils.h b/Minecraft.Server/Common/NetworkUtils.h new file mode 100644 index 000000000..c77d4506b --- /dev/null +++ b/Minecraft.Server/Common/NetworkUtils.h @@ -0,0 +1,29 @@ +#pragma once + +#include "StringUtils.h" + +#include + +namespace ServerRuntime +{ + namespace NetworkUtils + { + inline std::string NormalizeIpToken(const std::string &ip) + { + return StringUtils::ToLowerAscii(StringUtils::TrimAscii(ip)); + } + + inline bool IsIpLiteral(const std::string &text) + { + const std::string trimmed = StringUtils::TrimAscii(text); + if (trimmed.empty()) + { + return false; + } + + IN_ADDR ipv4 = {}; + IN6_ADDR ipv6 = {}; + return InetPtonA(AF_INET, trimmed.c_str(), &ipv4) == 1 || InetPtonA(AF_INET6, trimmed.c_str(), &ipv6) == 1; + } + } +} diff --git a/Minecraft.Server/Common/StringUtils.cpp b/Minecraft.Server/Common/StringUtils.cpp new file mode 100644 index 000000000..40881ae7b --- /dev/null +++ b/Minecraft.Server/Common/StringUtils.cpp @@ -0,0 +1,212 @@ +#include "stdafx.h" + +#include "StringUtils.h" + +#include +#include +#include +#include + +namespace ServerRuntime +{ + namespace StringUtils + { + std::string WideToUtf8(const std::wstring &value) + { + if (value.empty()) + { + return std::string(); + } + + int charCount = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), (int)value.length(), NULL, 0, NULL, NULL); + if (charCount <= 0) + { + return std::string(); + } + + std::string utf8; + utf8.resize(charCount); + WideCharToMultiByte(CP_UTF8, 0, value.c_str(), (int)value.length(), &utf8[0], charCount, NULL, NULL); + return utf8; + } + + std::wstring Utf8ToWide(const char *value) + { + if (value == NULL || value[0] == 0) + { + return std::wstring(); + } + + int wideCount = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0); + if (wideCount <= 0) + { + // Fall back to the current ANSI code page so legacy non-UTF-8 inputs remain readable. + wideCount = MultiByteToWideChar(CP_ACP, 0, value, -1, NULL, 0); + if (wideCount <= 0) + { + return std::wstring(); + } + + std::wstring wide; + wide.resize(wideCount - 1); + MultiByteToWideChar(CP_ACP, 0, value, -1, &wide[0], wideCount); + return wide; + } + + std::wstring wide; + wide.resize(wideCount - 1); + MultiByteToWideChar(CP_UTF8, 0, value, -1, &wide[0], wideCount); + return wide; + } + + std::wstring Utf8ToWide(const std::string &value) + { + return Utf8ToWide(value.c_str()); + } + + std::string StripUtf8Bom(const std::string &value) + { + if (value.size() >= 3 && + (unsigned char)value[0] == 0xEF && + (unsigned char)value[1] == 0xBB && + (unsigned char)value[2] == 0xBF) + { + return value.substr(3); + } + + return value; + } + + std::string TrimAscii(const std::string &value) + { + size_t start = 0; + while (start < value.length() && std::isspace((unsigned char)value[start])) + { + ++start; + } + + size_t end = value.length(); + while (end > start && std::isspace((unsigned char)value[end - 1])) + { + --end; + } + + return value.substr(start, end - start); + } + + std::string ToLowerAscii(const std::string &value) + { + std::string lowered = value; + for (size_t i = 0; i < lowered.length(); ++i) + { + lowered[i] = (char)std::tolower((unsigned char)lowered[i]); + } + return lowered; + } + + std::string JoinTokens(const std::vector &tokens, size_t startIndex, const char *separator) + { + if (startIndex >= tokens.size()) + { + return std::string(); + } + + const auto joinSeparator = std::string((separator != nullptr) ? separator : " "); + size_t totalLength = 0; + for (size_t i = startIndex; i < tokens.size(); ++i) + { + totalLength += tokens[i].size(); + } + + totalLength += (tokens.size() - startIndex - 1) * joinSeparator.size(); + std::string joined; + joined.reserve(totalLength); + for (size_t i = startIndex; i < tokens.size(); ++i) + { + if (!joined.empty()) + { + joined += joinSeparator; + } + + joined += tokens[i]; + } + + return joined; + } + + bool StartsWithIgnoreCase(const std::string &value, const std::string &prefix) + { + if (prefix.size() > value.size()) + { + return false; + } + + for (size_t i = 0; i < prefix.size(); ++i) + { + unsigned char a = (unsigned char)value[i]; + unsigned char b = (unsigned char)prefix[i]; + if (std::tolower(a) != std::tolower(b)) + { + return false; + } + } + + return true; + } + + bool TryParseUnsignedLongLong(const std::string &value, unsigned long long *outValue) + { + if (outValue == nullptr) + { + return false; + } + + const std::string trimmed = TrimAscii(value); + if (trimmed.empty()) + { + return false; + } + + errno = 0; + char *end = nullptr; + const unsigned long long parsed = _strtoui64(trimmed.c_str(), &end, 0); + if (end == trimmed.c_str() || errno != 0) + { + return false; + } + + while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n') + { + ++end; + } + + if (*end != 0) + { + return false; + } + + *outValue = parsed; + return true; + } + + std::string GetCurrentUtcTimestampIso8601() + { + SYSTEMTIME utc = {}; + GetSystemTime(&utc); + + char created[64] = {}; + sprintf_s( + created, + sizeof(created), + "%04u-%02u-%02uT%02u:%02u:%02uZ", + (unsigned)utc.wYear, + (unsigned)utc.wMonth, + (unsigned)utc.wDay, + (unsigned)utc.wHour, + (unsigned)utc.wMinute, + (unsigned)utc.wSecond); + return created; + } + } +} + diff --git a/Minecraft.Server/Common/StringUtils.h b/Minecraft.Server/Common/StringUtils.h new file mode 100644 index 000000000..68f818e1c --- /dev/null +++ b/Minecraft.Server/Common/StringUtils.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +namespace ServerRuntime +{ + namespace StringUtils + { + std::string WideToUtf8(const std::wstring &value); + std::wstring Utf8ToWide(const char *value); + std::wstring Utf8ToWide(const std::string &value); + std::string StripUtf8Bom(const std::string &value); + + std::string TrimAscii(const std::string &value); + std::string ToLowerAscii(const std::string &value); + std::string JoinTokens(const std::vector &tokens, size_t startIndex = 0, const char *separator = " "); + bool StartsWithIgnoreCase(const std::string &value, const std::string &prefix); + bool TryParseUnsignedLongLong(const std::string &value, unsigned long long *outValue); + std::string GetCurrentUtcTimestampIso8601(); + } +} + diff --git a/Minecraft.Server/Console/ServerCli.cpp b/Minecraft.Server/Console/ServerCli.cpp new file mode 100644 index 000000000..b633effda --- /dev/null +++ b/Minecraft.Server/Console/ServerCli.cpp @@ -0,0 +1,44 @@ +#include "stdafx.h" + +#include "ServerCli.h" + +#include "ServerCliEngine.h" +#include "ServerCliInput.h" + +namespace ServerRuntime +{ + ServerCli::ServerCli() + : m_engine(new ServerCliEngine()) + , m_input(new ServerCliInput()) + { + } + + ServerCli::~ServerCli() + { + Stop(); + } + + void ServerCli::Start() + { + if (m_input && m_engine) + { + m_input->Start(m_engine.get()); + } + } + + void ServerCli::Stop() + { + if (m_input) + { + m_input->Stop(); + } + } + + void ServerCli::Poll() + { + if (m_engine) + { + m_engine->Poll(); + } + } +} diff --git a/Minecraft.Server/Console/ServerCli.h b/Minecraft.Server/Console/ServerCli.h new file mode 100644 index 000000000..f544450b5 --- /dev/null +++ b/Minecraft.Server/Console/ServerCli.h @@ -0,0 +1,50 @@ +#pragma once + +#include + +namespace ServerRuntime +{ + class ServerCliEngine; + class ServerCliInput; + + /** + * **Server CLI facade** + * + * Owns the command engine and input component, and exposes a small lifecycle API. + * CLI 全体の開始・停止・更新をまとめる窓口クラス + */ + class ServerCli + { + public: + ServerCli(); + ~ServerCli(); + + /** + * **Start console input processing** + * + * Connects input to the engine and starts background reading. + * 入力処理を開始してエンジンに接続 + */ + void Start(); + + /** + * **Stop console input processing** + * + * Stops background input safely and detaches from the engine. + * 入力処理を安全に停止 + */ + void Stop(); + + /** + * **Process queued command lines** + * + * Drains commands collected by input and executes them in the main loop. + * 入力キューのコマンドを実行 + */ + void Poll(); + + private: + std::unique_ptr m_engine; + std::unique_ptr m_input; + }; +} diff --git a/Minecraft.Server/Console/ServerCliEngine.cpp b/Minecraft.Server/Console/ServerCliEngine.cpp new file mode 100644 index 000000000..82bbdcc8e --- /dev/null +++ b/Minecraft.Server/Console/ServerCliEngine.cpp @@ -0,0 +1,395 @@ +#include "stdafx.h" + +#include "ServerCliEngine.h" + +#include "ServerCliParser.h" +#include "ServerCliRegistry.h" +#include "commands\IServerCliCommand.h" +#include "commands\ban\CliCommandBan.h" +#include "commands\ban-ip\CliCommandBanIp.h" +#include "commands\ban-list\CliCommandBanList.h" +#include "commands\defaultgamemode\CliCommandDefaultGamemode.h" +#include "commands\enchant\CliCommandEnchant.h" +#include "commands\experience\CliCommandExperience.h" +#include "commands\gamemode\CliCommandGamemode.h" +#include "commands\give\CliCommandGive.h" +#include "commands\help\CliCommandHelp.h" +#include "commands\kill\CliCommandKill.h" +#include "commands\list\CliCommandList.h" +#include "commands\pardon\CliCommandPardon.h" +#include "commands\pardon-ip\CliCommandPardonIp.h" +#include "commands\stop\CliCommandStop.h" +#include "commands\time\CliCommandTime.h" +#include "commands\tp\CliCommandTp.h" +#include "commands\weather\CliCommandWeather.h" +#include "commands\whitelist\CliCommandWhitelist.h" +#include "..\Common\StringUtils.h" +#include "..\ServerShutdown.h" +#include "..\ServerLogger.h" +#include "..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\Minecraft.Client\PlayerList.h" +#include "..\..\Minecraft.Client\ServerPlayer.h" +#include "..\..\Minecraft.World\CommandDispatcher.h" +#include "..\..\Minecraft.World\CommandSender.h" +#include "..\..\Minecraft.World\LevelSettings.h" +#include "..\..\Minecraft.World\StringHelpers.h" + +#include +#include + +namespace ServerRuntime +{ + + /** + * Create an authorized Sender to make the CLI appear as a user. + * The return value can also be used to display logs. + */ + namespace + { + class ServerCliConsoleCommandSender : public CommandSender + { + public: + explicit ServerCliConsoleCommandSender(const ServerCliEngine *engine) + : m_engine(engine) + { + } + + void sendMessage(const wstring &message, ChatPacket::EChatPacketMessage type, int customData, const wstring &additionalMessage) override + { + (void)type; + (void)customData; + (void)additionalMessage; + if (m_engine == nullptr) + { + return; + } + + m_engine->LogInfo(StringUtils::WideToUtf8(message)); + } + + bool hasPermission(EGameCommand command) override + { + (void)command; + return true; + } + + private: + const ServerCliEngine *m_engine; + }; + } + + ServerCliEngine::ServerCliEngine() + : m_registry(new ServerCliRegistry()) + , m_consoleSender(std::make_shared(this)) + { + RegisterDefaultCommands(); + } + + ServerCliEngine::~ServerCliEngine() + { + } + + void ServerCliEngine::RegisterDefaultCommands() + { + m_registry->Register(std::unique_ptr(new CliCommandHelp())); + m_registry->Register(std::unique_ptr(new CliCommandStop())); + m_registry->Register(std::unique_ptr(new CliCommandList())); + m_registry->Register(std::unique_ptr(new CliCommandBan())); + m_registry->Register(std::unique_ptr(new CliCommandBanIp())); + m_registry->Register(std::unique_ptr(new CliCommandPardon())); + m_registry->Register(std::unique_ptr(new CliCommandPardonIp())); + m_registry->Register(std::unique_ptr(new CliCommandBanList())); + m_registry->Register(std::unique_ptr(new CliCommandWhitelist())); + m_registry->Register(std::unique_ptr(new CliCommandTp())); + m_registry->Register(std::unique_ptr(new CliCommandTime())); + m_registry->Register(std::unique_ptr(new CliCommandWeather())); + m_registry->Register(std::unique_ptr(new CliCommandGive())); + m_registry->Register(std::unique_ptr(new CliCommandEnchant())); + m_registry->Register(std::unique_ptr(new CliCommandKill())); + m_registry->Register(std::unique_ptr(new CliCommandGamemode())); + m_registry->Register(std::unique_ptr(new CliCommandDefaultGamemode())); + m_registry->Register(std::unique_ptr(new CliCommandExperience())); + } + + void ServerCliEngine::EnqueueCommandLine(const std::string &line) + { + std::lock_guard lock(m_queueMutex); + m_pendingLines.push(line); + } + + void ServerCliEngine::Poll() + { + for (;;) + { + std::string line; + { + // Keep the lock scope minimal: dequeue only, execute outside. + std::lock_guard lock(m_queueMutex); + if (m_pendingLines.empty()) + { + break; + } + line = m_pendingLines.front(); + m_pendingLines.pop(); + } + + ExecuteCommandLine(line); + } + } + + bool ServerCliEngine::ExecuteCommandLine(const std::string &line) + { + // Normalize user input before parsing (trim + optional leading slash). + std::wstring wide = trimString(StringUtils::Utf8ToWide(line)); + if (wide.empty()) + { + return true; + } + + std::string normalizedLine = StringUtils::WideToUtf8(wide); + if (!normalizedLine.empty() && normalizedLine[0] == '/') + { + normalizedLine = normalizedLine.substr(1); + } + + ServerCliParsedLine parsed = ServerCliParser::Parse(normalizedLine); + if (parsed.tokens.empty()) + { + return true; + } + + IServerCliCommand *command = m_registry->FindMutable(parsed.tokens[0]); + if (command == NULL) + { + LogWarn("Unknown command: " + parsed.tokens[0]); + return false; + } + + return command->Execute(parsed, this); + } + + void ServerCliEngine::BuildCompletions(const std::string &line, std::vector *out) const + { + if (out == NULL) + { + return; + } + + out->clear(); + ServerCliCompletionContext context = ServerCliParser::BuildCompletionContext(line); + bool slashPrefixedCommand = false; + std::string commandToken; + if (!context.parsed.tokens.empty()) + { + // Completion accepts both "tp" and "/tp" style command heads. + commandToken = context.parsed.tokens[0]; + if (!commandToken.empty() && commandToken[0] == '/') + { + commandToken = commandToken.substr(1); + slashPrefixedCommand = true; + } + } + + if (context.currentTokenIndex == 0) + { + std::string prefix = context.prefix; + if (!prefix.empty() && prefix[0] == '/') + { + prefix = prefix.substr(1); + slashPrefixedCommand = true; + } + + std::string linePrefix = context.linePrefix; + if (slashPrefixedCommand && linePrefix.empty()) + { + // Preserve leading slash when user started with "/". + linePrefix = "/"; + } + + m_registry->SuggestCommandNames(prefix, linePrefix, out); + } + else + { + const IServerCliCommand *command = m_registry->Find(commandToken); + if (command != NULL) + { + command->Complete(context, this, out); + } + } + + std::unordered_set seen; + std::vector unique; + for (size_t i = 0; i < out->size(); ++i) + { + // Remove duplicates while keeping first-seen ordering. + if (seen.insert((*out)[i]).second) + { + unique.push_back((*out)[i]); + } + } + out->swap(unique); + } + + void ServerCliEngine::LogInfo(const std::string &message) const + { + LogInfof("console", "%s", message.c_str()); + } + + void ServerCliEngine::LogWarn(const std::string &message) const + { + LogWarnf("console", "%s", message.c_str()); + } + + void ServerCliEngine::LogError(const std::string &message) const + { + LogErrorf("console", "%s", message.c_str()); + } + + void ServerCliEngine::RequestShutdown() const + { + RequestDedicatedServerShutdown(); + } + + std::vector ServerCliEngine::GetOnlinePlayerNamesUtf8() const + { + std::vector result; + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == NULL) + { + return result; + } + + PlayerList *players = server->getPlayers(); + if (players == NULL) + { + return result; + } + + for (size_t i = 0; i < players->players.size(); ++i) + { + std::shared_ptr player = players->players[i]; + if (player != NULL) + { + result.push_back(StringUtils::WideToUtf8(player->getName())); + } + } + + return result; + } + + std::shared_ptr ServerCliEngine::FindPlayerByNameUtf8(const std::string &name) const + { + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == NULL) + { + return nullptr; + } + + PlayerList *players = server->getPlayers(); + if (players == NULL) + { + return nullptr; + } + + std::wstring target = StringUtils::Utf8ToWide(name); + for (size_t i = 0; i < players->players.size(); ++i) + { + std::shared_ptr player = players->players[i]; + if (player != NULL && equalsIgnoreCase(player->getName(), target)) + { + return player; + } + } + + return nullptr; + } + + void ServerCliEngine::SuggestPlayers(const std::string &prefix, const std::string &linePrefix, std::vector *out) const + { + std::vector players = GetOnlinePlayerNamesUtf8(); + std::string loweredPrefix = StringUtils::ToLowerAscii(prefix); + for (size_t i = 0; i < players.size(); ++i) + { + std::string loweredName = StringUtils::ToLowerAscii(players[i]); + if (loweredName.compare(0, loweredPrefix.size(), loweredPrefix) == 0) + { + out->push_back(linePrefix + players[i]); + } + } + } + + void ServerCliEngine::SuggestGamemodes(const std::string &prefix, const std::string &linePrefix, std::vector *out) const + { + static const char *kModes[] = { "survival", "creative", "s", "c", "0", "1" }; + std::string loweredPrefix = StringUtils::ToLowerAscii(prefix); + for (size_t i = 0; i < sizeof(kModes) / sizeof(kModes[0]); ++i) + { + std::string candidate = kModes[i]; + std::string loweredCandidate = StringUtils::ToLowerAscii(candidate); + if (loweredCandidate.compare(0, loweredPrefix.size(), loweredPrefix) == 0) + { + out->push_back(linePrefix + candidate); + } + } + } + + GameType *ServerCliEngine::ParseGamemode(const std::string &token) const + { + std::string lowered = StringUtils::ToLowerAscii(token); + if (lowered == "survival" || lowered == "s" || lowered == "0") + { + return GameType::SURVIVAL; + } + if (lowered == "creative" || lowered == "c" || lowered == "1") + { + return GameType::CREATIVE; + } + + char *end = NULL; + long id = strtol(lowered.c_str(), &end, 10); + if (end != NULL && *end == 0) + { + // Numeric fallback supports extended ids handled by level settings. + return LevelSettings::validateGameType((int)id); + } + + return NULL; + } + + bool ServerCliEngine::DispatchWorldCommand(EGameCommand command, byteArray commandData, const std::shared_ptr &sender) const + { + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == NULL) + { + LogWarn("MinecraftServer instance is not available."); + return false; + } + + CommandDispatcher *dispatcher = server->getCommandDispatcher(); + if (dispatcher == NULL) + { + LogWarn("Command dispatcher is not available."); + return false; + } + + std::shared_ptr commandSender = sender; + if (commandSender == nullptr) + { + // fall back to console sender if caller did not provide one + commandSender = m_consoleSender; + } + if (commandSender == nullptr) + { + LogWarn("No command sender is available."); + return false; + } + + dispatcher->performCommand(commandSender, command, commandData); + return true; + } + + const ServerCliRegistry &ServerCliEngine::Registry() const + { + return *m_registry; + } +} diff --git a/Minecraft.Server/Console/ServerCliEngine.h b/Minecraft.Server/Console/ServerCliEngine.h new file mode 100644 index 000000000..b2d72bace --- /dev/null +++ b/Minecraft.Server/Console/ServerCliEngine.h @@ -0,0 +1,127 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "..\..\Minecraft.World\ArrayWithLength.h" +#include "..\..\Minecraft.World\CommandsEnum.h" + +class GameType; +class ServerPlayer; +class CommandSender; + +namespace ServerRuntime +{ + class ServerCliRegistry; + + /** + * **CLI execution engine** + * + * Handles parsing, command dispatch, completion suggestions, and server-side helpers. + * 解析・実行・補完エンジン + */ + class ServerCliEngine + { + public: + ServerCliEngine(); + ~ServerCliEngine(); + + /** + * **Queue one raw command line** + * + * Called by input thread; execution is deferred to `Poll()`. + * 入力行を実行キューに追加 + */ + void EnqueueCommandLine(const std::string &line); + + /** + * **Execute queued commands** + * + * Drains pending lines and dispatches them in order. + * キュー済みコマンドを順番に実行 + */ + void Poll(); + + /** + * **Execute one command line immediately** + * + * Parses and dispatches a normalized line to a registered command. + * 1行を直接パースしてコマンド実行 + */ + bool ExecuteCommandLine(const std::string &line); + + /** + * **Build completion candidates for current line** + * + * Produces command or argument suggestions based on parser context. + * 現在入力に対する補完候補を作成 + */ + void BuildCompletions(const std::string &line, std::vector *out) const; + + void LogInfo(const std::string &message) const; + void LogWarn(const std::string &message) const; + void LogError(const std::string &message) const; + void RequestShutdown() const; + + /** + * **List connected players as UTF-8 names** + * + * ここら辺は分けてもいいかも + */ + std::vector GetOnlinePlayerNamesUtf8() const; + + /** + * **Find a player by UTF-8 name** + */ + std::shared_ptr FindPlayerByNameUtf8(const std::string &name) const; + + /** + * **Suggest player-name arguments** + * + * Appends matching player candidates using the given completion prefix. + * プレイヤー名の補完候補 + */ + void SuggestPlayers(const std::string &prefix, const std::string &linePrefix, std::vector *out) const; + + /** + * **Suggest gamemode arguments** + * + * Appends standard gamemode aliases (survival/creative/0/1). + * ゲームモードの補完候補 + */ + void SuggestGamemodes(const std::string &prefix, const std::string &linePrefix, std::vector *out) const; + + /** + * **Parse gamemode token** + * + * Supports names, short aliases, and numeric ids. + * 文字列からゲームモードを解決 + */ + GameType *ParseGamemode(const std::string &token) const; + + /** + * **Dispatch one Minecraft.World game command** + * + * Uses `Minecraft.World::CommandDispatcher` for actual execution. + * When `sender` is null, an internal console command sender is used. + * + * Minecraft.Worldのコマンドを実行するためのディスパッチャーのラッパー + * 内部でsenderがnullの場合はコンソールコマンド送信者を使用 + */ + bool DispatchWorldCommand(EGameCommand command, byteArray commandData, const std::shared_ptr &sender = nullptr) const; + + const ServerCliRegistry &Registry() const; + + private: + void RegisterDefaultCommands(); + + private: + mutable std::mutex m_queueMutex; + std::queue m_pendingLines; + std::unique_ptr m_registry; + std::shared_ptr m_consoleSender; + }; +} diff --git a/Minecraft.Server/Console/ServerCliInput.cpp b/Minecraft.Server/Console/ServerCliInput.cpp new file mode 100644 index 000000000..d873980a0 --- /dev/null +++ b/Minecraft.Server/Console/ServerCliInput.cpp @@ -0,0 +1,285 @@ +#include "stdafx.h" + +#include "ServerCliInput.h" + +#include "ServerCliEngine.h" +#include "..\ServerLogger.h" +#include "..\vendor\linenoise\linenoise.h" + +#include +#include + +namespace +{ + bool UseStreamInputMode() + { + const char *mode = getenv("SERVER_CLI_INPUT_MODE"); + if (mode != NULL) + { + return _stricmp(mode, "stream") == 0 + || _stricmp(mode, "stdin") == 0; + } + + return false; + } + + int WaitForStdinReadable(HANDLE stdinHandle, DWORD waitMs) + { + if (stdinHandle == NULL || stdinHandle == INVALID_HANDLE_VALUE) + { + return -1; + } + + DWORD fileType = GetFileType(stdinHandle); + if (fileType == FILE_TYPE_PIPE) + { + DWORD available = 0; + if (!PeekNamedPipe(stdinHandle, NULL, 0, NULL, &available, NULL)) + { + return -1; + } + return available > 0 ? 1 : 0; + } + + if (fileType == FILE_TYPE_CHAR) + { + // console/pty char handles are often not waitable across Wine+Docker. + return 1; + } + + DWORD waitResult = WaitForSingleObject(stdinHandle, waitMs); + if (waitResult == WAIT_OBJECT_0) + { + return 1; + } + if (waitResult == WAIT_TIMEOUT) + { + return 0; + } + + return -1; + } +} + +namespace ServerRuntime +{ + // C-style completion callback bridge requires a static instance pointer. + ServerCliInput *ServerCliInput::s_instance = NULL; + + ServerCliInput::ServerCliInput() + : m_running(false) + , m_engine(NULL) + { + } + + ServerCliInput::~ServerCliInput() + { + Stop(); + } + + void ServerCliInput::Start(ServerCliEngine *engine) + { + if (engine == NULL || m_running.exchange(true)) + { + return; + } + + m_engine = engine; + s_instance = this; + linenoiseResetStop(); + linenoiseHistorySetMaxLen(128); + linenoiseSetCompletionCallback(&ServerCliInput::CompletionThunk); + m_inputThread = std::thread(&ServerCliInput::RunInputLoop, this); + LogInfo("console", "CLI input thread started."); + } + + void ServerCliInput::Stop() + { + if (!m_running.exchange(false)) + { + return; + } + + // Ask linenoise to break out first, then join thread safely. + linenoiseRequestStop(); + if (m_inputThread.joinable()) + { + CancelSynchronousIo((HANDLE)m_inputThread.native_handle()); + m_inputThread.join(); + } + linenoiseSetCompletionCallback(NULL); + + if (s_instance == this) + { + s_instance = NULL; + } + + m_engine = NULL; + LogInfo("console", "CLI input thread stopped."); + } + + bool ServerCliInput::IsRunning() const + { + return m_running.load(); + } + + void ServerCliInput::RunInputLoop() + { + if (UseStreamInputMode()) + { + LogInfo("console", "CLI input mode: stream(file stdin)"); + RunStreamInputLoop(); + return; + } + + RunLinenoiseLoop(); + } + + /** + * use linenoise for interactive console input, with line editing and history support + */ + void ServerCliInput::RunLinenoiseLoop() + { + while (m_running) + { + char *line = linenoise("server> "); + if (line == NULL) + { + // NULL is expected on stop request (or Ctrl+C inside linenoise). + if (!m_running) + { + break; + } + Sleep(10); + continue; + } + + EnqueueLine(line); + + linenoiseFree(line); + } + } + + /** + * use file-based stdin reading instead of linenoise when requested or when stdin is not a console/pty (e.g. piped input or non-interactive docker) + */ + void ServerCliInput::RunStreamInputLoop() + { + HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE); + if (stdinHandle == NULL || stdinHandle == INVALID_HANDLE_VALUE) + { + LogWarn("console", "stream input mode requested but STDIN handle is unavailable; falling back to linenoise."); + RunLinenoiseLoop(); + return; + } + + std::string line; + bool skipNextLf = false; + + printf("server> "); + fflush(stdout); + + while (m_running) + { + int readable = WaitForStdinReadable(stdinHandle, 50); + if (readable <= 0) + { + Sleep(10); + continue; + } + + char ch = 0; + DWORD bytesRead = 0; + if (!ReadFile(stdinHandle, &ch, 1, &bytesRead, NULL) || bytesRead == 0) + { + Sleep(10); + continue; + } + + if (skipNextLf && ch == '\n') + { + skipNextLf = false; + continue; + } + + if (ch == '\r' || ch == '\n') + { + if (ch == '\r') + { + skipNextLf = true; + } + else + { + skipNextLf = false; + } + + if (!line.empty()) + { + EnqueueLine(line.c_str()); + line.clear(); + } + + printf("server> "); + fflush(stdout); + continue; + } + + skipNextLf = false; + + if ((unsigned char)ch == 3) + { + continue; + } + + if ((unsigned char)ch == 8 || (unsigned char)ch == 127) + { + if (!line.empty()) + { + line.resize(line.size() - 1); + } + continue; + } + + if (isprint((unsigned char)ch) && line.size() < 4096) + { + line.push_back(ch); + } + } + } + + void ServerCliInput::EnqueueLine(const char *line) + { + if (line == NULL || line[0] == 0 || m_engine == NULL) + { + return; + } + + // Keep local history and forward command for main-thread execution. + linenoiseHistoryAdd(line); + m_engine->EnqueueCommandLine(line); + } + + void ServerCliInput::CompletionThunk(const char *line, linenoiseCompletions *completions) + { + // Static thunk forwards callback into instance state. + if (s_instance != NULL) + { + s_instance->BuildCompletions(line, completions); + } + } + + void ServerCliInput::BuildCompletions(const char *line, linenoiseCompletions *completions) + { + if (line == NULL || completions == NULL || m_engine == NULL) + { + return; + } + + std::vector suggestions; + m_engine->BuildCompletions(line, &suggestions); + for (size_t i = 0; i < suggestions.size(); ++i) + { + linenoiseAddCompletion(completions, suggestions[i].c_str()); + } + } +} diff --git a/Minecraft.Server/Console/ServerCliInput.h b/Minecraft.Server/Console/ServerCliInput.h new file mode 100644 index 000000000..83221a2c0 --- /dev/null +++ b/Minecraft.Server/Console/ServerCliInput.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +struct linenoiseCompletions; + +namespace ServerRuntime +{ + class ServerCliEngine; + + /** + * **CLI input worker** + * + * Owns the interactive input thread and bridges linenoise callbacks to the engine. + * 入力スレッドと補完コールバックを管理するクラス + */ + class ServerCliInput + { + public: + ServerCliInput(); + ~ServerCliInput(); + + /** + * **Start input loop** + * + * Binds to an engine and starts reading user input from the console. + * エンジンに接続して入力ループを開始 + */ + void Start(ServerCliEngine *engine); + + /** + * **Stop input loop** + * + * Requests stop and joins the input thread. + * 停止要求を出して入力スレッドを終了 + */ + void Stop(); + + /** + * **Check running state** + * + * Returns true while the input thread is active. + * 入力処理が動作中かどうか + */ + bool IsRunning() const; + + private: + void RunInputLoop(); + void RunLinenoiseLoop(); + void RunStreamInputLoop(); + void EnqueueLine(const char *line); + static void CompletionThunk(const char *line, linenoiseCompletions *completions); + void BuildCompletions(const char *line, linenoiseCompletions *completions); + + private: + std::atomic m_running; + std::thread m_inputThread; + ServerCliEngine *m_engine; + + static ServerCliInput *s_instance; + }; +} diff --git a/Minecraft.Server/Console/ServerCliParser.cpp b/Minecraft.Server/Console/ServerCliParser.cpp new file mode 100644 index 000000000..5888153fa --- /dev/null +++ b/Minecraft.Server/Console/ServerCliParser.cpp @@ -0,0 +1,116 @@ +#include "stdafx.h" + +#include "ServerCliParser.h" + +namespace ServerRuntime +{ + static void TokenizeLine(const std::string &line, std::vector *tokens, bool *trailingSpace) + { + std::string current; + bool inQuotes = false; + bool escaped = false; + + tokens->clear(); + *trailingSpace = false; + + for (size_t i = 0; i < line.size(); ++i) + { + char ch = line[i]; + if (escaped) + { + // Keep escaped character literally (e.g. \" or \ ). + current.push_back(ch); + escaped = false; + continue; + } + + if (ch == '\\') + { + escaped = true; + continue; + } + + if (ch == '"') + { + // Double quotes group spaces into one token. + inQuotes = !inQuotes; + continue; + } + + if (!inQuotes && (ch == ' ' || ch == '\t')) + { + if (!current.empty()) + { + tokens->push_back(current); + current.clear(); + } + continue; + } + + current.push_back(ch); + } + + if (!current.empty()) + { + tokens->push_back(current); + } + + if (!line.empty()) + { + char tail = line[line.size() - 1]; + // Trailing space means completion targets the next token slot. + *trailingSpace = (!inQuotes && (tail == ' ' || tail == '\t')); + } + } + + ServerCliParsedLine ServerCliParser::Parse(const std::string &line) + { + ServerCliParsedLine parsed; + parsed.raw = line; + TokenizeLine(line, &parsed.tokens, &parsed.trailingSpace); + return parsed; + } + + ServerCliCompletionContext ServerCliParser::BuildCompletionContext(const std::string &line) + { + ServerCliCompletionContext context; + context.parsed = Parse(line); + + if (context.parsed.tokens.empty()) + { + context.currentTokenIndex = 0; + context.prefix.clear(); + context.linePrefix.clear(); + return context; + } + + if (context.parsed.trailingSpace) + { + // Cursor is after a separator, so complete a new token. + context.currentTokenIndex = context.parsed.tokens.size(); + context.prefix.clear(); + } + else + { + // Cursor is inside current token, so complete by its prefix. + context.currentTokenIndex = context.parsed.tokens.size() - 1; + context.prefix = context.parsed.tokens.back(); + } + + for (size_t i = 0; i < context.currentTokenIndex; ++i) + { + // linePrefix is the immutable left side reused by completion output. + if (!context.linePrefix.empty()) + { + context.linePrefix.push_back(' '); + } + context.linePrefix += context.parsed.tokens[i]; + } + if (!context.linePrefix.empty()) + { + context.linePrefix.push_back(' '); + } + + return context; + } +} diff --git a/Minecraft.Server/Console/ServerCliParser.h b/Minecraft.Server/Console/ServerCliParser.h new file mode 100644 index 000000000..a84d179bf --- /dev/null +++ b/Minecraft.Server/Console/ServerCliParser.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +namespace ServerRuntime +{ + /** + * **Parsed command line** + */ + struct ServerCliParsedLine + { + std::string raw; + std::vector tokens; + bool trailingSpace; + + ServerCliParsedLine() + : trailingSpace(false) + { + } + }; + + /** + * **Completion context for one input line** + * + * Indicates current token index, token prefix, and the fixed line prefix. + */ + struct ServerCliCompletionContext + { + ServerCliParsedLine parsed; + size_t currentTokenIndex; + std::string prefix; + std::string linePrefix; + + ServerCliCompletionContext() + : currentTokenIndex(0) + { + } + }; + + /** + * **CLI parser helpers** + * + * Converts raw input text into tokenized data used by execution and completion. + */ + class ServerCliParser + { + public: + /** + * **Tokenize one command line** + * + * Supports quoted segments and escaped characters. + */ + static ServerCliParsedLine Parse(const std::string &line); + + /** + * **Build completion metadata** + * + * Determines active token position and reusable prefix parts. + */ + static ServerCliCompletionContext BuildCompletionContext(const std::string &line); + }; +} diff --git a/Minecraft.Server/Console/ServerCliRegistry.cpp b/Minecraft.Server/Console/ServerCliRegistry.cpp new file mode 100644 index 000000000..432907b23 --- /dev/null +++ b/Minecraft.Server/Console/ServerCliRegistry.cpp @@ -0,0 +1,99 @@ +#include "stdafx.h" + +#include "ServerCliRegistry.h" + +#include "commands\IServerCliCommand.h" +#include "..\Common\StringUtils.h" + +namespace ServerRuntime +{ + bool ServerCliRegistry::Register(std::unique_ptr command) + { + if (!command) + { + return false; + } + + IServerCliCommand *raw = command.get(); + std::string baseName = StringUtils::ToLowerAscii(raw->Name()); + // Reject empty/duplicate primary command names. + if (baseName.empty() || m_lookup.find(baseName) != m_lookup.end()) + { + return false; + } + std::vector aliases = raw->Aliases(); + std::vector normalizedAliases; + normalizedAliases.reserve(aliases.size()); + for (size_t i = 0; i < aliases.size(); ++i) + { + std::string alias = StringUtils::ToLowerAscii(aliases[i]); + // Alias must also be unique across all names and aliases. + if (alias.empty() || m_lookup.find(alias) != m_lookup.end()) + { + return false; + } + normalizedAliases.push_back(alias); + } + + m_lookup[baseName] = raw; + for (size_t i = 0; i < normalizedAliases.size(); ++i) + { + m_lookup[normalizedAliases[i]] = raw; + } + + // Command objects are owned here; lookup stores non-owning pointers. + m_commands.push_back(std::move(command)); + return true; + } + + const IServerCliCommand *ServerCliRegistry::Find(const std::string &name) const + { + std::string key = StringUtils::ToLowerAscii(name); + auto it = m_lookup.find(key); + if (it == m_lookup.end()) + { + return NULL; + } + return it->second; + } + + IServerCliCommand *ServerCliRegistry::FindMutable(const std::string &name) + { + std::string key = StringUtils::ToLowerAscii(name); + auto it = m_lookup.find(key); + if (it == m_lookup.end()) + { + return NULL; + } + return it->second; + } + + void ServerCliRegistry::SuggestCommandNames(const std::string &prefix, const std::string &linePrefix, std::vector *out) const + { + for (size_t i = 0; i < m_commands.size(); ++i) + { + const IServerCliCommand *command = m_commands[i].get(); + std::string name = command->Name(); + if (StringUtils::StartsWithIgnoreCase(name, prefix)) + { + out->push_back(linePrefix + name); + } + + // Include aliases so users can discover shorthand commands. + std::vector aliases = command->Aliases(); + for (size_t aliasIndex = 0; aliasIndex < aliases.size(); ++aliasIndex) + { + if (StringUtils::StartsWithIgnoreCase(aliases[aliasIndex], prefix)) + { + out->push_back(linePrefix + aliases[aliasIndex]); + } + } + } + } + + const std::vector> &ServerCliRegistry::Commands() const + { + return m_commands; + } +} + diff --git a/Minecraft.Server/Console/ServerCliRegistry.h b/Minecraft.Server/Console/ServerCliRegistry.h new file mode 100644 index 000000000..5104b5345 --- /dev/null +++ b/Minecraft.Server/Console/ServerCliRegistry.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include + +namespace ServerRuntime +{ + class IServerCliCommand; + + /** + * **CLI command registry** + */ + class ServerCliRegistry + { + public: + /** + * **Register a command object** + * + * Validates name/aliases and adds lookup entries. + * コマンドの追加 + */ + bool Register(std::unique_ptr command); + + /** + * **Find command by name or alias (const)** + * + * Returns null when no match exists. + */ + const IServerCliCommand *Find(const std::string &name) const; + + /** + * **Find mutable command by name or alias** + * + * Used by runtime dispatch path. + */ + IServerCliCommand *FindMutable(const std::string &name); + + /** + * **Suggest top-level command names** + * + * Adds matching command names and aliases to the output list. + */ + void SuggestCommandNames(const std::string &prefix, const std::string &linePrefix, std::vector *out) const; + + /** + * **Get registered command list** + * + * Intended for help output and inspection. + */ + const std::vector> &Commands() const; + + private: + std::vector> m_commands; + std::unordered_map m_lookup; + }; +} diff --git a/Minecraft.Server/Console/commands/CommandParsing.h b/Minecraft.Server/Console/commands/CommandParsing.h new file mode 100644 index 000000000..edef68d0e --- /dev/null +++ b/Minecraft.Server/Console/commands/CommandParsing.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include +#include +#include + +namespace ServerRuntime +{ + namespace CommandParsing + { + inline bool TryParseInt(const std::string &text, int *outValue) + { + if (outValue == nullptr || text.empty()) + { + return false; + } + + char *end = nullptr; + errno = 0; + const long parsedValue = std::strtol(text.c_str(), &end, 10); + if (end == text.c_str() || *end != '\0') + { + return false; + } + if (errno == ERANGE) + { + return false; + } + if (parsedValue < (std::numeric_limits::min)() || parsedValue > (std::numeric_limits::max)()) + { + return false; + } + + *outValue = static_cast(parsedValue); + return true; + } + } +} diff --git a/Minecraft.Server/Console/commands/IServerCliCommand.h b/Minecraft.Server/Console/commands/IServerCliCommand.h new file mode 100644 index 000000000..9cf5ef0e3 --- /dev/null +++ b/Minecraft.Server/Console/commands/IServerCliCommand.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +namespace ServerRuntime +{ + class ServerCliEngine; + struct ServerCliParsedLine; + struct ServerCliCompletionContext; + + /** + * **Command interface for server CLI** + * + * Implement this contract to add new commands without changing engine internals. + */ + class IServerCliCommand + { + public: + virtual ~IServerCliCommand() = default; + + /** Primary command name */ + virtual const char *Name() const = 0; + /** Optional aliases */ + virtual std::vector Aliases() const { return {}; } + /** Usage text for help */ + virtual const char *Usage() const = 0; + /** Short command description*/ + virtual const char *Description() const = 0; + + /** + * **Execute command logic** + * + * Called after tokenization and command lookup. + */ + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) = 0; + + /** + * **Provide argument completion candidates** + * + * Override when command-specific completion is needed. + */ + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + (void)context; + (void)engine; + (void)out; + } + }; +} diff --git a/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.cpp b/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.cpp new file mode 100644 index 000000000..99c1455e0 --- /dev/null +++ b/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.cpp @@ -0,0 +1,171 @@ +#include "stdafx.h" + +#include "CliCommandBanIp.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\NetworkUtils.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\ServerLogManager.h" +#include "..\..\..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\..\..\Minecraft.Client\PlayerConnection.h" +#include "..\..\..\..\Minecraft.Client\PlayerList.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" +#include "..\..\..\..\Minecraft.World\Connection.h" +#include "..\..\..\..\Minecraft.World\DisconnectPacket.h" + +namespace ServerRuntime +{ + namespace + { + // The dedicated server keeps the accepted remote IP in ServerLogManager, keyed by connection smallId. + // It's a bit strange from a responsibility standpoint, so we'll need to implement it separately. + static bool TryGetPlayerRemoteIp(const std::shared_ptr &player, std::string *outIp) + { + if (outIp == nullptr || player == nullptr || player->connection == nullptr || player->connection->connection == nullptr || player->connection->connection->getSocket() == nullptr) + { + return false; + } + + const unsigned char smallId = player->connection->connection->getSocket()->getSmallId(); + if (smallId == 0) + { + return false; + } + + return ServerRuntime::ServerLogManager::TryGetConnectionRemoteIp(smallId, outIp); + } + + // After persisting the ban, walk a snapshot of current players so every matching session is removed. + static int DisconnectPlayersByRemoteIp(const std::string &ip) + { + auto *server = MinecraftServer::getInstance(); + if (server == nullptr || server->getPlayers() == nullptr) + { + return 0; + } + + const std::string normalizedIp = NetworkUtils::NormalizeIpToken(ip); + const std::vector> playerSnapshot = server->getPlayers()->players; + int disconnectedCount = 0; + for (const auto &player : playerSnapshot) + { + std::string playerIp; + if (!TryGetPlayerRemoteIp(player, &playerIp)) + { + continue; + } + + if (NetworkUtils::NormalizeIpToken(playerIp) == normalizedIp) + { + if (player != nullptr && player->connection != nullptr) + { + player->connection->disconnect(DisconnectPacket::eDisconnect_Banned); + ++disconnectedCount; + } + } + } + + return disconnectedCount; + } + } + + const char *CliCommandBanIp::Name() const + { + return "ban-ip"; + } + + const char *CliCommandBanIp::Usage() const + { + return "ban-ip [reason ...]"; + } + + const char *CliCommandBanIp::Description() const + { + return "Ban an IP address or a player's current IP."; + } + + /** + * Resolves either a literal IP or an online player's current IP, persists the ban, and disconnects every matching connection + * IPまたは接続中プレイヤーの現在IPをBANし一致する接続を切断する + */ + bool CliCommandBanIp::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 2) + { + engine->LogWarn("Usage: ban-ip [reason ...]"); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + const std::string targetToken = line.tokens[1]; + std::string remoteIp; + // Match Java Edition behavior by accepting either a literal IP or an online player name. + const auto targetPlayer = engine->FindPlayerByNameUtf8(targetToken); + if (targetPlayer != nullptr) + { + if (!TryGetPlayerRemoteIp(targetPlayer, &remoteIp)) + { + engine->LogWarn("Cannot ban that player's IP because no current remote IP is available."); + return false; + } + } + else if (NetworkUtils::IsIpLiteral(targetToken)) + { + remoteIp = StringUtils::TrimAscii(targetToken); + } + else + { + engine->LogWarn("Unknown player or invalid IP address: " + targetToken); + return false; + } + + // Refuse duplicate bans so operators get immediate feedback instead of rewriting the same entry. + if (ServerRuntime::Access::IsIpBanned(remoteIp)) + { + engine->LogWarn("That IP address is already banned."); + return false; + } + + ServerRuntime::Access::BanMetadata metadata = ServerRuntime::Access::BanManager::BuildDefaultMetadata("Console"); + metadata.reason = StringUtils::JoinTokens(line.tokens, 2); + if (metadata.reason.empty()) + { + metadata.reason = "Banned by an operator."; + } + + // Publish the ban before disconnecting players so reconnect attempts are rejected immediately. + if (!ServerRuntime::Access::AddIpBan(remoteIp, metadata)) + { + engine->LogError("Failed to write IP ban."); + return false; + } + + const int disconnectedCount = DisconnectPlayersByRemoteIp(remoteIp); + // Report the resolved IP rather than the original token so player-name targets are explicit in the console. + engine->LogInfo("Banned IP address " + remoteIp + "."); + if (disconnectedCount > 0) + { + engine->LogInfo("Disconnected " + std::to_string(disconnectedCount) + " player(s) with that IP."); + } + return true; + } + + /** + * Suggests online player names for the player-target form of the Java Edition command + * プレイヤー名指定時の補完候補を返す + */ + void CliCommandBanIp::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} + diff --git a/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.h b/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.h new file mode 100644 index 000000000..1c116fa68 --- /dev/null +++ b/Minecraft.Server/Console/commands/ban-ip/CliCommandBanIp.h @@ -0,0 +1,19 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + /** + * Applies a dedicated-server IP ban using Java Edition style syntax and Access-backed persistence + */ + class CliCommandBanIp : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const; + }; +} diff --git a/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.cpp b/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.cpp new file mode 100644 index 000000000..146416172 --- /dev/null +++ b/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.cpp @@ -0,0 +1,136 @@ +#include "stdafx.h" + +#include "CliCommandBanList.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\StringUtils.h" + +#include + +namespace ServerRuntime +{ + namespace + { + static void AppendUniqueText(const std::string &text, std::vector *out) + { + if (out == nullptr || text.empty()) + { + return; + } + + if (std::find(out->begin(), out->end(), text) == out->end()) + { + out->push_back(text); + } + } + + static bool CompareLowerAscii(const std::string &left, const std::string &right) + { + return StringUtils::ToLowerAscii(left) < StringUtils::ToLowerAscii(right); + } + + static bool LogBannedPlayers(ServerCliEngine *engine) + { + std::vector entries; + if (!ServerRuntime::Access::SnapshotBannedPlayers(&entries)) + { + engine->LogError("Failed to read banned players."); + return false; + } + + std::vector names; + for (const auto &entry : entries) + { + AppendUniqueText(entry.name, &names); + } + std::sort(names.begin(), names.end(), CompareLowerAscii); + + engine->LogInfo("There are " + std::to_string(names.size()) + " banned player(s)."); + for (const auto &name : names) + { + engine->LogInfo(" " + name); + } + return true; + } + + static bool LogBannedIps(ServerCliEngine *engine) + { + std::vector entries; + if (!ServerRuntime::Access::SnapshotBannedIps(&entries)) + { + engine->LogError("Failed to read banned IPs."); + return false; + } + + std::vector ips; + for (const auto &entry : entries) + { + AppendUniqueText(entry.ip, &ips); + } + std::sort(ips.begin(), ips.end(), CompareLowerAscii); + + engine->LogInfo("There are " + std::to_string(ips.size()) + " banned IP(s)."); + for (const auto &ip : ips) + { + engine->LogInfo(" " + ip); + } + return true; + } + + static bool LogAllBans(ServerCliEngine *engine) + { + if (!LogBannedPlayers(engine)) + { + return false; + } + + // Always print the IP snapshot as well so ban-ip entries are visible from the same command output. + return LogBannedIps(engine); + } + } + + const char *CliCommandBanList::Name() const + { + return "banlist"; + } + + const char *CliCommandBanList::Usage() const + { + return "banlist"; + } + + const char *CliCommandBanList::Description() const + { + return "List all banned players and IPs."; + } + + /** + * Reads the current Access snapshots and always prints both banned players and banned IPs + * Access の一覧を読みプレイヤーBANとIP BANをまとめて表示する + */ + bool CliCommandBanList::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() > 1) + { + engine->LogWarn("Usage: banlist"); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + return LogAllBans(engine); + } + + void CliCommandBanList::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + (void)context; + (void)engine; + (void)out; + } +} + diff --git a/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.h b/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.h new file mode 100644 index 000000000..1db32bc1d --- /dev/null +++ b/Minecraft.Server/Console/commands/ban-list/CliCommandBanList.h @@ -0,0 +1,23 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + /** + * **Ban List Command** + * + * Lists dedicated-server player bans and IP bans in a single command output + * 専用サーバーのプレイヤーBANとIP BANをまとめて表示する + */ + class CliCommandBanList : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const; + }; +} + diff --git a/Minecraft.Server/Console/commands/ban/CliCommandBan.cpp b/Minecraft.Server/Console/commands/ban/CliCommandBan.cpp new file mode 100644 index 000000000..f9855c0cb --- /dev/null +++ b/Minecraft.Server/Console/commands/ban/CliCommandBan.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" + +#include "CliCommandBan.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\..\Minecraft.Client\PlayerConnection.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" +#include "..\..\..\..\Minecraft.World\DisconnectPacket.h" + +#include + +namespace ServerRuntime +{ + namespace + { + static void AppendUniqueXuid(PlayerUID xuid, std::vector *out) + { + if (out == nullptr || xuid == INVALID_XUID) + { + return; + } + + if (std::find(out->begin(), out->end(), xuid) == out->end()) + { + out->push_back(xuid); + } + } + + static void CollectPlayerBanXuids(const std::shared_ptr &player, std::vector *out) + { + if (player == nullptr || out == nullptr) + { + return; + } + + // Keep both identity variants because the dedicated server checks login and online XUIDs separately. + AppendUniqueXuid(player->getXuid(), out); + AppendUniqueXuid(player->getOnlineXuid(), out); + } + } + + const char *CliCommandBan::Name() const + { + return "ban"; + } + + const char *CliCommandBan::Usage() const + { + return "ban [reason ...]"; + } + + const char *CliCommandBan::Description() const + { + return "Ban an online player."; + } + + /** + * Resolves the live player, writes one or more Access ban entries, and disconnects the target with the banned reason + * 対象プレイヤーを解決してBANを保存し切断する + */ + bool CliCommandBan::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 2) + { + engine->LogWarn("Usage: ban [reason ...]"); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + const auto target = engine->FindPlayerByNameUtf8(line.tokens[1]); + if (target == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[1] + " (this server build can only ban players that are currently online)."); + return false; + } + + std::vector xuids; + CollectPlayerBanXuids(target, &xuids); + if (xuids.empty()) + { + engine->LogWarn("Cannot ban that player because no valid XUID is available."); + return false; + } + + const bool hasUnbannedIdentity = std::any_of( + xuids.begin(), + xuids.end(), + [](PlayerUID xuid) { return !ServerRuntime::Access::IsPlayerBanned(xuid); }); + if (!hasUnbannedIdentity) + { + engine->LogWarn("That player is already banned."); + return false; + } + + ServerRuntime::Access::BanMetadata metadata = ServerRuntime::Access::BanManager::BuildDefaultMetadata("Console"); + metadata.reason = StringUtils::JoinTokens(line.tokens, 2); + if (metadata.reason.empty()) + { + metadata.reason = "Banned by an operator."; + } + + const std::string playerName = StringUtils::WideToUtf8(target->getName()); + for (const auto xuid : xuids) + { + if (ServerRuntime::Access::IsPlayerBanned(xuid)) + { + continue; + } + + if (!ServerRuntime::Access::AddPlayerBan(xuid, playerName, metadata)) + { + engine->LogError("Failed to write player ban."); + return false; + } + } + + if (target->connection != nullptr) + { + target->connection->disconnect(DisconnectPacket::eDisconnect_Banned); + } + + engine->LogInfo("Banned player " + playerName + "."); + return true; + } + + /** + * Suggests currently connected player names for the Java-style player argument + * プレイヤー引数の補完候補を返す + */ + void CliCommandBan::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} + diff --git a/Minecraft.Server/Console/commands/ban/CliCommandBan.h b/Minecraft.Server/Console/commands/ban/CliCommandBan.h new file mode 100644 index 000000000..8605474c6 --- /dev/null +++ b/Minecraft.Server/Console/commands/ban/CliCommandBan.h @@ -0,0 +1,20 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + /** + * Applies a dedicated-server player ban using Java Edition style syntax and Access-backed persistence + * Java Edition 風の ban コマンドで永続プレイヤーBANを行う + */ + class CliCommandBan : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const; + }; +} diff --git a/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.cpp b/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.cpp new file mode 100644 index 000000000..ee0e35a20 --- /dev/null +++ b/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.cpp @@ -0,0 +1,117 @@ +#include "stdafx.h" + +#include "CliCommandDefaultGamemode.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\..\..\Minecraft.Client\PlayerList.h" +#include "..\..\..\..\Minecraft.Client\ServerLevel.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" +#include "..\..\..\..\Minecraft.World\net.minecraft.world.level.storage.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kDefaultGamemodeUsage = "defaultgamemode "; + + static std::string ModeLabel(GameType *mode) + { + if (mode == GameType::SURVIVAL) + { + return "survival"; + } + if (mode == GameType::CREATIVE) + { + return "creative"; + } + if (mode == GameType::ADVENTURE) + { + return "adventure"; + } + + return std::to_string(mode != nullptr ? mode->getId() : -1); + } + } + + const char *CliCommandDefaultGamemode::Name() const + { + return "defaultgamemode"; + } + + const char *CliCommandDefaultGamemode::Usage() const + { + return kDefaultGamemodeUsage; + } + + const char *CliCommandDefaultGamemode::Description() const + { + return "Set the default game mode (server-side implementation)."; + } + + bool CliCommandDefaultGamemode::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 2) + { + engine->LogWarn(std::string("Usage: ") + kDefaultGamemodeUsage); + return false; + } + + GameType *mode = engine->ParseGamemode(line.tokens[1]); + if (mode == nullptr) + { + engine->LogWarn("Unknown gamemode: " + line.tokens[1]); + return false; + } + + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == nullptr) + { + engine->LogWarn("MinecraftServer instance is not available."); + return false; + } + + PlayerList *players = server->getPlayers(); + if (players == nullptr) + { + engine->LogWarn("Player list is not available."); + return false; + } + + players->setOverrideGameMode(mode); + + for (unsigned int i = 0; i < server->levels.length; ++i) + { + ServerLevel *level = server->levels[i]; + if (level != nullptr && level->getLevelData() != nullptr) + { + level->getLevelData()->setGameType(mode); + } + } + + if (server->getForceGameType()) + { + for (size_t i = 0; i < players->players.size(); ++i) + { + std::shared_ptr player = players->players[i]; + if (player != nullptr) + { + player->setGameMode(mode); + player->fallDistance = 0.0f; + } + } + } + + engine->LogInfo("Default gamemode set to " + ModeLabel(mode) + "."); + return true; + } + + void CliCommandDefaultGamemode::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestGamemodes(context.prefix, context.linePrefix, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.h b/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.h new file mode 100644 index 000000000..5cc17b34d --- /dev/null +++ b/Minecraft.Server/Console/commands/defaultgamemode/CliCommandDefaultGamemode.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandDefaultGamemode : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.cpp b/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.cpp new file mode 100644 index 000000000..70d4d7d65 --- /dev/null +++ b/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.cpp @@ -0,0 +1,87 @@ +#include "stdafx.h" + +#include "CliCommandEnchant.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\CommandParsing.h" +#include "..\..\..\..\Minecraft.World\GameCommandPacket.h" +#include "..\..\..\..\Minecraft.World\EnchantItemCommand.h" +#include "..\..\..\..\Minecraft.World\net.minecraft.world.entity.player.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kEnchantUsage = "enchant [level]"; + } + + const char *CliCommandEnchant::Name() const + { + return "enchant"; + } + + const char *CliCommandEnchant::Usage() const + { + return kEnchantUsage; + } + + const char *CliCommandEnchant::Description() const + { + return "Enchant held item via Minecraft.World command dispatcher."; + } + + bool CliCommandEnchant::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 3 || line.tokens.size() > 4) + { + engine->LogWarn(std::string("Usage: ") + kEnchantUsage); + return false; + } + + std::shared_ptr target = engine->FindPlayerByNameUtf8(line.tokens[1]); + if (target == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[1]); + return false; + } + + int enchantmentId = 0; + int enchantmentLevel = 1; + if (!CommandParsing::TryParseInt(line.tokens[2], &enchantmentId)) + { + engine->LogWarn("Invalid enchantment id: " + line.tokens[2]); + return false; + } + if (line.tokens.size() >= 4 && !CommandParsing::TryParseInt(line.tokens[3], &enchantmentLevel)) + { + engine->LogWarn("Invalid enchantment level: " + line.tokens[3]); + return false; + } + + std::shared_ptr player = std::dynamic_pointer_cast(target); + if (player == nullptr) + { + engine->LogWarn("Cannot resolve target player entity."); + return false; + } + + std::shared_ptr packet = EnchantItemCommand::preparePacket(player, enchantmentId, enchantmentLevel); + if (packet == nullptr) + { + engine->LogError("Failed to build enchant command packet."); + return false; + } + + return engine->DispatchWorldCommand(packet->command, packet->data); + } + + void CliCommandEnchant::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.h b/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.h new file mode 100644 index 000000000..66e330bd0 --- /dev/null +++ b/Minecraft.Server/Console/commands/enchant/CliCommandEnchant.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandEnchant : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/experience/CliCommandExperience.cpp b/Minecraft.Server/Console/commands/experience/CliCommandExperience.cpp new file mode 100644 index 000000000..77df99ae3 --- /dev/null +++ b/Minecraft.Server/Console/commands/experience/CliCommandExperience.cpp @@ -0,0 +1,184 @@ +#include "stdafx.h" + +#include "CliCommandExperience.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\CommandParsing.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\..\..\Minecraft.Client\PlayerList.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +#include + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kExperienceUsage = "xp [L] [player]"; + constexpr const char *kExperienceUsageWithPlayer = "xp [L] "; + + struct ExperienceAmount + { + int amount = 0; + bool levels = false; + bool take = false; + }; + + static bool TryParseExperienceAmount(const std::string &token, ExperienceAmount *outValue) + { + if (outValue == nullptr || token.empty()) + { + return false; + } + + ExperienceAmount parsed; + std::string numericToken = token; + const char suffix = token[token.size() - 1]; + if (suffix == 'l' || suffix == 'L') + { + parsed.levels = true; + numericToken = token.substr(0, token.size() - 1); + if (numericToken.empty()) + { + return false; + } + } + + int signedAmount = 0; + if (!CommandParsing::TryParseInt(numericToken, &signedAmount)) + { + return false; + } + if (signedAmount == (std::numeric_limits::min)()) + { + return false; + } + + parsed.take = signedAmount < 0; + parsed.amount = parsed.take ? -signedAmount : signedAmount; + *outValue = parsed; + return true; + } + + static std::shared_ptr ResolveTargetPlayer(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() >= 3) + { + return engine->FindPlayerByNameUtf8(line.tokens[2]); + } + + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == nullptr || server->getPlayers() == nullptr) + { + return nullptr; + } + + PlayerList *players = server->getPlayers(); + if (players->players.size() == 1 && players->players[0] != nullptr) + { + return players->players[0]; + } + + return nullptr; + } + } + + const char *CliCommandExperience::Name() const + { + return "xp"; + } + + std::vector CliCommandExperience::Aliases() const + { + return { "experience" }; + } + + const char *CliCommandExperience::Usage() const + { + return kExperienceUsage; + } + + const char *CliCommandExperience::Description() const + { + return "Grant or remove experience (server-side implementation)."; + } + + bool CliCommandExperience::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 2 || line.tokens.size() > 3) + { + engine->LogWarn(std::string("Usage: ") + kExperienceUsage); + return false; + } + + ExperienceAmount amount; + if (!TryParseExperienceAmount(line.tokens[1], &amount)) + { + engine->LogWarn(std::string("Usage: ") + kExperienceUsage); + return false; + } + + std::shared_ptr target = ResolveTargetPlayer(line, engine); + if (target == nullptr) + { + if (line.tokens.size() >= 3) + { + engine->LogWarn("Unknown player: " + line.tokens[2]); + } + else + { + engine->LogWarn(std::string("Usage: ") + kExperienceUsageWithPlayer); + } + return false; + } + + if (amount.levels) + { + target->giveExperienceLevels(amount.take ? -amount.amount : amount.amount); + if (amount.take) + { + engine->LogInfo("Removed " + std::to_string(amount.amount) + " level(s) from " + StringUtils::WideToUtf8(target->getName()) + "."); + } + else + { + engine->LogInfo("Added " + std::to_string(amount.amount) + " level(s) to " + StringUtils::WideToUtf8(target->getName()) + "."); + } + return true; + } + + if (amount.take) + { + engine->LogWarn("Removing raw experience points is not supported. Use negative levels (example: xp -5L )."); + return false; + } + + target->increaseXp(amount.amount); + engine->LogInfo("Added " + std::to_string(amount.amount) + " experience points to " + StringUtils::WideToUtf8(target->getName()) + "."); + return true; + } + + void CliCommandExperience::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + if (StringUtils::StartsWithIgnoreCase("10", context.prefix)) + { + out->push_back(context.linePrefix + "10"); + } + if (StringUtils::StartsWithIgnoreCase("10L", context.prefix)) + { + out->push_back(context.linePrefix + "10L"); + } + if (StringUtils::StartsWithIgnoreCase("-5L", context.prefix)) + { + out->push_back(context.linePrefix + "-5L"); + } + } + else if (context.currentTokenIndex == 2) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/experience/CliCommandExperience.h b/Minecraft.Server/Console/commands/experience/CliCommandExperience.h new file mode 100644 index 000000000..3fddb2188 --- /dev/null +++ b/Minecraft.Server/Console/commands/experience/CliCommandExperience.h @@ -0,0 +1,17 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandExperience : public IServerCliCommand + { + public: + const char *Name() const override; + std::vector Aliases() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.cpp b/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.cpp new file mode 100644 index 000000000..f41660e6c --- /dev/null +++ b/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.cpp @@ -0,0 +1,109 @@ +#include "stdafx.h" + +#include "CliCommandGamemode.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\..\..\Minecraft.Client\PlayerList.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kGamemodeUsage = "gamemode [player]"; + constexpr const char *kGamemodeUsageWithPlayer = "gamemode "; + } + + const char *CliCommandGamemode::Name() const + { + return "gamemode"; + } + + std::vector CliCommandGamemode::Aliases() const + { + return { "gm" }; + } + + const char *CliCommandGamemode::Usage() const + { + return kGamemodeUsage; + } + + const char *CliCommandGamemode::Description() const + { + return "Set a player's game mode."; + } + + bool CliCommandGamemode::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 2 || line.tokens.size() > 3) + { + engine->LogWarn(std::string("Usage: ") + kGamemodeUsage); + return false; + } + + GameType *mode = engine->ParseGamemode(line.tokens[1]); + if (mode == nullptr) + { + engine->LogWarn("Unknown gamemode: " + line.tokens[1]); + return false; + } + + std::shared_ptr target = nullptr; + if (line.tokens.size() >= 3) + { + target = engine->FindPlayerByNameUtf8(line.tokens[2]); + if (target == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[2]); + return false; + } + } + else + { + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == nullptr || server->getPlayers() == nullptr) + { + engine->LogWarn("Player list is not available."); + return false; + } + + PlayerList *players = server->getPlayers(); + if (players->players.size() != 1 || players->players[0] == nullptr) + { + engine->LogWarn(std::string("Usage: ") + kGamemodeUsageWithPlayer); + return false; + } + target = players->players[0]; + } + + target->setGameMode(mode); + target->fallDistance = 0.0f; + + if (line.tokens.size() >= 3) + { + engine->LogInfo("Set " + line.tokens[2] + " gamemode to " + line.tokens[1] + "."); + } + else + { + engine->LogInfo("Set gamemode to " + line.tokens[1] + "."); + } + return true; + } + + void CliCommandGamemode::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestGamemodes(context.prefix, context.linePrefix, out); + } + else if (context.currentTokenIndex == 2) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} + + diff --git a/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.h b/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.h new file mode 100644 index 000000000..527bb1f9e --- /dev/null +++ b/Minecraft.Server/Console/commands/gamemode/CliCommandGamemode.h @@ -0,0 +1,18 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandGamemode : public IServerCliCommand + { + public: + const char *Name() const override; + std::vector Aliases() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} + diff --git a/Minecraft.Server/Console/commands/give/CliCommandGive.cpp b/Minecraft.Server/Console/commands/give/CliCommandGive.cpp new file mode 100644 index 000000000..20c094972 --- /dev/null +++ b/Minecraft.Server/Console/commands/give/CliCommandGive.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" + +#include "CliCommandGive.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\CommandParsing.h" +#include "..\..\..\..\Minecraft.World\GameCommandPacket.h" +#include "..\..\..\..\Minecraft.World\GiveItemCommand.h" +#include "..\..\..\..\Minecraft.World\net.minecraft.world.entity.player.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kGiveUsage = "give [amount] [aux]"; + } + + const char *CliCommandGive::Name() const + { + return "give"; + } + + const char *CliCommandGive::Usage() const + { + return kGiveUsage; + } + + const char *CliCommandGive::Description() const + { + return "Give an item via Minecraft.World command dispatcher."; + } + + bool CliCommandGive::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 3 || line.tokens.size() > 5) + { + engine->LogWarn(std::string("Usage: ") + kGiveUsage); + return false; + } + + std::shared_ptr target = engine->FindPlayerByNameUtf8(line.tokens[1]); + if (target == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[1]); + return false; + } + + int itemId = 0; + int amount = 1; + int aux = 0; + if (!CommandParsing::TryParseInt(line.tokens[2], &itemId)) + { + engine->LogWarn("Invalid item id: " + line.tokens[2]); + return false; + } + if (itemId <= 0) + { + engine->LogWarn("Item id must be greater than 0."); + return false; + } + if (line.tokens.size() >= 4 && !CommandParsing::TryParseInt(line.tokens[3], &amount)) + { + engine->LogWarn("Invalid amount: " + line.tokens[3]); + return false; + } + if (line.tokens.size() >= 5 && !CommandParsing::TryParseInt(line.tokens[4], &aux)) + { + engine->LogWarn("Invalid aux value: " + line.tokens[4]); + return false; + } + if (amount <= 0) + { + engine->LogWarn("Amount must be greater than 0."); + return false; + } + + std::shared_ptr player = std::dynamic_pointer_cast(target); + if (player == nullptr) + { + engine->LogWarn("Cannot resolve target player entity."); + return false; + } + + std::shared_ptr packet = GiveItemCommand::preparePacket(player, itemId, amount, aux); + if (packet == nullptr) + { + engine->LogError("Failed to build give command packet."); + return false; + } + + return engine->DispatchWorldCommand(packet->command, packet->data); + } + + void CliCommandGive::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/give/CliCommandGive.h b/Minecraft.Server/Console/commands/give/CliCommandGive.h new file mode 100644 index 000000000..7c21d997c --- /dev/null +++ b/Minecraft.Server/Console/commands/give/CliCommandGive.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandGive : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/help/CliCommandHelp.cpp b/Minecraft.Server/Console/commands/help/CliCommandHelp.cpp new file mode 100644 index 000000000..d4106a9c7 --- /dev/null +++ b/Minecraft.Server/Console/commands/help/CliCommandHelp.cpp @@ -0,0 +1,46 @@ +#include "stdafx.h" + +#include "CliCommandHelp.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliRegistry.h" + +namespace ServerRuntime +{ + const char *CliCommandHelp::Name() const + { + return "help"; + } + + std::vector CliCommandHelp::Aliases() const + { + return { "?" }; + } + + const char *CliCommandHelp::Usage() const + { + return "help"; + } + + const char *CliCommandHelp::Description() const + { + return "Show available server console commands."; + } + + bool CliCommandHelp::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + (void)line; + const std::vector> &commands = engine->Registry().Commands(); + engine->LogInfo("Available commands:"); + for (size_t i = 0; i < commands.size(); ++i) + { + std::string row = " "; + row += commands[i]->Usage(); + row += " - "; + row += commands[i]->Description(); + engine->LogInfo(row); + } + return true; + } +} + diff --git a/Minecraft.Server/Console/commands/help/CliCommandHelp.h b/Minecraft.Server/Console/commands/help/CliCommandHelp.h new file mode 100644 index 000000000..3612442f4 --- /dev/null +++ b/Minecraft.Server/Console/commands/help/CliCommandHelp.h @@ -0,0 +1,17 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandHelp : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual std::vector Aliases() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + }; +} + diff --git a/Minecraft.Server/Console/commands/kill/CliCommandKill.cpp b/Minecraft.Server/Console/commands/kill/CliCommandKill.cpp new file mode 100644 index 000000000..04b2c4191 --- /dev/null +++ b/Minecraft.Server/Console/commands/kill/CliCommandKill.cpp @@ -0,0 +1,64 @@ +#include "stdafx.h" + +#include "CliCommandKill.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\..\Minecraft.World\CommandSender.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kKillUsage = "kill "; + } + + const char *CliCommandKill::Name() const + { + return "kill"; + } + + const char *CliCommandKill::Usage() const + { + return kKillUsage; + } + + const char *CliCommandKill::Description() const + { + return "Kill a player via Minecraft.World command dispatcher."; + } + + bool CliCommandKill::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 2) + { + engine->LogWarn(std::string("Usage: ") + kKillUsage); + return false; + } + + std::shared_ptr target = engine->FindPlayerByNameUtf8(line.tokens[1]); + if (target == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[1]); + return false; + } + + std::shared_ptr sender = std::dynamic_pointer_cast(target); + if (sender == nullptr) + { + engine->LogWarn("Cannot resolve target command sender."); + return false; + } + + return engine->DispatchWorldCommand(eGameCommand_Kill, byteArray(), sender); + } + + void CliCommandKill::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/kill/CliCommandKill.h b/Minecraft.Server/Console/commands/kill/CliCommandKill.h new file mode 100644 index 000000000..e558fac0c --- /dev/null +++ b/Minecraft.Server/Console/commands/kill/CliCommandKill.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandKill : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/list/CliCommandList.cpp b/Minecraft.Server/Console/commands/list/CliCommandList.cpp new file mode 100644 index 000000000..a9c5a2127 --- /dev/null +++ b/Minecraft.Server/Console/commands/list/CliCommandList.cpp @@ -0,0 +1,49 @@ +#include "stdafx.h" + +#include "CliCommandList.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\..\Minecraft.Client\MinecraftServer.h" +#include "..\..\..\..\Minecraft.Client\PlayerList.h" + +namespace ServerRuntime +{ + const char *CliCommandList::Name() const + { + return "list"; + } + + const char *CliCommandList::Usage() const + { + return "list"; + } + + const char *CliCommandList::Description() const + { + return "List connected players."; + } + + bool CliCommandList::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + (void)line; + MinecraftServer *server = MinecraftServer::getInstance(); + if (server == NULL || server->getPlayers() == NULL) + { + engine->LogWarn("Player list is not available."); + return false; + } + + PlayerList *players = server->getPlayers(); + std::string names = StringUtils::WideToUtf8(players->getPlayerNames()); + if (names.empty()) + { + names = "(none)"; + } + + engine->LogInfo("Players (" + std::to_string(players->getPlayerCount()) + "): " + names); + return true; + } +} + + diff --git a/Minecraft.Server/Console/commands/list/CliCommandList.h b/Minecraft.Server/Console/commands/list/CliCommandList.h new file mode 100644 index 000000000..ad26dcbc2 --- /dev/null +++ b/Minecraft.Server/Console/commands/list/CliCommandList.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandList : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + }; +} + diff --git a/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.cpp b/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.cpp new file mode 100644 index 000000000..3517dbd87 --- /dev/null +++ b/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.cpp @@ -0,0 +1,98 @@ +#include "stdafx.h" + +#include "CliCommandPardonIp.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\NetworkUtils.h" +#include "..\..\..\Common\StringUtils.h" + +namespace ServerRuntime +{ + const char *CliCommandPardonIp::Name() const + { + return "pardon-ip"; + } + + const char *CliCommandPardonIp::Usage() const + { + return "pardon-ip
"; + } + + const char *CliCommandPardonIp::Description() const + { + return "Remove an IP ban."; + } + + /** + * Validates the literal IP argument and removes the matching Access IP ban entry + * リテラルIPを検証して一致するIP BANを解除する + */ + bool CliCommandPardonIp::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 2) + { + engine->LogWarn("Usage: pardon-ip
"); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + // Java Edition pardon-ip only operates on a literal address, so do not resolve player names here. + const std::string ip = StringUtils::TrimAscii(line.tokens[1]); + if (!NetworkUtils::IsIpLiteral(ip)) + { + engine->LogWarn("Invalid IP address: " + line.tokens[1]); + return false; + } + // Distinguish invalid input from a valid but currently unbanned address for clearer operator feedback. + if (!ServerRuntime::Access::IsIpBanned(ip)) + { + engine->LogWarn("That IP address is not banned."); + return false; + } + if (!ServerRuntime::Access::RemoveIpBan(ip)) + { + engine->LogError("Failed to remove IP ban."); + return false; + } + + engine->LogInfo("Unbanned IP address " + ip + "."); + return true; + } + + /** + * Suggests currently banned IP addresses for the Java Edition literal-IP argument + * BAN済みIPの補完候補を返す + */ + void CliCommandPardonIp::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + (void)engine; + // Complete from the persisted IP-ban snapshot because this command only accepts already-banned literals. + if (context.currentTokenIndex != 1 || out == nullptr) + { + return; + } + + std::vector entries; + if (!ServerRuntime::Access::SnapshotBannedIps(&entries)) + { + return; + } + + // Reuse the normalized prefix match used by other commands so completion stays case-insensitive. + for (const auto &entry : entries) + { + const std::string &candidate = entry.ip; + if (StringUtils::StartsWithIgnoreCase(candidate, context.prefix)) + { + out->push_back(context.linePrefix + candidate); + } + } + } +} + diff --git a/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.h b/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.h new file mode 100644 index 000000000..96f4c7fc7 --- /dev/null +++ b/Minecraft.Server/Console/commands/pardon-ip/CliCommandPardonIp.h @@ -0,0 +1,19 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + /** + * Removes a dedicated-server IP ban using Java Edition style syntax and Access-backed persistence + */ + class CliCommandPardonIp : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const; + }; +} diff --git a/Minecraft.Server/Console/commands/pardon/CliCommandPardon.cpp b/Minecraft.Server/Console/commands/pardon/CliCommandPardon.cpp new file mode 100644 index 000000000..d1e995e90 --- /dev/null +++ b/Minecraft.Server/Console/commands/pardon/CliCommandPardon.cpp @@ -0,0 +1,173 @@ +#include "stdafx.h" + +#include "CliCommandPardon.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" + +#include + +namespace ServerRuntime +{ + namespace + { + static void AppendUniqueText(const std::string &text, std::vector *out) + { + if (out == nullptr || text.empty()) + { + return; + } + + if (std::find(out->begin(), out->end(), text) == out->end()) + { + out->push_back(text); + } + } + + static void AppendUniqueXuid(PlayerUID xuid, std::vector *out) + { + if (out == nullptr || xuid == INVALID_XUID) + { + return; + } + + if (std::find(out->begin(), out->end(), xuid) == out->end()) + { + out->push_back(xuid); + } + } + } + + const char *CliCommandPardon::Name() const + { + return "pardon"; + } + + const char *CliCommandPardon::Usage() const + { + return "pardon "; + } + + const char *CliCommandPardon::Description() const + { + return "Remove a player ban."; + } + + /** + * Removes every Access ban entry that matches the requested player name so dual-XUID entries are cleared together + * 名前に一致するBANをまとめて解除する + */ + bool CliCommandPardon::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 2) + { + engine->LogWarn("Usage: pardon "); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + std::vector xuidsToRemove; + std::vector matchedNames; + std::shared_ptr onlineTarget = engine->FindPlayerByNameUtf8(line.tokens[1]); + if (onlineTarget != nullptr) + { + if (ServerRuntime::Access::IsPlayerBanned(onlineTarget->getXuid())) + { + AppendUniqueXuid(onlineTarget->getXuid(), &xuidsToRemove); + } + if (ServerRuntime::Access::IsPlayerBanned(onlineTarget->getOnlineXuid())) + { + AppendUniqueXuid(onlineTarget->getOnlineXuid(), &xuidsToRemove); + } + } + + std::vector entries; + if (!ServerRuntime::Access::SnapshotBannedPlayers(&entries)) + { + engine->LogError("Failed to read banned players."); + return false; + } + + const std::string loweredTarget = StringUtils::ToLowerAscii(line.tokens[1]); + for (const auto &entry : entries) + { + if (StringUtils::ToLowerAscii(entry.name) == loweredTarget) + { + PlayerUID parsedXuid = INVALID_XUID; + if (ServerRuntime::Access::TryParseXuid(entry.xuid, &parsedXuid)) + { + AppendUniqueXuid(parsedXuid, &xuidsToRemove); + } + AppendUniqueText(entry.name, &matchedNames); + } + } + + if (xuidsToRemove.empty()) + { + engine->LogWarn("That player is not banned."); + return false; + } + + for (const auto xuid : xuidsToRemove) + { + if (!ServerRuntime::Access::RemovePlayerBan(xuid)) + { + engine->LogError("Failed to remove player ban."); + return false; + } + } + + std::string playerName = line.tokens[1]; + if (!matchedNames.empty()) + { + playerName = matchedNames[0]; + } + else if (onlineTarget != nullptr) + { + playerName = StringUtils::WideToUtf8(onlineTarget->getName()); + } + + engine->LogInfo("Unbanned player " + playerName + "."); + return true; + } + + /** + * Suggests currently banned player names first and then online names for convenience + * BAN済み名とオンライン名を補完候補に出す + */ + void CliCommandPardon::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex != 1 || out == nullptr) + { + return; + } + + std::vector entries; + if (ServerRuntime::Access::SnapshotBannedPlayers(&entries)) + { + std::vector names; + for (const auto &entry : entries) + { + AppendUniqueText(entry.name, &names); + } + + for (const auto &name : names) + { + if (StringUtils::StartsWithIgnoreCase(name, context.prefix)) + { + out->push_back(context.linePrefix + name); + } + } + } + + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } +} + diff --git a/Minecraft.Server/Console/commands/pardon/CliCommandPardon.h b/Minecraft.Server/Console/commands/pardon/CliCommandPardon.h new file mode 100644 index 000000000..a171d4288 --- /dev/null +++ b/Minecraft.Server/Console/commands/pardon/CliCommandPardon.h @@ -0,0 +1,19 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + /** + * Removes dedicated-server player bans using Java Edition style syntax and Access-backed persistence + */ + class CliCommandPardon : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + virtual void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const; + }; +} diff --git a/Minecraft.Server/Console/commands/stop/CliCommandStop.cpp b/Minecraft.Server/Console/commands/stop/CliCommandStop.cpp new file mode 100644 index 000000000..29e42cd9a --- /dev/null +++ b/Minecraft.Server/Console/commands/stop/CliCommandStop.cpp @@ -0,0 +1,32 @@ +#include "stdafx.h" + +#include "CliCommandStop.h" + +#include "..\..\ServerCliEngine.h" + +namespace ServerRuntime +{ + const char *CliCommandStop::Name() const + { + return "stop"; + } + + const char *CliCommandStop::Usage() const + { + return "stop"; + } + + const char *CliCommandStop::Description() const + { + return "Stop the dedicated server."; + } + + bool CliCommandStop::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + (void)line; + engine->LogInfo("Stopping server..."); + engine->RequestShutdown(); + return true; + } +} + diff --git a/Minecraft.Server/Console/commands/stop/CliCommandStop.h b/Minecraft.Server/Console/commands/stop/CliCommandStop.h new file mode 100644 index 000000000..2297c6732 --- /dev/null +++ b/Minecraft.Server/Console/commands/stop/CliCommandStop.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandStop : public IServerCliCommand + { + public: + virtual const char *Name() const; + virtual const char *Usage() const; + virtual const char *Description() const; + virtual bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine); + }; +} + diff --git a/Minecraft.Server/Console/commands/time/CliCommandTime.cpp b/Minecraft.Server/Console/commands/time/CliCommandTime.cpp new file mode 100644 index 000000000..d274993cc --- /dev/null +++ b/Minecraft.Server/Console/commands/time/CliCommandTime.cpp @@ -0,0 +1,118 @@ +#include "stdafx.h" + +#include "CliCommandTime.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\..\Minecraft.World\GameCommandPacket.h" +#include "..\..\..\..\Minecraft.World\TimeCommand.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kTimeUsage = "time "; + + static bool TryResolveNightFlag(const std::vector &tokens, bool *outNight) + { + if (outNight == nullptr) + { + return false; + } + + std::string value; + if (tokens.size() == 2) + { + value = StringUtils::ToLowerAscii(tokens[1]); + } + else if (tokens.size() == 3 && StringUtils::ToLowerAscii(tokens[1]) == "set") + { + value = StringUtils::ToLowerAscii(tokens[2]); + } + else + { + return false; + } + + if (value == "day") + { + *outNight = false; + return true; + } + if (value == "night") + { + *outNight = true; + return true; + } + + return false; + } + + static void SuggestLiteral(const char *candidate, const ServerCliCompletionContext &context, std::vector *out) + { + if (candidate == nullptr || out == nullptr) + { + return; + } + + const std::string text(candidate); + if (StringUtils::StartsWithIgnoreCase(text, context.prefix)) + { + out->push_back(context.linePrefix + text); + } + } + } + + const char *CliCommandTime::Name() const + { + return "time"; + } + + const char *CliCommandTime::Usage() const + { + return kTimeUsage; + } + + const char *CliCommandTime::Description() const + { + return "Set day or night via Minecraft.World command dispatcher."; + } + + bool CliCommandTime::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + bool night = false; + if (!TryResolveNightFlag(line.tokens, &night)) + { + engine->LogWarn(std::string("Usage: ") + kTimeUsage); + return false; + } + + std::shared_ptr packet = TimeCommand::preparePacket(night); + if (packet == nullptr) + { + engine->LogError("Failed to build time command packet."); + return false; + } + + return engine->DispatchWorldCommand(packet->command, packet->data); + } + + void CliCommandTime::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + (void)engine; + if (context.currentTokenIndex == 1) + { + SuggestLiteral("day", context, out); + SuggestLiteral("night", context, out); + SuggestLiteral("set", context, out); + } + else if (context.currentTokenIndex == 2 && + context.parsed.tokens.size() >= 2 && + StringUtils::ToLowerAscii(context.parsed.tokens[1]) == "set") + { + SuggestLiteral("day", context, out); + SuggestLiteral("night", context, out); + } + } +} diff --git a/Minecraft.Server/Console/commands/time/CliCommandTime.h b/Minecraft.Server/Console/commands/time/CliCommandTime.h new file mode 100644 index 000000000..28cf5e5a9 --- /dev/null +++ b/Minecraft.Server/Console/commands/time/CliCommandTime.h @@ -0,0 +1,16 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandTime : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} diff --git a/Minecraft.Server/Console/commands/tp/CliCommandTp.cpp b/Minecraft.Server/Console/commands/tp/CliCommandTp.cpp new file mode 100644 index 000000000..45dbb2846 --- /dev/null +++ b/Minecraft.Server/Console/commands/tp/CliCommandTp.cpp @@ -0,0 +1,82 @@ +#include "stdafx.h" + +#include "CliCommandTp.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\..\Minecraft.Client\PlayerConnection.h" +#include "..\..\..\..\Minecraft.Client\TeleportCommand.h" +#include "..\..\..\..\Minecraft.Client\ServerPlayer.h" +#include "..\..\..\..\Minecraft.World\GameCommandPacket.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kTpUsage = "tp "; + } + + const char *CliCommandTp::Name() const + { + return "tp"; + } + + std::vector CliCommandTp::Aliases() const + { + return { "teleport" }; + } + + const char *CliCommandTp::Usage() const + { + return kTpUsage; + } + + const char *CliCommandTp::Description() const + { + return "Teleport one player to another via Minecraft.World command dispatcher."; + } + + bool CliCommandTp::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 3) + { + engine->LogWarn(std::string("Usage: ") + kTpUsage); + return false; + } + + std::shared_ptr subject = engine->FindPlayerByNameUtf8(line.tokens[1]); + std::shared_ptr destination = engine->FindPlayerByNameUtf8(line.tokens[2]); + if (subject == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[1]); + return false; + } + if (destination == nullptr) + { + engine->LogWarn("Unknown player: " + line.tokens[2]); + return false; + } + if (subject->connection == nullptr) + { + engine->LogWarn("Cannot teleport because source player connection is inactive."); + return false; + } + std::shared_ptr packet = TeleportCommand::preparePacket(subject->getXuid(), destination->getXuid()); + if (packet == nullptr) + { + engine->LogError("Failed to build teleport command packet."); + return false; + } + + return engine->DispatchWorldCommand(packet->command, packet->data); + } + + void CliCommandTp::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + if (context.currentTokenIndex == 1 || context.currentTokenIndex == 2) + { + engine->SuggestPlayers(context.prefix, context.linePrefix, out); + } + } +} + diff --git a/Minecraft.Server/Console/commands/tp/CliCommandTp.h b/Minecraft.Server/Console/commands/tp/CliCommandTp.h new file mode 100644 index 000000000..6e9ffdd7f --- /dev/null +++ b/Minecraft.Server/Console/commands/tp/CliCommandTp.h @@ -0,0 +1,18 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandTp : public IServerCliCommand + { + public: + const char *Name() const override; + std::vector Aliases() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} + diff --git a/Minecraft.Server/Console/commands/weather/CliCommandWeather.cpp b/Minecraft.Server/Console/commands/weather/CliCommandWeather.cpp new file mode 100644 index 000000000..e7f019542 --- /dev/null +++ b/Minecraft.Server/Console/commands/weather/CliCommandWeather.cpp @@ -0,0 +1,49 @@ +#include "stdafx.h" + +#include "CliCommandWeather.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\..\Minecraft.World\GameCommandPacket.h" +#include "..\..\..\..\Minecraft.World\ToggleDownfallCommand.h" + +namespace ServerRuntime +{ + namespace + { + constexpr const char *kWeatherUsage = "weather"; + } + + const char *CliCommandWeather::Name() const + { + return "weather"; + } + + const char *CliCommandWeather::Usage() const + { + return kWeatherUsage; + } + + const char *CliCommandWeather::Description() const + { + return "Toggle weather via Minecraft.World command dispatcher."; + } + + bool CliCommandWeather::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() != 1) + { + engine->LogWarn(std::string("Usage: ") + kWeatherUsage); + return false; + } + + std::shared_ptr packet = ToggleDownfallCommand::preparePacket(); + if (packet == nullptr) + { + engine->LogError("Failed to build weather command packet."); + return false; + } + + return engine->DispatchWorldCommand(packet->command, packet->data); + } +} diff --git a/Minecraft.Server/Console/commands/weather/CliCommandWeather.h b/Minecraft.Server/Console/commands/weather/CliCommandWeather.h new file mode 100644 index 000000000..03498b473 --- /dev/null +++ b/Minecraft.Server/Console/commands/weather/CliCommandWeather.h @@ -0,0 +1,15 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandWeather : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + }; +} diff --git a/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.cpp b/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.cpp new file mode 100644 index 000000000..037242780 --- /dev/null +++ b/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.cpp @@ -0,0 +1,285 @@ +#include "stdafx.h" + +#include "CliCommandWhitelist.h" + +#include "..\..\ServerCliEngine.h" +#include "..\..\ServerCliParser.h" +#include "..\..\..\Access\Access.h" +#include "..\..\..\Common\StringUtils.h" +#include "..\..\..\ServerProperties.h" + +#include +#include + +namespace ServerRuntime +{ + namespace + { + static const char *kWhitelistUsage = "whitelist [...]"; + + static bool CompareWhitelistEntries(const ServerRuntime::Access::WhitelistedPlayerEntry &left, const ServerRuntime::Access::WhitelistedPlayerEntry &right) + { + const auto leftName = StringUtils::ToLowerAscii(left.name); + const auto rightName = StringUtils::ToLowerAscii(right.name); + if (leftName != rightName) + { + return leftName < rightName; + } + + return StringUtils::ToLowerAscii(left.xuid) < StringUtils::ToLowerAscii(right.xuid); + } + + static bool PersistWhitelistToggle(bool enabled) + { + auto config = LoadServerPropertiesConfig(); + config.whiteListEnabled = enabled; + return SaveServerPropertiesConfig(config); + } + + static std::string BuildWhitelistEntryRow(const ServerRuntime::Access::WhitelistedPlayerEntry &entry) + { + std::string row = " "; + row += entry.xuid; + if (!entry.name.empty()) + { + row += " - "; + row += entry.name; + } + return row; + } + + static void LogWhitelistMode(ServerCliEngine *engine) + { + engine->LogInfo(std::string("Whitelist is ") + (ServerRuntime::Access::IsWhitelistEnabled() ? "enabled." : "disabled.")); + } + + static bool LogWhitelistEntries(ServerCliEngine *engine) + { + std::vector entries; + if (!ServerRuntime::Access::SnapshotWhitelistedPlayers(&entries)) + { + engine->LogError("Failed to read whitelist entries."); + return false; + } + + std::sort(entries.begin(), entries.end(), CompareWhitelistEntries); + LogWhitelistMode(engine); + engine->LogInfo("There are " + std::to_string(entries.size()) + " whitelisted player(s)."); + for (const auto &entry : entries) + { + engine->LogInfo(BuildWhitelistEntryRow(entry)); + } + return true; + } + + static bool TryParseWhitelistXuid(const std::string &text, ServerCliEngine *engine, PlayerUID *outXuid) + { + if (ServerRuntime::Access::TryParseXuid(text, outXuid)) + { + return true; + } + + engine->LogWarn("Invalid XUID: " + text); + return false; + } + + static void SuggestLiteral(const std::string &candidate, const ServerCliCompletionContext &context, std::vector *out) + { + if (out == nullptr) + { + return; + } + + if (StringUtils::StartsWithIgnoreCase(candidate, context.prefix)) + { + out->push_back(context.linePrefix + candidate); + } + } + } + + const char *CliCommandWhitelist::Name() const + { + return "whitelist"; + } + + const char *CliCommandWhitelist::Usage() const + { + return kWhitelistUsage; + } + + const char *CliCommandWhitelist::Description() const + { + return "Manage the dedicated-server XUID whitelist."; + } + + bool CliCommandWhitelist::Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) + { + if (line.tokens.size() < 2) + { + engine->LogWarn(std::string("Usage: ") + kWhitelistUsage); + return false; + } + if (!ServerRuntime::Access::IsInitialized()) + { + engine->LogWarn("Access manager is not initialized."); + return false; + } + + const auto subcommand = StringUtils::ToLowerAscii(line.tokens[1]); + if (subcommand == "on" || subcommand == "off") + { + if (line.tokens.size() != 2) + { + engine->LogWarn("Usage: whitelist "); + return false; + } + + const bool enabled = (subcommand == "on"); + if (!PersistWhitelistToggle(enabled)) + { + engine->LogError("Failed to persist whitelist mode to server.properties."); + return false; + } + + ServerRuntime::Access::SetWhitelistEnabled(enabled); + engine->LogInfo(std::string("Whitelist ") + (enabled ? "enabled." : "disabled.")); + return true; + } + + if (subcommand == "list") + { + if (line.tokens.size() != 2) + { + engine->LogWarn("Usage: whitelist list"); + return false; + } + + return LogWhitelistEntries(engine); + } + + if (subcommand == "reload") + { + if (line.tokens.size() != 2) + { + engine->LogWarn("Usage: whitelist reload"); + return false; + } + if (!ServerRuntime::Access::ReloadWhitelist()) + { + engine->LogError("Failed to reload whitelist."); + return false; + } + + const auto config = LoadServerPropertiesConfig(); + ServerRuntime::Access::SetWhitelistEnabled(config.whiteListEnabled); + engine->LogInfo("Reloaded whitelist from disk."); + LogWhitelistMode(engine); + return true; + } + + if (subcommand == "add") + { + if (line.tokens.size() < 3) + { + engine->LogWarn("Usage: whitelist add [name ...]"); + return false; + } + + PlayerUID xuid = INVALID_XUID; + if (!TryParseWhitelistXuid(line.tokens[2], engine, &xuid)) + { + return false; + } + + if (ServerRuntime::Access::IsPlayerWhitelisted(xuid)) + { + engine->LogWarn("That XUID is already whitelisted."); + return false; + } + + const auto metadata = ServerRuntime::Access::WhitelistManager::BuildDefaultMetadata("Console"); + const auto name = StringUtils::JoinTokens(line.tokens, 3); + if (!ServerRuntime::Access::AddWhitelistedPlayer(xuid, name, metadata)) + { + engine->LogError("Failed to write whitelist entry."); + return false; + } + + std::string message = "Whitelisted XUID " + ServerRuntime::Access::FormatXuid(xuid) + "."; + if (!name.empty()) + { + message += " Name: " + name; + } + engine->LogInfo(message); + return true; + } + + if (subcommand == "remove") + { + if (line.tokens.size() != 3) + { + engine->LogWarn("Usage: whitelist remove "); + return false; + } + + PlayerUID xuid = INVALID_XUID; + if (!TryParseWhitelistXuid(line.tokens[2], engine, &xuid)) + { + return false; + } + + if (!ServerRuntime::Access::IsPlayerWhitelisted(xuid)) + { + engine->LogWarn("That XUID is not whitelisted."); + return false; + } + + if (!ServerRuntime::Access::RemoveWhitelistedPlayer(xuid)) + { + engine->LogError("Failed to remove whitelist entry."); + return false; + } + + engine->LogInfo("Removed XUID " + ServerRuntime::Access::FormatXuid(xuid) + " from the whitelist."); + return true; + } + + engine->LogWarn(std::string("Usage: ") + kWhitelistUsage); + return false; + } + + void CliCommandWhitelist::Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const + { + (void)engine; + if (out == nullptr) + { + return; + } + + if (context.currentTokenIndex == 1) + { + SuggestLiteral("on", context, out); + SuggestLiteral("off", context, out); + SuggestLiteral("list", context, out); + SuggestLiteral("add", context, out); + SuggestLiteral("remove", context, out); + SuggestLiteral("reload", context, out); + return; + } + + if (context.currentTokenIndex == 2 && context.parsed.tokens.size() >= 2 && StringUtils::ToLowerAscii(context.parsed.tokens[1]) == "remove") + { + std::vector entries; + if (!ServerRuntime::Access::SnapshotWhitelistedPlayers(&entries)) + { + return; + } + + for (const auto &entry : entries) + { + SuggestLiteral(entry.xuid, context, out); + } + } + } +} + diff --git a/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.h b/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.h new file mode 100644 index 000000000..45e21a5e6 --- /dev/null +++ b/Minecraft.Server/Console/commands/whitelist/CliCommandWhitelist.h @@ -0,0 +1,17 @@ +#pragma once + +#include "..\IServerCliCommand.h" + +namespace ServerRuntime +{ + class CliCommandWhitelist : public IServerCliCommand + { + public: + const char *Name() const override; + const char *Usage() const override; + const char *Description() const override; + bool Execute(const ServerCliParsedLine &line, ServerCliEngine *engine) override; + void Complete(const ServerCliCompletionContext &context, const ServerCliEngine *engine, std::vector *out) const override; + }; +} + diff --git a/Minecraft.Server/Minecraft.Server.vcxproj b/Minecraft.Server/Minecraft.Server.vcxproj new file mode 100644 index 000000000..be2eb80c8 --- /dev/null +++ b/Minecraft.Server/Minecraft.Server.vcxproj @@ -0,0 +1,749 @@ + + + + + Debug + x64 + + + Release + x64 + + + + {7CB40BFC-C8E4-4293-A22E-D2041348D5AF} + Win32Proj + MinecraftServer + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + $(SolutionDir)$(Platform)\Minecraft.Server\$(Configuration)\ + $(SolutionDir)$(Platform)\Minecraft.Server\$(Configuration)\obj\MinecraftServer\ + Minecraft.Server + $(OutDir) + -port 25565 -bind 0.0.0.0 -name DedicatedServer + WindowsLocalDebugger + + + $(SolutionDir)$(Platform)\Minecraft.Server\$(Configuration)\ + $(SolutionDir)$(Platform)\Minecraft.Server\$(Configuration)\obj\MinecraftServer\ + Minecraft.Server + $(OutDir) + -port 25565 -bind 0.0.0.0 -name DedicatedServer + WindowsLocalDebugger + + + + Level3 + Disabled + Use + $(OutDir)MinecraftServer.pch + MultiThreadedDebug + ProgramDatabase + Sync + true + true + _LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_DEBUG;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64;MINECRAFT_SERVER_BUILD;%(PreprocessorDefinitions) + ..\Minecraft.Client;..\Minecraft.Client\Windows64\Iggy\include;..\Minecraft.Client\Xbox\Sentient\Include;..\Minecraft.World\x64headers;..\include;$(ProjectDir)Windows64;%(AdditionalIncludeDirectories) + + + false + + + _WINDOWS64;%(PreprocessorDefinitions) + ..\Minecraft.Client;..\Minecraft.Client\Xbox;%(AdditionalIncludeDirectories) + + + Console + mainCRTStartup + true + d3d11.lib;XInput9_1_0.lib;wsock32.lib;legacy_stdio_definitions.lib;..\Minecraft.World\x64_Debug\Minecraft.World.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggy_w64.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggyperfmon_w64.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggyexpruntime_w64.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Input_d.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Storage_d.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Render_PC_d.lib;%(AdditionalDependencies) + + + powershell -ExecutionPolicy Bypass -File "$(ProjectDir)Windows64\postbuild_server.ps1" -OutDir "$(OutDir)." -ProjectRoot "$(ProjectDir).." -Configuration "$(Configuration)" + + + + + Level3 + MaxSpeed + true + true + Use + $(OutDir)MinecraftServer.pch + MultiThreaded + Sync + true + true + _LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64;MINECRAFT_SERVER_BUILD;%(PreprocessorDefinitions) + ..\Minecraft.Client;..\Minecraft.Client\Windows64\Iggy\include;..\Minecraft.Client\Xbox\Sentient\Include;..\Minecraft.World\x64headers;..\include;$(ProjectDir)Windows64;%(AdditionalIncludeDirectories) + + + false + + + _WINDOWS64;%(PreprocessorDefinitions) + ..\Minecraft.Client;..\Minecraft.Client\Xbox;%(AdditionalIncludeDirectories) + + + Console + mainCRTStartup + true + true + true + d3d11.lib;XInput9_1_0.lib;wsock32.lib;legacy_stdio_definitions.lib;..\Minecraft.World\x64_Release\Minecraft.World.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggy_w64.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggyperfmon_w64.lib;..\Minecraft.Client\Windows64\Iggy\lib\iggyexpruntime_w64.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Input.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Storage.lib;..\Minecraft.Client\Windows64\4JLibs\libs\4J_Render_PC.lib;%(AdditionalDependencies) + + + powershell -ExecutionPolicy Bypass -File "$(ProjectDir)Windows64\postbuild_server.ps1" -OutDir "$(OutDir)." -ProjectRoot "$(ProjectDir).." -Configuration "$(Configuration)" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + NotUsing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NotUsing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NotUsing + + + + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {F046C3CE-9749-4823-B32B-D9CC10B1A2C8} + false + + + + + + + + diff --git a/Minecraft.Server/Minecraft.Server.vcxproj.filters b/Minecraft.Server/Minecraft.Server.vcxproj.filters new file mode 100644 index 000000000..8cd5e26e0 --- /dev/null +++ b/Minecraft.Server/Minecraft.Server.vcxproj.filters @@ -0,0 +1,737 @@ + + + + + {A8A47C24-66C0-4912-9D34-2CBF87F1D707} + + + {39B037A0-9B57-454A-AF34-7D9164E22A0F} + + + {7C28D123-0DA3-4B17-84C0-E326F5A75740} + + + {29AB58D1-E8A9-465A-B3EA-BC5E9110A7A1} + + + {BC6FD58B-1A40-45FE-B8D9-1A087C25126D} + + + {3E4D5A41-CAB8-4A10-82B5-8B2AE2E25CB2} + + + + + Server + + + Server + + + Server + + + Server + + + Server\Console + + + Server\Console + + + Server\Console + + + Server\Console + + + Server\Common + + + Server\Vendor + + + Server + + + Server\Access + + + Server\Access + + + Server\Access + + + Server\Common + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + + + Server\Console + + + Server\Console + + + Server\Console + + + Server\Console + + + Server\Access + + + Server\Access + + + Server\Access + + + Server\Common + + + Server\Common + + + Server\Common + + + Server\Common + + + Server + + + Server + + + Server + + + Server\Vendor + + + Server + + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + Server\Console\Commands + + + + + + + + + + diff --git a/Minecraft.Server/ServerLogManager.cpp b/Minecraft.Server/ServerLogManager.cpp new file mode 100644 index 000000000..84805f7e4 --- /dev/null +++ b/Minecraft.Server/ServerLogManager.cpp @@ -0,0 +1,402 @@ +#include "stdafx.h" + +#include "ServerLogManager.h" + +#include "Common\StringUtils.h" +#include "ServerLogger.h" + +#include +#include + +extern bool g_Win64DedicatedServer; + +namespace ServerRuntime +{ + namespace ServerLogManager + { + namespace + { + /** + * **!! This information is managed solely for logging purposes, but it is questionable from a liability perspective, so it will eventually need to be separated !!** + * + * Tracks the remote IP and accepted player name associated with one `smallId` + * 1つのsmallIdに紐づく接続IPとプレイヤー名を保持する + */ + struct ConnectionLogEntry + { + std::string remoteIp; + std::string playerName; + }; + + /** + * Owns the shared connection cache used by hook points running on different threads + * 複数スレッドのhookから共有される接続キャッシュを保持する + */ + struct ServerLogState + { + std::mutex stateLock; + std::array entries; + }; + + ServerLogState g_serverLogState; + + static bool IsDedicatedServerLoggingEnabled() + { + return g_Win64DedicatedServer; + } + + static void ResetConnectionLogEntry(ConnectionLogEntry *entry) + { + if (entry == NULL) + { + return; + } + + entry->remoteIp.clear(); + entry->playerName.clear(); + } + + static std::string NormalizeRemoteIp(const char *ip) + { + if (ip == NULL || ip[0] == 0) + { + return std::string("unknown"); + } + + return std::string(ip); + } + + static std::string NormalizePlayerName(const std::wstring &playerName) + { + std::string playerNameUtf8 = StringUtils::WideToUtf8(playerName); + if (playerNameUtf8.empty()) + { + playerNameUtf8 = ""; + } + + return playerNameUtf8; + } + + // Default to the main app channel when the caller does not provide a source tag. + static const char *NormalizeClientLogSource(const char *source) + { + if (source == NULL || source[0] == 0) + { + return "app"; + } + + return source; + } + + static void EmitClientDebugLogLine(const char *source, const std::string &line) + { + if (line.empty()) + { + return; + } + + LogDebugf("client", "[%s] %s", NormalizeClientLogSource(source), line.c_str()); + } + + // Split one debug payload into individual lines so each line becomes a prompt-safe server log entry. + static void ForwardClientDebugMessage(const char *source, const char *message) + { + if (message == NULL || message[0] == 0) + { + return; + } + + const char *cursor = message; + while (*cursor != 0) + { + const char *lineStart = cursor; + while (*cursor != 0 && *cursor != '\r' && *cursor != '\n') + { + ++cursor; + } + + // Split multi-line client debug output into prompt-safe server log entries. + if (cursor > lineStart) + { + EmitClientDebugLogLine(source, std::string(lineStart, (size_t)(cursor - lineStart))); + } + + while (*cursor == '\r' || *cursor == '\n') + { + ++cursor; + } + } + } + + // Share the same formatting path for app, user, and legacy debug-spew forwards. + static void ForwardFormattedClientDebugLogV(const char *source, const char *format, va_list args) + { + if (!IsDedicatedServerLoggingEnabled() || format == NULL || format[0] == 0) + { + return; + } + + char messageBuffer[2048] = {}; + vsnprintf_s(messageBuffer, sizeof(messageBuffer), _TRUNCATE, format, args); + ForwardClientDebugMessage(source, messageBuffer); + } + + static const char *TcpRejectReasonToString(ETcpRejectReason reason) + { + switch (reason) + { + case eTcpRejectReason_BannedIp: return "banned-ip"; + case eTcpRejectReason_GameNotReady: return "game-not-ready"; + case eTcpRejectReason_ServerFull: return "server-full"; + default: return "unknown"; + } + } + + static const char *LoginRejectReasonToString(ELoginRejectReason reason) + { + switch (reason) + { + case eLoginRejectReason_BannedXuid: return "banned-xuid"; + case eLoginRejectReason_NotWhitelisted: return "not-whitelisted"; + case eLoginRejectReason_DuplicateXuid: return "duplicate-xuid"; + case eLoginRejectReason_DuplicateName: return "duplicate-name"; + default: return "unknown"; + } + } + + static const char *DisconnectReasonToString(DisconnectPacket::eDisconnectReason reason) + { + switch (reason) + { + case DisconnectPacket::eDisconnect_None: return "none"; + case DisconnectPacket::eDisconnect_Quitting: return "quitting"; + case DisconnectPacket::eDisconnect_Closed: return "closed"; + case DisconnectPacket::eDisconnect_LoginTooLong: return "login-too-long"; + case DisconnectPacket::eDisconnect_IllegalStance: return "illegal-stance"; + case DisconnectPacket::eDisconnect_IllegalPosition: return "illegal-position"; + case DisconnectPacket::eDisconnect_MovedTooQuickly: return "moved-too-quickly"; + case DisconnectPacket::eDisconnect_NoFlying: return "no-flying"; + case DisconnectPacket::eDisconnect_Kicked: return "kicked"; + case DisconnectPacket::eDisconnect_TimeOut: return "timeout"; + case DisconnectPacket::eDisconnect_Overflow: return "overflow"; + case DisconnectPacket::eDisconnect_EndOfStream: return "end-of-stream"; + case DisconnectPacket::eDisconnect_ServerFull: return "server-full"; + case DisconnectPacket::eDisconnect_OutdatedServer: return "outdated-server"; + case DisconnectPacket::eDisconnect_OutdatedClient: return "outdated-client"; + case DisconnectPacket::eDisconnect_UnexpectedPacket: return "unexpected-packet"; + case DisconnectPacket::eDisconnect_ConnectionCreationFailed: return "connection-creation-failed"; + case DisconnectPacket::eDisconnect_NoMultiplayerPrivilegesHost: return "no-multiplayer-privileges-host"; + case DisconnectPacket::eDisconnect_NoMultiplayerPrivilegesJoin: return "no-multiplayer-privileges-join"; + case DisconnectPacket::eDisconnect_NoUGC_AllLocal: return "no-ugc-all-local"; + case DisconnectPacket::eDisconnect_NoUGC_Single_Local: return "no-ugc-single-local"; + case DisconnectPacket::eDisconnect_ContentRestricted_AllLocal: return "content-restricted-all-local"; + case DisconnectPacket::eDisconnect_ContentRestricted_Single_Local: return "content-restricted-single-local"; + case DisconnectPacket::eDisconnect_NoUGC_Remote: return "no-ugc-remote"; + case DisconnectPacket::eDisconnect_NoFriendsInGame: return "no-friends-in-game"; + case DisconnectPacket::eDisconnect_Banned: return "banned"; + case DisconnectPacket::eDisconnect_NotFriendsWithHost: return "not-friends-with-host"; + case DisconnectPacket::eDisconnect_NATMismatch: return "nat-mismatch"; + default: return "unknown"; + } + } + } + + // Only forward client-side debug output while the process is running as the dedicated server. + bool ShouldForwardClientDebugLogs() + { + return IsDedicatedServerLoggingEnabled(); + } + + void ForwardClientAppDebugLogV(const char *format, va_list args) + { + ForwardFormattedClientDebugLogV("app", format, args); + } + + void ForwardClientUserDebugLogV(int user, const char *format, va_list args) + { + char source[32] = {}; + _snprintf_s(source, sizeof(source), _TRUNCATE, "app:user=%d", user); + ForwardFormattedClientDebugLogV(source, format, args); + } + + void ForwardClientDebugSpewLogV(const char *format, va_list args) + { + ForwardFormattedClientDebugLogV("debug-spew", format, args); + } + + // Clear every cached connection slot during startup so stale metadata never leaks into future logs. + void Initialize() + { + std::lock_guard stateLock(g_serverLogState.stateLock); + for (size_t index = 0; index < g_serverLogState.entries.size(); ++index) + { + ResetConnectionLogEntry(&g_serverLogState.entries[index]); + } + } + + // Reuse Initialize as the shutdown cleanup path because both operations wipe the cache. + void Shutdown() + { + Initialize(); + } + + // Log the raw socket arrival before a smallId is assigned so early rejects still have an IP in the logs. + void OnIncomingTcpConnection(const char *ip) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + const std::string remoteIp = NormalizeRemoteIp(ip); + LogInfof("network", "incoming tcp connection from %s", remoteIp.c_str()); + } + + // TCP rejects happen before connection state is cached, so log directly from the supplied remote IP. + void OnRejectedTcpConnection(const char *ip, ETcpRejectReason reason) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + const std::string remoteIp = NormalizeRemoteIp(ip); + LogWarnf("network", "rejected tcp connection from %s: reason=%s", remoteIp.c_str(), TcpRejectReasonToString(reason)); + } + + // Cache the accepted remote IP immediately so later login and disconnect logs can reuse it. + void OnAcceptedTcpConnection(unsigned char smallId, const char *ip) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + const std::string remoteIp = NormalizeRemoteIp(ip); + { + std::lock_guard stateLock(g_serverLogState.stateLock); + ConnectionLogEntry &entry = g_serverLogState.entries[smallId]; + ResetConnectionLogEntry(&entry); + entry.remoteIp = remoteIp; + } + + LogInfof("network", "accepted tcp connection from %s as smallId=%u", remoteIp.c_str(), (unsigned)smallId); + } + + // Once login succeeds, bind the resolved player name onto the cached transport entry. + void OnAcceptedPlayerLogin(unsigned char smallId, const std::wstring &playerName) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + const std::string playerNameUtf8 = NormalizePlayerName(playerName); + std::string remoteIp("unknown"); + { + std::lock_guard stateLock(g_serverLogState.stateLock); + ConnectionLogEntry &entry = g_serverLogState.entries[smallId]; + entry.playerName = playerNameUtf8; + if (!entry.remoteIp.empty()) + { + remoteIp = entry.remoteIp; + } + } + + LogInfof("network", "accepted player login: name=\"%s\" ip=%s smallId=%u", playerNameUtf8.c_str(), remoteIp.c_str(), (unsigned)smallId); + } + + // Read the cached IP for the rejection log, then clear the slot because the player never fully joined. + void OnRejectedPlayerLogin(unsigned char smallId, const std::wstring &playerName, ELoginRejectReason reason) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + const std::string playerNameUtf8 = NormalizePlayerName(playerName); + std::string remoteIp("unknown"); + { + std::lock_guard stateLock(g_serverLogState.stateLock); + ConnectionLogEntry &entry = g_serverLogState.entries[smallId]; + if (!entry.remoteIp.empty()) + { + remoteIp = entry.remoteIp; + } + ResetConnectionLogEntry(&entry); + } + + LogWarnf("network", "rejected login from %s: name=\"%s\" reason=%s", remoteIp.c_str(), playerNameUtf8.c_str(), LoginRejectReasonToString(reason)); + } + + // Disconnect logging is the final consumer of cached metadata, so it also clears the slot afterward. + void OnPlayerDisconnected( + unsigned char smallId, + const std::wstring &playerName, + DisconnectPacket::eDisconnectReason reason, + bool initiatedByServer) + { + if (!IsDedicatedServerLoggingEnabled()) + { + return; + } + + std::string playerNameUtf8 = NormalizePlayerName(playerName); + std::string remoteIp("unknown"); + { + // Copy state under lock and emit the log after unlocking so CLI output never blocks connection bookkeeping. + std::lock_guard stateLock(g_serverLogState.stateLock); + ConnectionLogEntry &entry = g_serverLogState.entries[smallId]; + if (!entry.remoteIp.empty()) + { + remoteIp = entry.remoteIp; + } + if (playerNameUtf8 == "" && !entry.playerName.empty()) + { + playerNameUtf8 = entry.playerName; + } + ResetConnectionLogEntry(&entry); + } + + LogInfof( + "network", + "%s: name=\"%s\" ip=%s smallId=%u reason=%s", + initiatedByServer ? "disconnecting player" : "player disconnected", + playerNameUtf8.c_str(), + remoteIp.c_str(), + (unsigned)smallId, + DisconnectReasonToString(reason)); + } + + /** + * For logging purposes, the responsibility is technically misplaced, but the IP is cached in `LogManager`. + * Those cached values are then used to retrieve the player's IP. + * + * Eventually, this should be implemented in a separate class or on the `Minecraft.Client` side instead. + */ + bool TryGetConnectionRemoteIp(unsigned char smallId, std::string *outIp) + { + if (!IsDedicatedServerLoggingEnabled() || outIp == NULL) + { + return false; + } + + std::lock_guard stateLock(g_serverLogState.stateLock); + const ConnectionLogEntry &entry = g_serverLogState.entries[smallId]; + if (entry.remoteIp.empty() || entry.remoteIp == "unknown") + { + return false; + } + + *outIp = entry.remoteIp; + return true; + } + + // Provide explicit cache cleanup for paths that terminate without going through disconnect logging. + void ClearConnection(unsigned char smallId) + { + std::lock_guard stateLock(g_serverLogState.stateLock); + ResetConnectionLogEntry(&g_serverLogState.entries[smallId]); + } + } +} diff --git a/Minecraft.Server/ServerLogManager.h b/Minecraft.Server/ServerLogManager.h new file mode 100644 index 000000000..1d4abfb5b --- /dev/null +++ b/Minecraft.Server/ServerLogManager.h @@ -0,0 +1,127 @@ +#pragma once + +#include +#include + +#include "..\Minecraft.World\DisconnectPacket.h" + +namespace ServerRuntime +{ + namespace ServerLogManager + { + /** + * Identifies why the dedicated server rejected a TCP connection before login completed + * ログイン完了前にTCP接続を拒否した理由 + */ + enum ETcpRejectReason + { + eTcpRejectReason_BannedIp = 0, + eTcpRejectReason_GameNotReady, + eTcpRejectReason_ServerFull + }; + + /** + * Identifies why the dedicated server rejected a player during login validation + * ログイン検証中にプレイヤーを拒否した理由 + */ + enum ELoginRejectReason + { + eLoginRejectReason_BannedXuid = 0, + eLoginRejectReason_NotWhitelisted, + eLoginRejectReason_DuplicateXuid, + eLoginRejectReason_DuplicateName + }; + + /** + * Returns `true` when client-side debug logs should be redirected into the dedicated server logger + * dedicated server時にclient側デバッグログを転送すかどうか + */ + bool ShouldForwardClientDebugLogs(); + + /** + * Formats and forwards `CMinecraftApp::DebugPrintf` output through the dedicated server logger + * CMinecraftApp::DebugPrintf の出力を専用サーバーロガーへ転送 + */ + void ForwardClientAppDebugLogV(const char *format, va_list args); + + /** + * Formats and forwards `CMinecraftApp::DebugPrintf(int user, ...)` output through the dedicated server logger + * CMinecraftApp::DebugPrintf(int user, ...) の出力を専用サーバーロガーへ転送 + */ + void ForwardClientUserDebugLogV(int user, const char *format, va_list args); + + /** + * Formats and forwards legacy `DebugSpew` output through the dedicated server logger + * 従来の DebugSpew 出力を専用サーバーロガーへ転送 + */ + void ForwardClientDebugSpewLogV(const char *format, va_list args); + + /** + * Clears cached connection metadata before the dedicated server starts accepting players + * 接続ログ管理用のキャッシュを初期化 + */ + void Initialize(); + + /** + * Releases cached connection metadata after the dedicated server stops + * 接続ログ管理用のキャッシュを停止時に破棄 + */ + void Shutdown(); + + /** + * **Log Incoming TCP Connection** + * + * Emits a named log for a raw TCP accept before smallId assignment finishes + * smallId割り当て前のTCP接続を記録 + */ + void OnIncomingTcpConnection(const char *ip); + + /** + * Emits a named log for a TCP connection rejected before login starts + * ログイン開始前に拒否したTCP接続を記録 + */ + void OnRejectedTcpConnection(const char *ip, ETcpRejectReason reason); + + /** + * Stores the remote IP for the assigned smallId and logs the accepted transport connection + * 割り当て済みsmallIdに対接続IPを保存して記録 + */ + void OnAcceptedTcpConnection(unsigned char smallId, const char *ip); + + /** + * Associates a player name with the connection and emits the accepted login log + * 接続にプレイヤー名を関連付けてログイン成功を記録 + */ + void OnAcceptedPlayerLogin(unsigned char smallId, const std::wstring &playerName); + + /** + * Emits a named login rejection log and clears cached metadata for that smallId + * ログイン拒否を記録し対象smallIdのキャッシュを破棄 + */ + void OnRejectedPlayerLogin(unsigned char smallId, const std::wstring &playerName, ELoginRejectReason reason); + + /** + * Emits a named disconnect log using cached connection metadata and then clears that entry + * 接続キャッシュを使って切断ログを出しその後で破棄 + */ + void OnPlayerDisconnected( + unsigned char smallId, + const std::wstring &playerName, + DisconnectPacket::eDisconnectReason reason, + bool initiatedByServer); + + /** + * Reads the cached remote IP for a live smallId without consuming the entry + * Eventually, this should be implemented in a separate class or on the `Minecraft.Client` side instead. + * + * 指定smallIdの接続IPをキャッシュから参照する + */ + bool TryGetConnectionRemoteIp(unsigned char smallId, std::string *outIp); + + /** + * Removes any remembered IP or player name for the specified smallId + * 指定smallIdに紐づく接続キャッシュを消去 + */ + void ClearConnection(unsigned char smallId); + } +} diff --git a/Minecraft.Server/ServerLogger.cpp b/Minecraft.Server/ServerLogger.cpp new file mode 100644 index 000000000..0c7c567f6 --- /dev/null +++ b/Minecraft.Server/ServerLogger.cpp @@ -0,0 +1,258 @@ +#include "stdafx.h" + +#include "ServerLogger.h" +#include "Common\\StringUtils.h" +#include "vendor\\linenoise\\linenoise.h" + +#include +#include +#include + +namespace ServerRuntime +{ +static volatile LONG g_minLogLevel = (LONG)eServerLogLevel_Info; + +static const char *NormalizeCategory(const char *category) +{ + if (category == NULL || category[0] == 0) + { + return "server"; + } + return category; +} + +static const char *LogLevelToString(EServerLogLevel level) +{ + switch (level) + { + case eServerLogLevel_Debug: + return "DEBUG"; + case eServerLogLevel_Info: + return "INFO"; + case eServerLogLevel_Warn: + return "WARN"; + case eServerLogLevel_Error: + return "ERROR"; + default: + return "INFO"; + } +} + +static WORD LogLevelToColor(EServerLogLevel level) +{ + switch (level) + { + case eServerLogLevel_Debug: + return FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; + case eServerLogLevel_Warn: + return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; + case eServerLogLevel_Error: + return FOREGROUND_RED | FOREGROUND_INTENSITY; + case eServerLogLevel_Info: + default: + return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; + } +} + +static void BuildTimestamp(char *buffer, size_t bufferSize) +{ + if (buffer == NULL || bufferSize == 0) + { + return; + } + + SYSTEMTIME localTime; + GetLocalTime(&localTime); + sprintf_s( + buffer, + bufferSize, + "%04u-%02u-%02u %02u:%02u:%02u.%03u", + (unsigned)localTime.wYear, + (unsigned)localTime.wMonth, + (unsigned)localTime.wDay, + (unsigned)localTime.wHour, + (unsigned)localTime.wMinute, + (unsigned)localTime.wSecond, + (unsigned)localTime.wMilliseconds); +} + +static bool ShouldLog(EServerLogLevel level) +{ + return ((LONG)level >= g_minLogLevel); +} + +static void WriteLogLine(EServerLogLevel level, const char *category, const char *message) +{ + if (!ShouldLog(level)) + { + return; + } + + linenoiseExternalWriteBegin(); + + const char *safeCategory = NormalizeCategory(category); + const char *safeMessage = (message != NULL) ? message : ""; + + char timestamp[32] = {}; + BuildTimestamp(timestamp, sizeof(timestamp)); + + HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_SCREEN_BUFFER_INFO originalInfo; + bool hasColorConsole = false; + if (stdoutHandle != INVALID_HANDLE_VALUE && stdoutHandle != NULL) + { + if (GetConsoleScreenBufferInfo(stdoutHandle, &originalInfo)) + { + hasColorConsole = true; + SetConsoleTextAttribute(stdoutHandle, LogLevelToColor(level)); + } + } + + printf( + "[%s][%s][%s] %s\n", + timestamp, + LogLevelToString(level), + safeCategory, + safeMessage); + fflush(stdout); + + if (hasColorConsole) + { + SetConsoleTextAttribute(stdoutHandle, originalInfo.wAttributes); + } + + linenoiseExternalWriteEnd(); +} + +static void WriteLogLineV(EServerLogLevel level, const char *category, const char *format, va_list args) +{ + char messageBuffer[2048] = {}; + if (format == NULL) + { + WriteLogLine(level, category, ""); + return; + } + + vsnprintf_s(messageBuffer, sizeof(messageBuffer), _TRUNCATE, format, args); + WriteLogLine(level, category, messageBuffer); +} + +bool TryParseServerLogLevel(const char *value, EServerLogLevel *outLevel) +{ + if (value == NULL || outLevel == NULL) + { + return false; + } + + if (_stricmp(value, "debug") == 0) + { + *outLevel = eServerLogLevel_Debug; + return true; + } + if (_stricmp(value, "info") == 0) + { + *outLevel = eServerLogLevel_Info; + return true; + } + if (_stricmp(value, "warn") == 0 || _stricmp(value, "warning") == 0) + { + *outLevel = eServerLogLevel_Warn; + return true; + } + if (_stricmp(value, "error") == 0) + { + *outLevel = eServerLogLevel_Error; + return true; + } + + return false; +} + +void SetServerLogLevel(EServerLogLevel level) +{ + if (level < eServerLogLevel_Debug) + { + level = eServerLogLevel_Debug; + } + else if (level > eServerLogLevel_Error) + { + level = eServerLogLevel_Error; + } + + g_minLogLevel = (LONG)level; +} + +EServerLogLevel GetServerLogLevel() +{ + return (EServerLogLevel)g_minLogLevel; +} + +void LogDebug(const char *category, const char *message) +{ + WriteLogLine(eServerLogLevel_Debug, category, message); +} + +void LogInfo(const char *category, const char *message) +{ + WriteLogLine(eServerLogLevel_Info, category, message); +} + +void LogWarn(const char *category, const char *message) +{ + WriteLogLine(eServerLogLevel_Warn, category, message); +} + +void LogError(const char *category, const char *message) +{ + WriteLogLine(eServerLogLevel_Error, category, message); +} + +void LogDebugf(const char *category, const char *format, ...) +{ + va_list args; + va_start(args, format); + WriteLogLineV(eServerLogLevel_Debug, category, format, args); + va_end(args); +} + +void LogInfof(const char *category, const char *format, ...) +{ + va_list args; + va_start(args, format); + WriteLogLineV(eServerLogLevel_Info, category, format, args); + va_end(args); +} + +void LogWarnf(const char *category, const char *format, ...) +{ + va_list args; + va_start(args, format); + WriteLogLineV(eServerLogLevel_Warn, category, format, args); + va_end(args); +} + +void LogErrorf(const char *category, const char *format, ...) +{ + va_list args; + va_start(args, format); + WriteLogLineV(eServerLogLevel_Error, category, format, args); + va_end(args); +} + +void LogStartupStep(const char *message) +{ + LogInfo("startup", message); +} + +void LogWorldIO(const char *message) +{ + LogInfo("world-io", message); +} + +void LogWorldName(const char *prefix, const std::wstring &name) +{ + std::string utf8 = StringUtils::WideToUtf8(name); + LogInfof("world-io", "%s: %s", (prefix != NULL) ? prefix : "name", utf8.c_str()); +} +} + diff --git a/Minecraft.Server/ServerLogger.h b/Minecraft.Server/ServerLogger.h new file mode 100644 index 000000000..89b820e6a --- /dev/null +++ b/Minecraft.Server/ServerLogger.h @@ -0,0 +1,44 @@ +#pragma once + +#include + +namespace ServerRuntime +{ + enum EServerLogLevel + { + eServerLogLevel_Debug = 0, + eServerLogLevel_Info = 1, + eServerLogLevel_Warn = 2, + eServerLogLevel_Error = 3 + }; + + /** + * **Parse Log Level String** + * + * Converts a string value into log level (`debug`/`info`/`warn`/`error`) + * ログレベル文字列の変換処理 + * + * @param value Source string + * @param outLevel Output location for parsed level + * @return `true` when conversion succeeds + */ + bool TryParseServerLogLevel(const char *value, EServerLogLevel *outLevel); + + void SetServerLogLevel(EServerLogLevel level); + EServerLogLevel GetServerLogLevel(); + + void LogDebug(const char *category, const char *message); + void LogInfo(const char *category, const char *message); + void LogWarn(const char *category, const char *message); + void LogError(const char *category, const char *message); + + /** Emit formatted log output with the specified level and category */ + void LogDebugf(const char *category, const char *format, ...); + void LogInfof(const char *category, const char *format, ...); + void LogWarnf(const char *category, const char *format, ...); + void LogErrorf(const char *category, const char *format, ...); + + void LogStartupStep(const char *message); + void LogWorldIO(const char *message); + void LogWorldName(const char *prefix, const std::wstring &name); +} diff --git a/Minecraft.Server/ServerProperties.cpp b/Minecraft.Server/ServerProperties.cpp new file mode 100644 index 000000000..d6ba64e7e --- /dev/null +++ b/Minecraft.Server/ServerProperties.cpp @@ -0,0 +1,930 @@ +#include "stdafx.h" + +#include "ServerProperties.h" + +#include "ServerLogger.h" +#include "Common\\StringUtils.h" +#include "Common\\FileUtils.h" +#include "..\\Minecraft.World\\ChunkSource.h" + +#include +#include +#include +#include +#include + +namespace ServerRuntime +{ +using StringUtils::ToLowerAscii; +using StringUtils::TrimAscii; +using StringUtils::StripUtf8Bom; +using StringUtils::Utf8ToWide; +using StringUtils::WideToUtf8; + +struct ServerPropertyDefault +{ + const char *key; + const char *value; +}; + +static const char *kServerPropertiesPath = "server.properties"; +static const size_t kMaxSaveIdLength = 31; + +static const int kDefaultServerPort = 25565; +static const int kDefaultMaxPlayers = 16; +static const int kMaxDedicatedPlayers = 256; +static const int kDefaultAutosaveIntervalSeconds = 60; +static const char *kLanAdvertisePropertyKey = "lan-advertise"; + +static const ServerPropertyDefault kServerPropertyDefaults[] = +{ + { "allow-flight", "true" }, + { "allow-nether", "true" }, + { "autosave-interval", "60" }, + { "bedrock-fog", "true" }, + { "bonus-chest", "false" }, + { "difficulty", "1" }, + { "disable-saving", "false" }, + { "do-daylight-cycle", "true" }, + { "do-mob-loot", "true" }, + { "do-mob-spawning", "true" }, + { "do-tile-drops", "true" }, + { "fire-spreads", "true" }, + { "friends-of-friends", "false" }, + { "gamemode", "0" }, + { "gamertags", "true" }, + { "generate-structures", "true" }, + { "host-can-be-invisible", "true" }, + { "host-can-change-hunger", "true" }, + { "host-can-fly", "true" }, + { "keep-inventory", "false" }, + { "level-id", "world" }, + { "level-name", "world" }, + { "level-seed", "" }, + { "level-type", "default" }, + { "world-size", "classic" }, + { "spawn-protection", "0" }, + { "log-level", "info" }, + { "max-build-height", "256" }, + { "max-players", "16" }, + { "mob-griefing", "true" }, + { "motd", "A Minecraft Server" }, + { "natural-regeneration", "true" }, + { "pvp", "true" }, + { "server-ip", "0.0.0.0" }, + { "server-name", "DedicatedServer" }, + { "server-port", "25565" }, + { "white-list", "false" }, + { "lan-advertise", "false" }, + { "spawn-animals", "true" }, + { "spawn-monsters", "true" }, + { "spawn-npcs", "true" }, + { "tnt", "true" }, + { "trust-players", "true" } +}; + +static std::string BoolToString(bool value) +{ + return value ? "true" : "false"; +} + +static std::string IntToString(int value) +{ + char buffer[32] = {}; + sprintf_s(buffer, sizeof(buffer), "%d", value); + return std::string(buffer); +} + +static std::string Int64ToString(__int64 value) +{ + char buffer[64] = {}; + _i64toa_s(value, buffer, sizeof(buffer), 10); + return std::string(buffer); +} + +static int ClampInt(int value, int minValue, int maxValue) +{ + if (value < minValue) + { + return minValue; + } + if (value > maxValue) + { + return maxValue; + } + return value; +} + +static bool TryParseBool(const std::string &value, bool *outValue) +{ + if (outValue == NULL) + { + return false; + } + + std::string lowered = ToLowerAscii(TrimAscii(value)); + if (lowered == "true" || lowered == "1" || lowered == "yes" || lowered == "on") + { + *outValue = true; + return true; + } + if (lowered == "false" || lowered == "0" || lowered == "no" || lowered == "off") + { + *outValue = false; + return true; + } + return false; +} + +static bool TryParseInt(const std::string &value, int *outValue) +{ + if (outValue == NULL) + { + return false; + } + + std::string trimmed = TrimAscii(value); + if (trimmed.empty()) + { + return false; + } + + char *end = NULL; + long parsed = strtol(trimmed.c_str(), &end, 10); + if (end == trimmed.c_str() || *end != 0) + { + return false; + } + + *outValue = (int)parsed; + return true; +} + +static bool TryParseInt64(const std::string &value, __int64 *outValue) +{ + if (outValue == NULL) + { + return false; + } + + std::string trimmed = TrimAscii(value); + if (trimmed.empty()) + { + return false; + } + + char *end = NULL; + __int64 parsed = _strtoi64(trimmed.c_str(), &end, 10); + if (end == trimmed.c_str() || *end != 0) + { + return false; + } + + *outValue = parsed; + return true; +} + +static std::string LogLevelToPropertyValue(EServerLogLevel level) +{ + switch (level) + { + case eServerLogLevel_Debug: + return "debug"; + case eServerLogLevel_Warn: + return "warn"; + case eServerLogLevel_Error: + return "error"; + case eServerLogLevel_Info: + default: + return "info"; + } +} + +/** + * **Normalize Save ID** + * + * Normalizes an arbitrary string into a safe save destination ID + * Conversion rules: + * - Lowercase alphabetic characters + * - Keep only `[a-z0-9_.-]` + * - Replace spaces and unsupported characters with `_` + * - Fallback to `world` when empty + * - Enforce max length to match storage constraints + * 保存先IDの正規化処理 + */ +static std::string NormalizeSaveId(const std::string &source) +{ + std::string out; + out.reserve(source.length()); + + // Normalize into a character set that is safe for storage save IDs + // Replace invalid characters with '_' and fold letter case to reduce collisions + for (size_t i = 0; i < source.length(); ++i) + { + unsigned char ch = (unsigned char)source[i]; + if (ch >= 'A' && ch <= 'Z') + { + ch = (unsigned char)(ch - 'A' + 'a'); + } + + const bool alnum = (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); + const bool passthrough = (ch == '_') || (ch == '-') || (ch == '.'); + if (alnum || passthrough) + { + out.push_back((char)ch); + } + else if (std::isspace(ch)) + { + out.push_back('_'); + } + else if (ch < 0x80) + { + out.push_back('_'); + } + } + + if (out.empty()) + { + out = "world"; + } + + // Add a prefix when needed to avoid awkward leading characters + if (!((out[0] >= 'a' && out[0] <= 'z') || (out[0] >= '0' && out[0] <= '9'))) + { + out = std::string("w_") + out; + } + + // Clamp length to the 4J-side filename buffer constraint + if (out.length() > kMaxSaveIdLength) + { + out.resize(kMaxSaveIdLength); + } + + return out; +} + +static void ApplyDefaultServerProperties(std::unordered_map *properties) +{ + if (properties == NULL) + { + return; + } + + const size_t defaultCount = sizeof(kServerPropertyDefaults) / sizeof(kServerPropertyDefaults[0]); + for (size_t i = 0; i < defaultCount; ++i) + { + (*properties)[kServerPropertyDefaults[i].key] = kServerPropertyDefaults[i].value; + } +} + +/** + * **Parse server.properties Text** + * + * Extracts key/value pairs from `server.properties` format text + * - Ignores lines starting with `#` or `!` as comments + * - Accepts `=` or `:` as separators + * - Skips invalid lines and continues + * server.propertiesのパース処理 + */ +static bool ReadServerPropertiesFile(const char *filePath, std::unordered_map *properties, int *outParsedCount) +{ + if (properties == NULL) + { + return false; + } + + std::string text; + if (filePath == NULL || !FileUtils::ReadTextFile(filePath, &text)) + { + return false; + } + + text = StripUtf8Bom(text); + + int parsedCount = 0; + for (size_t start = 0; start <= text.length();) + { + size_t end = text.find_first_of("\r\n", start); + size_t nextStart = text.length() + 1; + if (end != std::string::npos) + { + nextStart = end + 1; + if (text[end] == '\r' && nextStart < text.length() && text[nextStart] == '\n') + { + ++nextStart; + } + } + + std::string line; + if (end == std::string::npos) + { + line = text.substr(start); + } + else + { + line = text.substr(start, end - start); + } + + std::string trimmedLine = TrimAscii(line); + if (trimmedLine.empty()) + { + start = nextStart; + continue; + } + + if (trimmedLine[0] == '#' || trimmedLine[0] == '!') + { + start = nextStart; + continue; + } + + size_t eqPos = trimmedLine.find('='); + size_t colonPos = trimmedLine.find(':'); + size_t sepPos = std::string::npos; + if (eqPos == std::string::npos) + { + sepPos = colonPos; + } + else if (colonPos == std::string::npos) + { + sepPos = eqPos; + } + else + { + sepPos = (eqPos < colonPos) ? eqPos : colonPos; + } + + if (sepPos == std::string::npos) + { + start = nextStart; + continue; + } + + std::string key = TrimAscii(trimmedLine.substr(0, sepPos)); + if (key.empty()) + { + start = nextStart; + continue; + } + + std::string value = TrimAscii(trimmedLine.substr(sepPos + 1)); + (*properties)[key] = value; + ++parsedCount; + start = nextStart; + } + + if (outParsedCount != NULL) + { + *outParsedCount = parsedCount; + } + + return true; +} + +/** + * **Write server.properties Text** + * + * Writes key/value data back as `server.properties` + * Sorts keys before writing to keep output order stable + * server.propertiesの書き戻し処理 + */ +static bool WriteServerPropertiesFile(const char *filePath, const std::unordered_map &properties) +{ + if (filePath == NULL) + { + return false; + } + + std::string text; + text += "# Minecraft server properties\n"; + text += "# Auto-generated and normalized when missing\n"; + + std::map sortedProperties(properties.begin(), properties.end()); + for (std::map::const_iterator it = sortedProperties.begin(); it != sortedProperties.end(); ++it) + { + text += it->first; + text += "="; + text += it->second; + text += "\n"; + } + + return FileUtils::WriteTextFileAtomic(filePath, text); +} + +static bool ReadNormalizedBoolProperty( + std::unordered_map *properties, + const char *key, + bool defaultValue, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + bool value = defaultValue; + if (!TryParseBool(raw, &value)) + { + value = defaultValue; + } + + std::string normalized = BoolToString(value); + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + return value; +} + +static int ReadNormalizedIntProperty( + std::unordered_map *properties, + const char *key, + int defaultValue, + int minValue, + int maxValue, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + int value = defaultValue; + if (!TryParseInt(raw, &value)) + { + value = defaultValue; + } + value = ClampInt(value, minValue, maxValue); + + std::string normalized = IntToString(value); + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + return value; +} + +static std::string ReadNormalizedStringProperty( + std::unordered_map *properties, + const char *key, + const std::string &defaultValue, + size_t maxLength, + bool *shouldWrite) +{ + std::string value = TrimAscii((*properties)[key]); + if (value.empty()) + { + value = defaultValue; + } + if (maxLength > 0 && value.length() > maxLength) + { + value.resize(maxLength); + } + + if (value != (*properties)[key]) + { + (*properties)[key] = value; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + return value; +} + +static bool ReadNormalizedOptionalInt64Property( + std::unordered_map *properties, + const char *key, + __int64 *outValue, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + if (raw.empty()) + { + if ((*properties)[key] != "") + { + (*properties)[key] = ""; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + return false; + } + + __int64 parsed = 0; + if (!TryParseInt64(raw, &parsed)) + { + (*properties)[key] = ""; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + return false; + } + + std::string normalized = Int64ToString(parsed); + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + if (outValue != NULL) + { + *outValue = parsed; + } + return true; +} + +static EServerLogLevel ReadNormalizedLogLevelProperty( + std::unordered_map *properties, + const char *key, + EServerLogLevel defaultValue, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + EServerLogLevel value = defaultValue; + if (!TryParseServerLogLevel(raw.c_str(), &value)) + { + value = defaultValue; + } + + std::string normalized = LogLevelToPropertyValue(value); + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + return value; +} + +static std::string ReadNormalizedLevelTypeProperty( + std::unordered_map *properties, + const char *key, + bool *outIsFlat, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + std::string lowered = ToLowerAscii(raw); + + bool isFlat = false; + std::string normalized = "default"; + if (lowered == "flat" || lowered == "superflat" || lowered == "1") + { + isFlat = true; + normalized = "flat"; + } + else if (lowered == "default" || lowered == "normal" || lowered == "0") + { + isFlat = false; + normalized = "default"; + } + + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + if (outIsFlat != NULL) + { + *outIsFlat = isFlat; + } + + return normalized; +} + +static std::string WorldSizeToPropertyValue(int worldSize) +{ + switch (worldSize) + { + case e_worldSize_Small: + return "small"; + case e_worldSize_Medium: + return "medium"; + case e_worldSize_Large: + return "large"; + case e_worldSize_Classic: + default: + return "classic"; + } +} + +static int WorldSizeToXzChunks(int worldSize) +{ + switch (worldSize) + { + case e_worldSize_Small: + return LEVEL_WIDTH_SMALL; + case e_worldSize_Medium: + return LEVEL_WIDTH_MEDIUM; + case e_worldSize_Large: + return LEVEL_WIDTH_LARGE; + case e_worldSize_Classic: + default: + return LEVEL_WIDTH_CLASSIC; + } +} + +static int WorldSizeToHellScale(int worldSize) +{ + switch (worldSize) + { + case e_worldSize_Small: + return HELL_LEVEL_SCALE_SMALL; + case e_worldSize_Medium: + return HELL_LEVEL_SCALE_MEDIUM; + case e_worldSize_Large: + return HELL_LEVEL_SCALE_LARGE; + case e_worldSize_Classic: + default: + return HELL_LEVEL_SCALE_CLASSIC; + } +} + +static bool TryParseWorldSize(const std::string &lowered, int *outWorldSize) +{ + if (outWorldSize == NULL) + { + return false; + } + + if (lowered == "classic" || lowered == "54" || lowered == "1") + { + *outWorldSize = e_worldSize_Classic; + return true; + } + if (lowered == "small" || lowered == "64" || lowered == "2") + { + *outWorldSize = e_worldSize_Small; + return true; + } + if (lowered == "medium" || lowered == "192" || lowered == "3") + { + *outWorldSize = e_worldSize_Medium; + return true; + } + if (lowered == "large" || lowered == "320" || lowered == "4") + { + *outWorldSize = e_worldSize_Large; + return true; + } + + return false; +} + +static int ReadNormalizedWorldSizeProperty( + std::unordered_map *properties, + const char *key, + int defaultWorldSize, + int *outXzChunks, + int *outHellScale, + bool *shouldWrite) +{ + std::string raw = TrimAscii((*properties)[key]); + std::string lowered = ToLowerAscii(raw); + + int worldSize = defaultWorldSize; + if (!raw.empty()) + { + int parsedWorldSize = defaultWorldSize; + if (TryParseWorldSize(lowered, &parsedWorldSize)) + { + worldSize = parsedWorldSize; + } + } + + std::string normalized = WorldSizeToPropertyValue(worldSize); + if (raw != normalized) + { + (*properties)[key] = normalized; + if (shouldWrite != NULL) + { + *shouldWrite = true; + } + } + + if (outXzChunks != NULL) + { + *outXzChunks = WorldSizeToXzChunks(worldSize); + } + if (outHellScale != NULL) + { + *outHellScale = WorldSizeToHellScale(worldSize); + } + + return worldSize; +} + +/** + * **Load Effective Server Properties Config** + * + * Loads effective world settings, repairs missing or invalid values, and returns normalized config + * - Creates defaults when file is missing + * - Fills required keys when absent + * - Normalizes `level-id` to a safe format + * - Auto-saves when any fix is applied + * 実効設定の読み込みと補正処理 + */ +ServerPropertiesConfig LoadServerPropertiesConfig() +{ + ServerPropertiesConfig config; + + std::unordered_map defaults; + std::unordered_map loaded; + ApplyDefaultServerProperties(&defaults); + + int parsedCount = 0; + bool readSuccess = ReadServerPropertiesFile(kServerPropertiesPath, &loaded, &parsedCount); + std::unordered_map merged = defaults; + bool shouldWrite = false; + + if (!readSuccess) + { + LogWorldIO("server.properties not found or unreadable; creating defaults"); + shouldWrite = true; + } + else + { + if (parsedCount == 0) + { + LogWorldIO("server.properties has no properties; applying defaults"); + shouldWrite = true; + } + + const size_t defaultCount = sizeof(kServerPropertyDefaults) / sizeof(kServerPropertyDefaults[0]); + for (size_t i = 0; i < defaultCount; ++i) + { + if (loaded.find(kServerPropertyDefaults[i].key) == loaded.end()) + { + shouldWrite = true; + break; + } + } + } + + for (std::unordered_map::const_iterator it = loaded.begin(); it != loaded.end(); ++it) + { + // Merge loaded values over defaults and keep unknown keys whenever possible + merged[it->first] = it->second; + } + + std::string worldName = TrimAscii(merged["level-name"]); + if (worldName.empty()) + { + worldName = "world"; + shouldWrite = true; + } + + std::string worldSaveId = TrimAscii(merged["level-id"]); + if (worldSaveId.empty()) + { + // If level-id is missing, derive it from level-name to lock save destination + worldSaveId = NormalizeSaveId(worldName); + shouldWrite = true; + } + else + { + // Normalize existing level-id as well to avoid future inconsistencies + std::string normalized = NormalizeSaveId(worldSaveId); + if (normalized != worldSaveId) + { + worldSaveId = normalized; + shouldWrite = true; + } + } + + merged["level-name"] = worldName; + merged["level-id"] = worldSaveId; + + config.worldName = Utf8ToWide(worldName.c_str()); + config.worldSaveId = worldSaveId; + + config.serverPort = ReadNormalizedIntProperty(&merged, "server-port", kDefaultServerPort, 1, 65535, &shouldWrite); + config.serverIp = ReadNormalizedStringProperty(&merged, "server-ip", "0.0.0.0", 255, &shouldWrite); + config.lanAdvertise = ReadNormalizedBoolProperty(&merged, kLanAdvertisePropertyKey, false, &shouldWrite); + config.whiteListEnabled = ReadNormalizedBoolProperty(&merged, "white-list", false, &shouldWrite); + config.serverName = ReadNormalizedStringProperty(&merged, "server-name", "DedicatedServer", 16, &shouldWrite); + config.maxPlayers = ReadNormalizedIntProperty(&merged, "max-players", kDefaultMaxPlayers, 1, kMaxDedicatedPlayers, &shouldWrite); + config.seed = 0; + config.hasSeed = ReadNormalizedOptionalInt64Property(&merged, "level-seed", &config.seed, &shouldWrite); + config.logLevel = ReadNormalizedLogLevelProperty(&merged, "log-level", eServerLogLevel_Info, &shouldWrite); + config.autosaveIntervalSeconds = ReadNormalizedIntProperty(&merged, "autosave-interval", kDefaultAutosaveIntervalSeconds, 5, 3600, &shouldWrite); + + config.difficulty = ReadNormalizedIntProperty(&merged, "difficulty", 1, 0, 3, &shouldWrite); + config.gameMode = ReadNormalizedIntProperty(&merged, "gamemode", 0, 0, 1, &shouldWrite); + config.worldSize = ReadNormalizedWorldSizeProperty( + &merged, + "world-size", + e_worldSize_Classic, + &config.worldSizeChunks, + &config.worldHellScale, + &shouldWrite); + config.levelType = ReadNormalizedLevelTypeProperty(&merged, "level-type", &config.levelTypeFlat, &shouldWrite); + config.spawnProtectionRadius = ReadNormalizedIntProperty(&merged, "spawn-protection", 0, 0, 256, &shouldWrite); + config.generateStructures = ReadNormalizedBoolProperty(&merged, "generate-structures", true, &shouldWrite); + config.bonusChest = ReadNormalizedBoolProperty(&merged, "bonus-chest", false, &shouldWrite); + config.pvp = ReadNormalizedBoolProperty(&merged, "pvp", true, &shouldWrite); + config.trustPlayers = ReadNormalizedBoolProperty(&merged, "trust-players", true, &shouldWrite); + config.fireSpreads = ReadNormalizedBoolProperty(&merged, "fire-spreads", true, &shouldWrite); + config.tnt = ReadNormalizedBoolProperty(&merged, "tnt", true, &shouldWrite); + config.spawnAnimals = ReadNormalizedBoolProperty(&merged, "spawn-animals", true, &shouldWrite); + config.spawnNpcs = ReadNormalizedBoolProperty(&merged, "spawn-npcs", true, &shouldWrite); + config.spawnMonsters = ReadNormalizedBoolProperty(&merged, "spawn-monsters", true, &shouldWrite); + config.allowFlight = ReadNormalizedBoolProperty(&merged, "allow-flight", true, &shouldWrite); + config.allowNether = ReadNormalizedBoolProperty(&merged, "allow-nether", true, &shouldWrite); + config.friendsOfFriends = ReadNormalizedBoolProperty(&merged, "friends-of-friends", false, &shouldWrite); + config.gamertags = ReadNormalizedBoolProperty(&merged, "gamertags", true, &shouldWrite); + config.bedrockFog = ReadNormalizedBoolProperty(&merged, "bedrock-fog", true, &shouldWrite); + config.hostCanFly = ReadNormalizedBoolProperty(&merged, "host-can-fly", true, &shouldWrite); + config.hostCanChangeHunger = ReadNormalizedBoolProperty(&merged, "host-can-change-hunger", true, &shouldWrite); + config.hostCanBeInvisible = ReadNormalizedBoolProperty(&merged, "host-can-be-invisible", true, &shouldWrite); + config.disableSaving = ReadNormalizedBoolProperty(&merged, "disable-saving", false, &shouldWrite); + config.mobGriefing = ReadNormalizedBoolProperty(&merged, "mob-griefing", true, &shouldWrite); + config.keepInventory = ReadNormalizedBoolProperty(&merged, "keep-inventory", false, &shouldWrite); + config.doMobSpawning = ReadNormalizedBoolProperty(&merged, "do-mob-spawning", true, &shouldWrite); + config.doMobLoot = ReadNormalizedBoolProperty(&merged, "do-mob-loot", true, &shouldWrite); + config.doTileDrops = ReadNormalizedBoolProperty(&merged, "do-tile-drops", true, &shouldWrite); + config.naturalRegeneration = ReadNormalizedBoolProperty(&merged, "natural-regeneration", true, &shouldWrite); + config.doDaylightCycle = ReadNormalizedBoolProperty(&merged, "do-daylight-cycle", true, &shouldWrite); + + config.maxBuildHeight = ReadNormalizedIntProperty(&merged, "max-build-height", 256, 64, 256, &shouldWrite); + config.motd = ReadNormalizedStringProperty(&merged, "motd", "A Minecraft Server", 255, &shouldWrite); + + if (shouldWrite) + { + if (WriteServerPropertiesFile(kServerPropertiesPath, merged)) + { + LogWorldIO("wrote server.properties"); + } + else + { + LogWorldIO("failed to write server.properties"); + } + } + + return config; +} + +/** + * **Save World Identity While Preserving Other Keys** + * + * Saves world identity fields while preserving as many other settings as possible + * - Reads existing file and merges including unknown keys + * - Updates `level-name`, `level-id`, and `white-list` before writing back + * ワールド識別情報の保存処理 + */ +bool SaveServerPropertiesConfig(const ServerPropertiesConfig &config) +{ + std::unordered_map merged; + ApplyDefaultServerProperties(&merged); + + std::unordered_map loaded; + int parsedCount = 0; + if (ReadServerPropertiesFile(kServerPropertiesPath, &loaded, &parsedCount)) + { + for (std::unordered_map::const_iterator it = loaded.begin(); it != loaded.end(); ++it) + { + // Keep existing content so keys untouched by caller are not dropped + merged[it->first] = it->second; + } + } + + std::string worldName = TrimAscii(WideToUtf8(config.worldName)); + if (worldName.empty()) + { + worldName = "world"; // Default world name + } + + std::string worldSaveId = TrimAscii(config.worldSaveId); + if (worldSaveId.empty()) + { + worldSaveId = NormalizeSaveId(worldName); + } + else + { + worldSaveId = NormalizeSaveId(worldSaveId); + } + + merged["level-name"] = worldName; + merged["level-id"] = worldSaveId; + merged["white-list"] = BoolToString(config.whiteListEnabled); + + return WriteServerPropertiesFile(kServerPropertiesPath, merged); +} +} + diff --git a/Minecraft.Server/ServerProperties.h b/Minecraft.Server/ServerProperties.h new file mode 100644 index 000000000..3bb5aca80 --- /dev/null +++ b/Minecraft.Server/ServerProperties.h @@ -0,0 +1,105 @@ +#pragma once + +#include +#include "ServerLogger.h" + +namespace ServerRuntime +{ + /** + * `server.properties` + */ + struct ServerPropertiesConfig + { + /** world name `level-name` */ + std::wstring worldName; + /** world save id `level-id` */ + std::string worldSaveId; + + /** `server-port` */ + int serverPort; + /** `server-ip` */ + std::string serverIp; + /** `lan-advertise` */ + bool lanAdvertise; + /** `white-list` */ + bool whiteListEnabled; + /** `server-name` (max 16 chars at runtime) */ + std::string serverName; + /** `max-players` */ + int maxPlayers; + /** `level-seed` is explicitly set */ + bool hasSeed; + /** `level-seed` */ + __int64 seed; + /** `log-level` */ + EServerLogLevel logLevel; + /** `autosave-interval` (seconds) */ + int autosaveIntervalSeconds; + + /** host options / game settings */ + int difficulty; + int gameMode; + /** `world-size` preset (`classic` / `small` / `medium` / `large`) */ + int worldSize; + /** Overworld chunk width derived from `world-size` */ + int worldSizeChunks; + /** Nether scale derived from `world-size` */ + int worldHellScale; + bool levelTypeFlat; + /** `spawn-protection` radius in blocks (0 disables protection) */ + int spawnProtectionRadius; + bool generateStructures; + bool bonusChest; + bool pvp; + bool trustPlayers; + bool fireSpreads; + bool tnt; + bool spawnAnimals; + bool spawnNpcs; + bool spawnMonsters; + bool allowFlight; + bool allowNether; + bool friendsOfFriends; + bool gamertags; + bool bedrockFog; + bool hostCanFly; + bool hostCanChangeHunger; + bool hostCanBeInvisible; + bool disableSaving; + bool mobGriefing; + bool keepInventory; + bool doMobSpawning; + bool doMobLoot; + bool doTileDrops; + bool naturalRegeneration; + bool doDaylightCycle; + + /** other MinecraftServer runtime settings */ + int maxBuildHeight; + std::string levelType; + std::string motd; + }; + + /** + * server.properties loader + * + * - ファイル欠損時はデフォルト値で新規作成 + * - 必須キー不足時は補完して再保存 + * - `level-id` は保存先として安全な形式へ正規化 + * + * @return `WorldManager` が利用するワールド設定 + */ + ServerPropertiesConfig LoadServerPropertiesConfig(); + + /** + * server.properties saver + * + * - `level-name` と `level-id` を更新 + * - `white-list` を更新 + * - それ以外の既存キーは極力保持 + * + * @param config 保存するワールド識別情報と永続化対象設定 + * @return 書き込み成功時 `true` + */ + bool SaveServerPropertiesConfig(const ServerPropertiesConfig &config); +} diff --git a/Minecraft.Server/ServerShutdown.h b/Minecraft.Server/ServerShutdown.h new file mode 100644 index 000000000..302b1a55d --- /dev/null +++ b/Minecraft.Server/ServerShutdown.h @@ -0,0 +1,6 @@ +#pragma once + +namespace ServerRuntime +{ + void RequestDedicatedServerShutdown(); +} diff --git a/Minecraft.Server/Windows64/ServerMain.cpp b/Minecraft.Server/Windows64/ServerMain.cpp new file mode 100644 index 000000000..a8d5fc66b --- /dev/null +++ b/Minecraft.Server/Windows64/ServerMain.cpp @@ -0,0 +1,718 @@ +#include "stdafx.h" + +#include "Common/App_Defines.h" +#include "Common/Network/GameNetworkManager.h" +#include "Input.h" +#include "Minecraft.h" +#include "MinecraftServer.h" +#include "..\Access\Access.h" +#include "..\Common\StringUtils.h" +#include "..\ServerLogger.h" +#include "..\ServerLogManager.h" +#include "..\ServerProperties.h" +#include "..\ServerShutdown.h" +#include "..\WorldManager.h" +#include "..\Console\ServerCli.h" +#include "Tesselator.h" +#include "Windows64/4JLibs/inc/4J_Render.h" +#include "Windows64/GameConfig/Minecraft.spa.h" +#include "Windows64/KeyboardMouseInput.h" +#include "Windows64/Network/WinsockNetLayer.h" +#include "Windows64/Windows64_UIController.h" +#include "Common/UI/UI.h" + +#include "../../Minecraft.World/AABB.h" +#include "../../Minecraft.World/Vec3.h" +#include "../../Minecraft.World/IntCache.h" +#include "../../Minecraft.World/ChunkSource.h" +#include "../../Minecraft.World/TilePos.h" +#include "../../Minecraft.World/compression.h" +#include "../../Minecraft.World/OldChunkStorage.h" +#include "../../Minecraft.World/net.minecraft.world.level.tile.h" +#include "../../Minecraft.World/Random.h" + +#include +#include +#include + +#include + +extern ATOM MyRegisterClass(HINSTANCE hInstance); +extern BOOL InitInstance(HINSTANCE hInstance, int nCmdShow); +extern HRESULT InitDevice(); +extern void CleanupDevice(); +extern void DefineActions(void); + +extern HWND g_hWnd; +extern int g_iScreenWidth; +extern int g_iScreenHeight; +extern char g_Win64Username[17]; +extern wchar_t g_Win64UsernameW[17]; +extern ID3D11Device* g_pd3dDevice; +extern ID3D11DeviceContext* g_pImmediateContext; +extern IDXGISwapChain* g_pSwapChain; +extern ID3D11RenderTargetView* g_pRenderTargetView; +extern ID3D11DepthStencilView* g_pDepthStencilView; +extern DWORD dwProfileSettingsA[]; + +static const int kProfileValueCount = 5; +static const int kProfileSettingCount = 4; + +struct DedicatedServerConfig +{ + int port; + char bindIP[256]; + char name[17]; + int maxPlayers; + int worldSize; + int worldSizeChunks; + int worldHellScale; + __int64 seed; + ServerRuntime::EServerLogLevel logLevel; + bool hasSeed; + bool showHelp; +}; + +static std::atomic g_shutdownRequested(false); +static const DWORD kDefaultAutosaveIntervalMs = 60 * 1000; +static const int kServerActionPad = 0; + +static bool IsShutdownRequested() +{ + return g_shutdownRequested.load(); +} + +namespace ServerRuntime +{ + void RequestDedicatedServerShutdown() + { + g_shutdownRequested.store(true); + } +} + +/** + * Calls Access::Shutdown automatically once dedicated access control was initialized successfully + * アクセス制御初期化後のShutdownを自動化する + */ +class AccessShutdownGuard +{ +public: + AccessShutdownGuard() + : m_active(false) + { + } + + void Activate() + { + m_active = true; + } + + ~AccessShutdownGuard() + { + if (m_active) + { + ServerRuntime::Access::Shutdown(); + } + } + +private: + bool m_active; +}; +static BOOL WINAPI ConsoleCtrlHandlerProc(DWORD ctrlType) +{ + switch (ctrlType) + { + case CTRL_C_EVENT: + case CTRL_BREAK_EVENT: + case CTRL_CLOSE_EVENT: + case CTRL_SHUTDOWN_EVENT: + ServerRuntime::RequestDedicatedServerShutdown(); + return TRUE; + default: + return FALSE; + } +} + +/** + * **Wait For Server Stopped Signal** + * + * Thread entry used during shutdown to wait until the network layer reports server stop completion + * 停止通知待機用の終了スレッド処理 + */ +static int WaitForServerStoppedThreadProc(void *) +{ + if (g_NetworkManager.ServerStoppedValid()) + { + g_NetworkManager.ServerStoppedWait(); + } + return 0; +} + +static void PrintUsage() +{ + ServerRuntime::LogInfo("usage", "Minecraft.Server.exe [options]"); + ServerRuntime::LogInfo("usage", " -port <1-65535> Listen TCP port (default: server.properties:server-port)"); + ServerRuntime::LogInfo("usage", " -ip Bind address (default: server.properties:server-ip)"); + ServerRuntime::LogInfo("usage", " -bind Alias of -ip"); + ServerRuntime::LogInfo("usage", " -name Host display name (max 16 chars, default: server.properties:server-name)"); + ServerRuntime::LogInfo("usage", " -maxplayers <1-8> Public slots (default: server.properties:max-players)"); + ServerRuntime::LogInfo("usage", " -seed World seed (overrides server.properties:level-seed)"); + ServerRuntime::LogInfo("usage", " -loglevel debug|info|warn|error (default: server.properties:log-level)"); + ServerRuntime::LogInfo("usage", " -help Show this help"); +} + +using ServerRuntime::LoadServerPropertiesConfig; +using ServerRuntime::LogError; +using ServerRuntime::LogErrorf; +using ServerRuntime::LogInfof; +using ServerRuntime::LogDebugf; +using ServerRuntime::LogStartupStep; +using ServerRuntime::LogWarn; +using ServerRuntime::LogWorldIO; +using ServerRuntime::SaveServerPropertiesConfig; +using ServerRuntime::SetServerLogLevel; +using ServerRuntime::ServerPropertiesConfig; +using ServerRuntime::TryParseServerLogLevel; +using ServerRuntime::StringUtils::WideToUtf8; +using ServerRuntime::BootstrapWorldForServer; +using ServerRuntime::eWorldBootstrap_CreatedNew; +using ServerRuntime::eWorldBootstrap_Failed; +using ServerRuntime::eWorldBootstrap_Loaded; +using ServerRuntime::WaitForWorldActionIdle; +using ServerRuntime::WorldBootstrapResult; + +static bool ParseIntArg(const char *value, int *outValue) +{ + if (value == NULL || *value == 0) + return false; + + char *end = NULL; + long parsed = strtol(value, &end, 10); + if (end == value || *end != 0) + return false; + + *outValue = (int)parsed; + return true; +} + +static bool ParseInt64Arg(const char *value, __int64 *outValue) +{ + if (value == NULL || *value == 0) + return false; + + char *end = NULL; + __int64 parsed = _strtoi64(value, &end, 10); + if (end == value || *end != 0) + return false; + + *outValue = parsed; + return true; +} + +static bool ParseCommandLine(int argc, char **argv, DedicatedServerConfig *config) +{ + for (int i = 1; i < argc; ++i) + { + const char *arg = argv[i]; + if (_stricmp(arg, "-help") == 0 || _stricmp(arg, "--help") == 0 || _stricmp(arg, "-h") == 0) + { + config->showHelp = true; + return true; + } + else if ((_stricmp(arg, "-port") == 0) && (i + 1 < argc)) + { + int port = 0; + if (!ParseIntArg(argv[++i], &port) || port <= 0 || port > 65535) + { + LogError("startup", "Invalid -port value."); + return false; + } + config->port = port; + } + else if ((_stricmp(arg, "-ip") == 0 || _stricmp(arg, "-bind") == 0) && (i + 1 < argc)) + { + strncpy_s(config->bindIP, sizeof(config->bindIP), argv[++i], _TRUNCATE); + } + else if ((_stricmp(arg, "-name") == 0) && (i + 1 < argc)) + { + strncpy_s(config->name, sizeof(config->name), argv[++i], _TRUNCATE); + } + else if ((_stricmp(arg, "-maxplayers") == 0) && (i + 1 < argc)) + { + int maxPlayers = 0; + if (!ParseIntArg(argv[++i], &maxPlayers) || maxPlayers <= 0 || maxPlayers > MINECRAFT_NET_MAX_PLAYERS) + { + LogError("startup", "Invalid -maxplayers value."); + return false; + } + config->maxPlayers = maxPlayers; + } + else if ((_stricmp(arg, "-seed") == 0) && (i + 1 < argc)) + { + if (!ParseInt64Arg(argv[++i], &config->seed)) + { + LogError("startup", "Invalid -seed value."); + return false; + } + config->hasSeed = true; + } + else if ((_stricmp(arg, "-loglevel") == 0) && (i + 1 < argc)) + { + if (!TryParseServerLogLevel(argv[++i], &config->logLevel)) + { + LogError("startup", "Invalid -loglevel value. Use debug/info/warn/error."); + return false; + } + } + else + { + LogErrorf("startup", "Unknown or incomplete argument: %s", arg); + return false; + } + } + + return true; +} + +static void SetExeWorkingDirectory() +{ + char exePath[MAX_PATH] = {}; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + char *slash = strrchr(exePath, '\\'); + if (slash != NULL) + { + *(slash + 1) = 0; + SetCurrentDirectoryA(exePath); + } +} + +static void ApplyServerPropertiesToDedicatedConfig(const ServerPropertiesConfig &serverProperties, DedicatedServerConfig *config) +{ + if (config == NULL) + { + return; + } + + config->port = serverProperties.serverPort; + strncpy_s( + config->bindIP, + sizeof(config->bindIP), + serverProperties.serverIp.empty() ? "0.0.0.0" : serverProperties.serverIp.c_str(), + _TRUNCATE); + strncpy_s( + config->name, + sizeof(config->name), + serverProperties.serverName.empty() ? "DedicatedServer" : serverProperties.serverName.c_str(), + _TRUNCATE); + config->maxPlayers = serverProperties.maxPlayers; + config->worldSize = serverProperties.worldSize; + config->worldSizeChunks = serverProperties.worldSizeChunks; + config->worldHellScale = serverProperties.worldHellScale; + config->logLevel = serverProperties.logLevel; + config->hasSeed = serverProperties.hasSeed; + config->seed = serverProperties.seed; +} + +/** + * **Tick Core Async Subsystems** + * + * Advances core subsystems for one frame to keep async processing alive + * Call continuously even inside wait loops to avoid stalling storage/profile/network work + * 非同期進行維持のためのティック処理 + */ +static void TickCoreSystems() +{ + g_NetworkManager.DoWork(); + ProfileManager.Tick(); + StorageManager.Tick(); +} + +/** + * **Handle Queued XUI Server Action Once** + * + * Processes queued XUI/server action once + * XUIアクションの単発処理 + */ +static void HandleXuiActions() +{ + app.HandleXuiActions(); +} + +/** + * Dedicated Server Entory Point + * + * 主な責務: + * - プロセス/描画/ネットワークの初期化 + * - `WorldManager` によるワールドロードまたは新規作成 + * - メインループと定期オートセーブ実行 + * - 終了時の最終保存と各サブシステムの安全停止 + */ +int main(int argc, char **argv) +{ + DedicatedServerConfig config; + config.port = WIN64_NET_DEFAULT_PORT; + strncpy_s(config.bindIP, sizeof(config.bindIP), "0.0.0.0", _TRUNCATE); + strncpy_s(config.name, sizeof(config.name), "DedicatedServer", _TRUNCATE); + config.maxPlayers = MINECRAFT_NET_MAX_PLAYERS; + config.worldSize = e_worldSize_Classic; + config.worldSizeChunks = LEVEL_WIDTH_CLASSIC; + config.worldHellScale = HELL_LEVEL_SCALE_CLASSIC; + config.seed = 0; + config.logLevel = ServerRuntime::eServerLogLevel_Info; + config.hasSeed = false; + config.showHelp = false; + + SetConsoleCtrlHandler(ConsoleCtrlHandlerProc, TRUE); + SetExeWorkingDirectory(); + + // Load base settings from server.properties, then override with CLI values when provided + ServerPropertiesConfig serverProperties = LoadServerPropertiesConfig(); + ApplyServerPropertiesToDedicatedConfig(serverProperties, &config); + + if (!ParseCommandLine(argc, argv, &config)) + { + PrintUsage(); + return 1; + } + if (config.showHelp) + { + PrintUsage(); + return 0; + } + + SetServerLogLevel(config.logLevel); + LogStartupStep("initializing process state"); + AccessShutdownGuard accessShutdownGuard; + + g_iScreenWidth = 1280; + g_iScreenHeight = 720; + + strncpy_s(g_Win64Username, sizeof(g_Win64Username), config.name, _TRUNCATE); + MultiByteToWideChar(CP_ACP, 0, g_Win64Username, -1, g_Win64UsernameW, 17); + + g_Win64MultiplayerHost = true; + g_Win64MultiplayerJoin = false; + g_Win64MultiplayerPort = config.port; + strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), config.bindIP, _TRUNCATE); + g_Win64DedicatedServer = true; + g_Win64DedicatedServerPort = config.port; + strncpy_s(g_Win64DedicatedServerBindIP, sizeof(g_Win64DedicatedServerBindIP), config.bindIP, _TRUNCATE); + g_Win64DedicatedServerLanAdvertise = serverProperties.lanAdvertise; + LogStartupStep("initializing server log manager"); + ServerRuntime::ServerLogManager::Initialize(); + LogStartupStep("initializing dedicated access control"); + if (!ServerRuntime::Access::Initialize(".", serverProperties.whiteListEnabled)) + { + LogError("startup", "Failed to initialize dedicated server access control."); + return 2; + } + accessShutdownGuard.Activate(); + LogInfof("startup", "LAN advertise: %s", serverProperties.lanAdvertise ? "enabled" : "disabled"); + LogInfof("startup", "Whitelist: %s", serverProperties.whiteListEnabled ? "enabled" : "disabled"); + LogInfof("startup", "Spawn protection radius: %d", serverProperties.spawnProtectionRadius); +#ifdef _LARGE_WORLDS + LogInfof( + "startup", + "World size preset: %d (xz=%d, hell-scale=%d)", + config.worldSize, + config.worldSizeChunks, + config.worldHellScale); +#endif + + LogStartupStep("registering hidden window class"); + HINSTANCE hInstance = GetModuleHandle(NULL); + MyRegisterClass(hInstance); + + LogStartupStep("creating hidden window"); + if (!InitInstance(hInstance, SW_HIDE)) + { + LogError("startup", "Failed to create window instance."); + + return 2; + } + ShowWindow(g_hWnd, SW_HIDE); + + LogStartupStep("initializing graphics device wrappers"); + if (FAILED(InitDevice())) + { + LogError("startup", "Failed to initialize D3D device."); + CleanupDevice(); + + return 2; + } + + LogStartupStep("loading media/string tables"); + app.loadMediaArchive(); + RenderManager.Initialise(g_pd3dDevice, g_pSwapChain); + app.loadStringTable(); + ui.init(g_pd3dDevice, g_pImmediateContext, g_pRenderTargetView, g_pDepthStencilView, g_iScreenWidth, g_iScreenHeight); + + InputManager.Initialise(1, 3, MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); + g_KBMInput.Init(); + DefineActions(); + InputManager.SetJoypadMapVal(0, 0); + InputManager.SetKeyRepeatRate(0.3f, 0.2f); + + ProfileManager.Initialise( + TITLEID_MINECRAFT, + app.m_dwOfferID, + PROFILE_VERSION_10, + kProfileValueCount, + kProfileSettingCount, + dwProfileSettingsA, + app.GAME_DEFINED_PROFILE_DATA_BYTES * XUSER_MAX_COUNT, + &app.uiGameDefinedDataChangedBitmask); + ProfileManager.SetDefaultOptionsCallback(&CConsoleMinecraftApp::DefaultOptionsCallback, (LPVOID)&app); + ProfileManager.SetDebugFullOverride(true); + + LogStartupStep("initializing network manager"); + g_NetworkManager.Initialise(); + + for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) + { + IQNet::m_player[i].m_smallId = (BYTE)i; + IQNet::m_player[i].m_isRemote = false; + IQNet::m_player[i].m_isHostPlayer = (i == 0); + swprintf_s(IQNet::m_player[i].m_gamertag, 32, L"Player%d", i); + } + wcscpy_s(IQNet::m_player[0].m_gamertag, 32, g_Win64UsernameW); + WinsockNetLayer::Initialize(); + + Tesselator::CreateNewThreadStorage(1024 * 1024); + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::CreateNewThreadStorage(); + OldChunkStorage::CreateNewThreadStorage(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); + + LogStartupStep("creating Minecraft singleton"); + Minecraft::main(); + Minecraft *minecraft = Minecraft::GetInstance(); + if (minecraft == NULL) + { + LogError("startup", "Minecraft initialization failed."); + CleanupDevice(); + + return 3; + } + + app.InitGameSettings(); + + MinecraftServer::resetFlags(); + app.SetTutorialMode(false); + app.SetCorruptSaveDeleted(false); + app.SetGameHostOption(eGameHostOption_Difficulty, serverProperties.difficulty); + app.SetGameHostOption(eGameHostOption_FriendsOfFriends, serverProperties.friendsOfFriends ? 1 : 0); + app.SetGameHostOption(eGameHostOption_Gamertags, serverProperties.gamertags ? 1 : 0); + app.SetGameHostOption(eGameHostOption_BedrockFog, serverProperties.bedrockFog ? 1 : 0); + app.SetGameHostOption(eGameHostOption_GameType, serverProperties.gameMode); + app.SetGameHostOption(eGameHostOption_LevelType, serverProperties.levelTypeFlat ? 1 : 0); + app.SetGameHostOption(eGameHostOption_Structures, serverProperties.generateStructures ? 1 : 0); + app.SetGameHostOption(eGameHostOption_BonusChest, serverProperties.bonusChest ? 1 : 0); + app.SetGameHostOption(eGameHostOption_PvP, serverProperties.pvp ? 1 : 0); + app.SetGameHostOption(eGameHostOption_TrustPlayers, serverProperties.trustPlayers ? 1 : 0); + app.SetGameHostOption(eGameHostOption_FireSpreads, serverProperties.fireSpreads ? 1 : 0); + app.SetGameHostOption(eGameHostOption_TNT, serverProperties.tnt ? 1 : 0); + app.SetGameHostOption( + eGameHostOption_CheatsEnabled, + (serverProperties.hostCanFly || serverProperties.hostCanChangeHunger || serverProperties.hostCanBeInvisible) ? 1 : 0); + app.SetGameHostOption(eGameHostOption_HostCanFly, serverProperties.hostCanFly ? 1 : 0); + app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, serverProperties.hostCanChangeHunger ? 1 : 0); + app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, serverProperties.hostCanBeInvisible ? 1 : 0); + app.SetGameHostOption(eGameHostOption_DisableSaving, serverProperties.disableSaving ? 1 : 0); + app.SetGameHostOption(eGameHostOption_MobGriefing, serverProperties.mobGriefing ? 1 : 0); + app.SetGameHostOption(eGameHostOption_KeepInventory, serverProperties.keepInventory ? 1 : 0); + app.SetGameHostOption(eGameHostOption_DoMobSpawning, serverProperties.doMobSpawning ? 1 : 0); + app.SetGameHostOption(eGameHostOption_DoMobLoot, serverProperties.doMobLoot ? 1 : 0); + app.SetGameHostOption(eGameHostOption_DoTileDrops, serverProperties.doTileDrops ? 1 : 0); + app.SetGameHostOption(eGameHostOption_NaturalRegeneration, serverProperties.naturalRegeneration ? 1 : 0); + app.SetGameHostOption(eGameHostOption_DoDaylightCycle, serverProperties.doDaylightCycle ? 1 : 0); +#ifdef _LARGE_WORLDS + app.SetGameHostOption(eGameHostOption_WorldSize, serverProperties.worldSize); + // Apply desired target size for loading existing worlds. + // Expansion happens only when target size is larger than current level size. + app.SetGameNewWorldSize(serverProperties.worldSizeChunks, true); + app.SetGameNewHellScale(serverProperties.worldHellScale); +#endif + + StorageManager.SetSaveDisabled(serverProperties.disableSaving); + // Read world name and fixed save-id from server.properties + // Delegate load-vs-create decision to WorldManager + std::wstring targetWorldName = serverProperties.worldName; + if (targetWorldName.empty()) + { + targetWorldName = L"world"; // Default world name + } + WorldBootstrapResult worldBootstrap = BootstrapWorldForServer(serverProperties, kServerActionPad, &TickCoreSystems); + if (worldBootstrap.status == eWorldBootstrap_Loaded) + { + const std::string &loadedSaveFilename = worldBootstrap.resolvedSaveId; + if (!loadedSaveFilename.empty() && _stricmp(loadedSaveFilename.c_str(), serverProperties.worldSaveId.c_str()) != 0) + { + // Persist the actually loaded save-id back to config + // Keep lookup keys aligned for next startup + LogWorldIO("updating level-id to loaded save filename"); + serverProperties.worldSaveId = loadedSaveFilename; + if (!SaveServerPropertiesConfig(serverProperties)) + { + LogWorldIO("failed to persist updated level-id"); + } + } + } + else if (worldBootstrap.status == eWorldBootstrap_Failed) + { + LogErrorf("world-io", "Failed to load configured world \"%s\".", WideToUtf8(targetWorldName).c_str()); + WinsockNetLayer::Shutdown(); + g_NetworkManager.Terminate(); + CleanupDevice(); + + return 4; + } + + NetworkGameInitData *param = new NetworkGameInitData(); + if (config.hasSeed) + { + param->seed = config.seed; + } + else + { + param->seed = (new Random())->nextLong(); + } +#ifdef _LARGE_WORLDS + param->xzSize = (unsigned int)config.worldSizeChunks; + param->hellScale = (unsigned char)config.worldHellScale; +#endif + param->saveData = worldBootstrap.saveData; + param->settings = app.GetGameHostOption(eGameHostOption_All); + param->dedicatedNoLocalHostPlayer = true; + + LogStartupStep("starting hosted network game thread"); + g_NetworkManager.HostGame(0, true, false, (unsigned char)config.maxPlayers, 0); + g_NetworkManager.FakeLocalPlayerJoined(); + + C4JThread *startThread = new C4JThread(&CGameNetworkManager::RunNetworkGameThreadProc, (LPVOID)param, "RunNetworkGame"); + startThread->Run(); + + while (startThread->isRunning() && !IsShutdownRequested()) + { + TickCoreSystems(); + Sleep(10); + } + + startThread->WaitForCompletion(INFINITE); + int startupResult = startThread->GetExitCode(); + delete startThread; + + if (startupResult != 0) + { + LogErrorf("startup", "Failed to start dedicated server (code %d).", startupResult); + WinsockNetLayer::Shutdown(); + g_NetworkManager.Terminate(); + CleanupDevice(); + + return 4; + } + + LogStartupStep("server startup complete"); + LogInfof("startup", "Dedicated server listening on %s:%d", g_Win64MultiplayerIP, g_Win64MultiplayerPort); + if (worldBootstrap.status == eWorldBootstrap_CreatedNew && !IsShutdownRequested() && !app.m_bShutdown) + { + // Windows64 suppresses saveToDisc right after new world creation + // Dedicated Server explicitly runs the initial save here + LogWorldIO("requesting initial save for newly created world"); + WaitForWorldActionIdle(kServerActionPad, 5000, &TickCoreSystems, &HandleXuiActions); + app.SetXuiServerAction(kServerActionPad, eXuiServerAction_AutoSaveGame); + if (!WaitForWorldActionIdle(kServerActionPad, 30000, &TickCoreSystems, &HandleXuiActions)) + { + LogWorldIO("initial save timed out"); + LogWarn("world-io", "Timed out waiting for initial save action to finish."); + } + else + { + LogWorldIO("initial save completed"); + } + } + DWORD autosaveIntervalMs = kDefaultAutosaveIntervalMs; + if (serverProperties.autosaveIntervalSeconds > 0) + { + autosaveIntervalMs = (DWORD)(serverProperties.autosaveIntervalSeconds * 1000); + } + DWORD nextAutosaveTick = GetTickCount() + autosaveIntervalMs; + bool autosaveRequested = false; + ServerRuntime::ServerCli serverCli; + serverCli.Start(); + + while (!IsShutdownRequested() && !app.m_bShutdown) + { + TickCoreSystems(); + HandleXuiActions(); + serverCli.Poll(); + + if (IsShutdownRequested() || app.m_bShutdown) + { + break; + } + + if (autosaveRequested && app.GetXuiServerAction(kServerActionPad) == eXuiServerAction_Idle) + { + LogWorldIO("autosave completed"); + autosaveRequested = false; + } + + if (MinecraftServer::serverHalted()) + { + break; + } + + DWORD now = GetTickCount(); + if ((LONG)(now - nextAutosaveTick) >= 0) + { + if (app.GetXuiServerAction(kServerActionPad) == eXuiServerAction_Idle) + { + LogWorldIO("requesting autosave"); + app.SetXuiServerAction(kServerActionPad, eXuiServerAction_AutoSaveGame); + autosaveRequested = true; + } + nextAutosaveTick = now + autosaveIntervalMs; + } + + Sleep(10); + } + serverCli.Stop(); + app.m_bShutdown = true; + + LogInfof("shutdown", "Dedicated server stopped"); + MinecraftServer *server = MinecraftServer::getInstance(); + if (server != NULL) + { + server->setSaveOnExit(true); + } + if (server != NULL) + { + LogWorldIO("requesting save before shutdown"); + LogWorldIO("using saveOnExit for shutdown"); + } + + MinecraftServer::HaltServer(); + + if (g_NetworkManager.ServerStoppedValid()) + { + C4JThread waitThread(&WaitForServerStoppedThreadProc, NULL, "WaitServerStopped"); + waitThread.Run(); + waitThread.WaitForCompletion(INFINITE); + } + + LogInfof("shutdown", "Cleaning up and exiting."); + WinsockNetLayer::Shutdown(); + LogDebugf("shutdown", "Network layer shutdown complete."); + g_NetworkManager.Terminate(); + LogDebugf("shutdown", "Network manager terminated."); + ServerRuntime::ServerLogManager::Shutdown(); + CleanupDevice(); + + + return 0; +} + diff --git a/Minecraft.Server/Windows64/postbuild_server.ps1 b/Minecraft.Server/Windows64/postbuild_server.ps1 new file mode 100644 index 000000000..27451ba2e --- /dev/null +++ b/Minecraft.Server/Windows64/postbuild_server.ps1 @@ -0,0 +1,65 @@ +param( + [string]$OutDir, + [string]$ProjectRoot, + [string]$Configuration +) + +if ([string]::IsNullOrWhiteSpace($OutDir)) { + throw "OutDir is required." +} + +if ([string]::IsNullOrWhiteSpace($ProjectRoot)) { + $ProjectRoot = Resolve-Path (Join-Path $PSScriptRoot "..\\..") +} + +if ([string]::IsNullOrWhiteSpace($Configuration)) { + $Configuration = "Debug" +} + +$OutDir = [System.IO.Path]::GetFullPath($OutDir) +$ProjectRoot = [System.IO.Path]::GetFullPath($ProjectRoot) +$ClientRoot = Join-Path $ProjectRoot "Minecraft.Client" + +Write-Host "Server post-build started. OutDir: $OutDir" + +function Ensure-Dir([string]$path) { + if (-not (Test-Path $path)) { + New-Item -ItemType Directory -Path $path -Force | Out-Null + } +} + +function Copy-Tree-IfExists([string]$src, [string]$dst) { + if (Test-Path $src) { + Ensure-Dir $dst + xcopy /q /y /i /s /e /d "$src" "$dst" 2>$null | Out-Null + } +} + +function Copy-File-IfExists([string]$src, [string]$dst) { + if (Test-Path $src) { + $dstDir = Split-Path -Parent $dst + Ensure-Dir $dstDir + xcopy /q /y /d "$src" "$dstDir" 2>$null | Out-Null + } +} + +function Copy-FirstExisting([string[]]$candidates, [string]$dstFile) { + foreach ($candidate in $candidates) { + if (Test-Path $candidate) { + Copy-File-IfExists $candidate $dstFile + return + } + } +} + +# Dedicated server only needs core resources for current startup path. +Copy-File-IfExists (Join-Path $ClientRoot "Common\\Media\\MediaWindows64.arc") (Join-Path $OutDir "Common\\Media\\MediaWindows64.arc") +Copy-Tree-IfExists (Join-Path $ClientRoot "Common\\res") (Join-Path $OutDir "Common\\res") +Copy-Tree-IfExists (Join-Path $ClientRoot "Windows64\\GameHDD") (Join-Path $OutDir "Windows64\\GameHDD") + +# Runtime DLLs. +Copy-FirstExisting @( + (Join-Path $ClientRoot "Windows64\\Iggy\\lib\\redist64\\iggy_w64.dll"), + (Join-Path $ProjectRoot ("x64\\{0}\\iggy_w64.dll" -f $Configuration)) +) (Join-Path $OutDir "iggy_w64.dll") + diff --git a/Minecraft.Server/WorldManager.cpp b/Minecraft.Server/WorldManager.cpp new file mode 100644 index 000000000..b9ec3dd90 --- /dev/null +++ b/Minecraft.Server/WorldManager.cpp @@ -0,0 +1,641 @@ +#include "stdafx.h" + +#include "WorldManager.h" + +#include "Minecraft.h" +#include "MinecraftServer.h" +#include "ServerLogger.h" +#include "Common\\StringUtils.h" + +#include +#include + +namespace ServerRuntime +{ +using StringUtils::Utf8ToWide; +using StringUtils::WideToUtf8; + +enum EWorldSaveLoadResult +{ + eWorldSaveLoad_Loaded, + eWorldSaveLoad_NotFound, + eWorldSaveLoad_Failed +}; + +struct SaveInfoQueryContext +{ + bool done; + bool success; + SAVE_DETAILS *details; + + SaveInfoQueryContext() + : done(false) + , success(false) + , details(NULL) + { + } +}; + +struct SaveDataLoadContext +{ + bool done; + bool isCorrupt; + bool isOwner; + + SaveDataLoadContext() + : done(false) + , isCorrupt(true) + , isOwner(false) + { + } +}; + +/** + * **Apply Save ID To StorageManager** + * + * Applies the configured save destination ID (`level-id`) to `StorageManager` + * - Re-applies the same ID at startup and before save to avoid destination drift + * - Ignores empty values as invalid + * - For some reason, a date-based world file occasionally appears after a debug build, but the cause is unknown. + * 保存先IDの適用処理 + * + * @param saveFilename Normalized save destination ID + */ +static void SetStorageSaveUniqueFilename(const std::string &saveFilename) +{ + if (saveFilename.empty()) + { + return; + } + + char filenameBuffer[64] = {}; + strncpy_s(filenameBuffer, sizeof(filenameBuffer), saveFilename.c_str(), _TRUNCATE); + StorageManager.SetSaveUniqueFilename(filenameBuffer); +} + +static void LogSaveFilename(const char *prefix, const std::string &saveFilename) +{ + LogInfof("world-io", "%s: %s", (prefix != NULL) ? prefix : "save-filename", saveFilename.c_str()); +} + +/** + * Verifies a directory exists and creates it when missing + * - Treats an existing non-directory path as failure + * - Returns whether the directory had to be created + * ディレクトリ存在保証の補助処理 + */ +static bool EnsureDirectoryExists(const std::wstring &directoryPath, bool *outCreated) +{ + if (outCreated != NULL) + { + *outCreated = false; + } + if (directoryPath.empty()) + { + return false; + } + + DWORD attrs = GetFileAttributesW(directoryPath.c_str()); + if (attrs != INVALID_FILE_ATTRIBUTES) + { + if ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0) + { + return true; + } + + LogErrorf("world-io", "path exists but is not a directory: %s", WideToUtf8(directoryPath).c_str()); + return false; + } + + if (CreateDirectoryW(directoryPath.c_str(), NULL)) + { + if (outCreated != NULL) + { + *outCreated = true; + } + return true; + } + + DWORD error = GetLastError(); + if (error == ERROR_ALREADY_EXISTS) + { + attrs = GetFileAttributesW(directoryPath.c_str()); + if (attrs != INVALID_FILE_ATTRIBUTES && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) + { + return true; + } + } + + LogErrorf( + "world-io", + "failed to create directory %s (error=%lu)", + WideToUtf8(directoryPath).c_str(), + (unsigned long)error); + return false; +} + +/** + * Prepares the save root used by the Windows64 storage layout + * - Creates `Windows64` first because `CreateDirectoryW` is not recursive + * - Creates `Windows64\\GameHDD` when missing before world bootstrap starts + * Windows64用保存先ディレクトリの存在保証 + */ +static bool EnsureGameHddRootExists() +{ + bool windows64Created = false; + if (!EnsureDirectoryExists(L"Windows64", &windows64Created)) + { + return false; + } + + bool gameHddCreated = false; + if (!EnsureDirectoryExists(L"Windows64\\GameHDD", &gameHddCreated)) + { + return false; + } + + if (windows64Created || gameHddCreated) + { + LogWorldIO("created missing Windows64\\GameHDD storage directories"); + } + + return true; +} + +static void LogEnumeratedSaveInfo(int index, const SAVE_INFO &saveInfo) +{ + std::wstring title = Utf8ToWide(saveInfo.UTF8SaveTitle); + std::wstring filename = Utf8ToWide(saveInfo.UTF8SaveFilename); + std::string titleUtf8 = WideToUtf8(title); + std::string filenameUtf8 = WideToUtf8(filename); + + char logLine[512] = {}; + sprintf_s( + logLine, + sizeof(logLine), + "save[%d] title=\"%s\" filename=\"%s\"", + index, + titleUtf8.c_str(), + filenameUtf8.c_str()); + LogDebug("world-io", logLine); +} + +/** + * **Save List Callback** + * + * Captures async save-list results into `SaveInfoQueryContext` and marks completion for the waiter + * セーブ一覧取得の完了通知 + */ +static int GetSavesInfoCallbackProc(LPVOID lpParam, SAVE_DETAILS *pSaveDetails, const bool bRes) +{ + SaveInfoQueryContext *context = (SaveInfoQueryContext *)lpParam; + if (context != NULL) + { + context->details = pSaveDetails; + context->success = bRes; + context->done = true; + } + return 0; +} + +/** + * **Save Data Load Callback** + * + * Writes load results such as corruption status into `SaveDataLoadContext` + * セーブ読み込み結果の反映 + */ +static int LoadSaveDataCallbackProc(LPVOID lpParam, const bool bIsCorrupt, const bool bIsOwner) +{ + SaveDataLoadContext *context = (SaveDataLoadContext *)lpParam; + if (context != NULL) + { + context->isCorrupt = bIsCorrupt; + context->isOwner = bIsOwner; + context->done = true; + } + return 0; +} + +/** + * **Wait For Save List Completion** + * + * Waits until save-list retrieval completes + * - Prefers callback completion as the primary signal + * - Also falls back to polling because some environments populate `ReturnSavesInfo()` before callback + * セーブ一覧待機の補助処理 + * + * @return `true` when completion is detected + */ +static bool WaitForSaveInfoResult(SaveInfoQueryContext *context, DWORD timeoutMs, WorldManagerTickProc tickProc) +{ + DWORD start = GetTickCount(); + while ((GetTickCount() - start) < timeoutMs) + { + if (context->done) + { + return true; + } + + if (context->details == NULL) + { + // Some implementations fill ReturnSavesInfo before the callback + // Keep polling as a fallback instead of relying only on callback completion + SAVE_DETAILS *details = StorageManager.ReturnSavesInfo(); + if (details != NULL) + { + context->details = details; + context->success = true; + context->done = true; + return true; + } + } + + if (tickProc != NULL) + { + tickProc(); + } + Sleep(10); + } + + return context->done; +} + +/** + * **Wait For Save Data Load Completion** + * + * Waits for the save-data load callback to complete + * セーブ本体の読み込み待機 + * + * @return `true` when callback is reached, `false` on timeout + */ +static bool WaitForSaveLoadResult(SaveDataLoadContext *context, DWORD timeoutMs, WorldManagerTickProc tickProc) +{ + DWORD start = GetTickCount(); + while ((GetTickCount() - start) < timeoutMs) + { + if (context->done) + { + return true; + } + + if (tickProc != NULL) + { + tickProc(); + } + Sleep(10); + } + + return context->done; +} + +/** + * **Match SAVE_INFO By World Name** + * + * Compares both save title and save filename against the target world name + * ワールド名一致判定 + */ +static bool SaveInfoMatchesWorldName(const SAVE_INFO &saveInfo, const std::wstring &targetWorldName) +{ + if (targetWorldName.empty()) + { + return false; + } + + std::wstring saveTitle = Utf8ToWide(saveInfo.UTF8SaveTitle); + std::wstring saveFilename = Utf8ToWide(saveInfo.UTF8SaveFilename); + + if (!saveTitle.empty() && (_wcsicmp(saveTitle.c_str(), targetWorldName.c_str()) == 0)) + { + return true; + } + if (!saveFilename.empty() && (_wcsicmp(saveFilename.c_str(), targetWorldName.c_str()) == 0)) + { + return true; + } + + return false; +} + +/** + * **Match SAVE_INFO By Save Filename** + * + * Checks whether `SAVE_INFO` matches by save destination ID (`UTF8SaveFilename`) + * 保存先ID一致判定 + */ +static bool SaveInfoMatchesSaveFilename(const SAVE_INFO &saveInfo, const std::string &targetSaveFilename) +{ + if (targetSaveFilename.empty() || saveInfo.UTF8SaveFilename[0] == 0) + { + return false; + } + + return (_stricmp(saveInfo.UTF8SaveFilename, targetSaveFilename.c_str()) == 0); +} + +/** + * **Apply World Identity To Storage** + * + * Applies world identity (`level-name` + `level-id`) to storage + * - Always sets both display name and ID to avoid partial configuration + * - Helps prevent unintended new save destinations across environment differences + * 保存先と表示名の同期処理 + */ +static void ApplyWorldStorageTarget(const std::wstring &worldName, const std::string &saveId) +{ + // Set both title (display name) and save ID (actual folder name) explicitly + // Setting only one side can create unexpected new save targets in some environments + StorageManager.SetSaveTitle(worldName.c_str()); + SetStorageSaveUniqueFilename(saveId); +} + +/** + * **Prepare World Save Data For Startup** + * + * Searches for a save matching the target world and extracts startup payload when found + * Match priority: + * 1. Exact match by `level-id` (`UTF8SaveFilename`) + * 2. Fallback match by `level-name` against title or filename + * ワールド一致セーブの探索処理 + * + * @return + * - `eWorldSaveLoad_Loaded`: Existing save loaded successfully + * - `eWorldSaveLoad_NotFound`: No matching save found + * - `eWorldSaveLoad_Failed`: API failure, corruption, or invalid data + */ +static EWorldSaveLoadResult PrepareWorldSaveData( + const std::wstring &targetWorldName, + const std::string &targetSaveFilename, + int actionPad, + WorldManagerTickProc tickProc, + LoadSaveDataThreadParam **outSaveData, + std::string *outResolvedSaveFilename) +{ + if (outSaveData == NULL) + { + return eWorldSaveLoad_Failed; + } + *outSaveData = NULL; + if (outResolvedSaveFilename != NULL) + { + outResolvedSaveFilename->clear(); + } + + LogWorldIO("enumerating saves for configured world"); + StorageManager.ClearSavesInfo(); + + SaveInfoQueryContext infoContext; + int infoState = StorageManager.GetSavesInfo(actionPad, &GetSavesInfoCallbackProc, &infoContext, "save"); + if (infoState == C4JStorage::ESaveGame_Idle) + { + infoContext.done = true; + infoContext.success = true; + infoContext.details = StorageManager.ReturnSavesInfo(); + } + else if (infoState != C4JStorage::ESaveGame_GetSavesInfo) + { + LogWorldIO("GetSavesInfo failed to start"); + return eWorldSaveLoad_Failed; + } + + if (!WaitForSaveInfoResult(&infoContext, 10000, tickProc)) + { + LogWorldIO("timed out waiting for save list"); + return eWorldSaveLoad_Failed; + } + + if (infoContext.details == NULL) + { + infoContext.details = StorageManager.ReturnSavesInfo(); + } + if (infoContext.details == NULL) + { + LogWorldIO("failed to retrieve save list"); + return eWorldSaveLoad_Failed; + } + + int matchedIndex = -1; + if (!targetSaveFilename.empty()) + { + // 1) If save ID is provided, search by it first + // This is the most stable way to reuse the same world target + for (int i = 0; i < infoContext.details->iSaveC; ++i) + { + LogEnumeratedSaveInfo(i, infoContext.details->SaveInfoA[i]); + if (SaveInfoMatchesSaveFilename(infoContext.details->SaveInfoA[i], targetSaveFilename)) + { + matchedIndex = i; + break; + } + } + } + + if (matchedIndex < 0 && targetSaveFilename.empty()) + { + for (int i = 0; i < infoContext.details->iSaveC; ++i) + { + LogEnumeratedSaveInfo(i, infoContext.details->SaveInfoA[i]); + } + } + + for (int i = 0; i < infoContext.details->iSaveC; ++i) + { + // 2) If no save matched by ID, try compatibility fallback + // Match worldName against save title or save filename + if (matchedIndex >= 0) + { + break; + } + if (SaveInfoMatchesWorldName(infoContext.details->SaveInfoA[i], targetWorldName)) + { + matchedIndex = i; + break; + } + } + + if (matchedIndex < 0) + { + LogWorldIO("no save matched configured world name"); + return eWorldSaveLoad_NotFound; + } + + std::wstring matchedTitle = Utf8ToWide(infoContext.details->SaveInfoA[matchedIndex].UTF8SaveTitle); + if (matchedTitle.empty()) + { + matchedTitle = targetWorldName; + } + LogWorldName("matched save title", matchedTitle); + SAVE_INFO *matchedSaveInfo = &infoContext.details->SaveInfoA[matchedIndex]; + std::wstring matchedFilename = Utf8ToWide(matchedSaveInfo->UTF8SaveFilename); + if (!matchedFilename.empty()) + { + LogWorldName("matched save filename", matchedFilename); + } + + ApplyWorldStorageTarget(targetWorldName, targetSaveFilename); + + std::string resolvedSaveFilename; + if (matchedSaveInfo->UTF8SaveFilename[0] != 0) + { + // Prefer the save ID that was actually matched, then keep using it for future saves + resolvedSaveFilename = matchedSaveInfo->UTF8SaveFilename; + SetStorageSaveUniqueFilename(resolvedSaveFilename); + } + else if (!targetSaveFilename.empty()) + { + resolvedSaveFilename = targetSaveFilename; + } + + if (outResolvedSaveFilename != NULL) + { + *outResolvedSaveFilename = resolvedSaveFilename; + } + + SaveDataLoadContext loadContext; + int loadState = StorageManager.LoadSaveData(matchedSaveInfo, &LoadSaveDataCallbackProc, &loadContext); + if (loadState != C4JStorage::ESaveGame_Load && loadState != C4JStorage::ESaveGame_Idle) + { + LogWorldIO("LoadSaveData failed to start"); + return eWorldSaveLoad_Failed; + } + + if (loadState == C4JStorage::ESaveGame_Load) + { + if (!WaitForSaveLoadResult(&loadContext, 15000, tickProc)) + { + LogWorldIO("timed out waiting for save data load"); + return eWorldSaveLoad_Failed; + } + if (loadContext.isCorrupt) + { + LogWorldIO("target save is corrupt; aborting load"); + return eWorldSaveLoad_Failed; + } + } + + unsigned int saveSize = StorageManager.GetSaveSize(); + if (saveSize == 0) + { + // Treat zero-byte payload as failure even when load API reports success + LogWorldIO("loaded save has zero size"); + return eWorldSaveLoad_Failed; + } + + byteArray loadedSaveData(saveSize, false); + unsigned int loadedSize = saveSize; + StorageManager.GetSaveData(loadedSaveData.data, &loadedSize); + if (loadedSize == 0) + { + LogWorldIO("failed to copy loaded save data from storage manager"); + return eWorldSaveLoad_Failed; + } + + *outSaveData = new LoadSaveDataThreadParam(loadedSaveData.data, loadedSize, matchedTitle); + LogWorldIO("prepared save data payload for server startup"); + return eWorldSaveLoad_Loaded; +} + +/** + * **Bootstrap World State For Server Startup** + * + * Determines final world startup state + * - Returns loaded save data when an existing save is found + * - Prepares a new world context when not found + * - Returns `Failed` when startup should be aborted + * サーバー起動時のワールド確定処理 + */ +WorldBootstrapResult BootstrapWorldForServer( + const ServerPropertiesConfig &config, + int actionPad, + WorldManagerTickProc tickProc) +{ + WorldBootstrapResult result; + if (!EnsureGameHddRootExists()) + { + LogWorldIO("failed to prepare Windows64\\GameHDD storage root"); + return result; + } + + std::wstring targetWorldName = config.worldName; + std::string targetSaveFilename = config.worldSaveId; + if (targetWorldName.empty()) + { + targetWorldName = L"world"; + } + + LogWorldName("configured level-name", targetWorldName); + if (!targetSaveFilename.empty()) + { + LogSaveFilename("configured level-id", targetSaveFilename); + } + + ApplyWorldStorageTarget(targetWorldName, targetSaveFilename); + + std::string loadedSaveFilename; + EWorldSaveLoadResult worldLoadResult = PrepareWorldSaveData( + targetWorldName, + targetSaveFilename, + actionPad, + tickProc, + &result.saveData, + &loadedSaveFilename); + if (worldLoadResult == eWorldSaveLoad_Loaded) + { + result.status = eWorldBootstrap_Loaded; + result.resolvedSaveId = loadedSaveFilename; + LogStartupStep("loading configured world from save data"); + } + else if (worldLoadResult == eWorldSaveLoad_NotFound) + { + // Create a new context only when no matching save exists + // Fix saveId here so the next startup writes to the same location + result.status = eWorldBootstrap_CreatedNew; + result.resolvedSaveId = targetSaveFilename; + LogStartupStep("configured world not found; creating new world"); + LogWorldIO("creating new world save context"); + StorageManager.ResetSaveData(); + ApplyWorldStorageTarget(targetWorldName, targetSaveFilename); + } + else + { + result.status = eWorldBootstrap_Failed; + } + + return result; +} + +/** + * **Wait Until Server XUI Action Is Idle** + * + * Keeps tick/handle running during save action so async processing does not stall + * XUIアクション待機中の進行維持処理 + */ +bool WaitForWorldActionIdle( + int actionPad, + DWORD timeoutMs, + WorldManagerTickProc tickProc, + WorldManagerHandleActionsProc handleActionsProc) +{ + DWORD start = GetTickCount(); + while (app.GetXuiServerAction(actionPad) != eXuiServerAction_Idle && !MinecraftServer::serverHalted()) + { + // Keep network and storage progressing while waiting + // If this stops, save action itself may stall and time out + if (tickProc != NULL) + { + tickProc(); + } + if (handleActionsProc != NULL) + { + handleActionsProc(); + } + if ((GetTickCount() - start) >= timeoutMs) + { + return false; + } + Sleep(10); + } + + return (app.GetXuiServerAction(actionPad) == eXuiServerAction_Idle); +} +} + diff --git a/Minecraft.Server/WorldManager.h b/Minecraft.Server/WorldManager.h new file mode 100644 index 000000000..a4a8e77b1 --- /dev/null +++ b/Minecraft.Server/WorldManager.h @@ -0,0 +1,92 @@ +#pragma once + +#include +#include + +#include "ServerProperties.h" + +struct _LoadSaveDataThreadParam; +typedef struct _LoadSaveDataThreadParam LoadSaveDataThreadParam; + +namespace ServerRuntime +{ + /** Tick callback used while waiting on async storage/network work */ + typedef void (*WorldManagerTickProc)(); + /** Optional action handler used while waiting for server actions */ + typedef void (*WorldManagerHandleActionsProc)(); + + /** + * **World Bootstrap Status** + * + * Result type for world startup preparation, either loading an existing world or creating a new one + * ワールド起動準備の結果種別 + */ + enum EWorldBootstrapStatus + { + /** Found and loaded an existing world */ + eWorldBootstrap_Loaded, + /** No matching save was found, created a new world context */ + eWorldBootstrap_CreatedNew, + /** Bootstrap failed and server startup should be aborted */ + eWorldBootstrap_Failed + }; + + /** + * **World Bootstrap Result** + * + * Output payload returned by world startup preparation + * ワールド起動準備の出力データ + */ + struct WorldBootstrapResult + { + /** Bootstrap status */ + EWorldBootstrapStatus status; + /** Save data used for server initialization, `NULL` when creating a new world */ + LoadSaveDataThreadParam *saveData; + /** Save ID that was actually selected */ + std::string resolvedSaveId; + + WorldBootstrapResult() + : status(eWorldBootstrap_Failed) + , saveData(NULL) + { + } + }; + + /** + * **Bootstrap Target World For Server Startup** + * + * Resolves whether the target world should be loaded from an existing save or created as new + * - Applies `level-name` and `level-id` from `server.properties` + * - Loads when a matching save exists + * - Creates a new world context only when no save matches + * サーバー起動時のロードか新規作成かを確定する + * + * @param config Normalized `server.properties` values + * @param actionPad padId used by async storage APIs + * @param tickProc Tick callback run while waiting for async completion + * @return Bootstrap result including whether save data was loaded + */ + WorldBootstrapResult BootstrapWorldForServer( + const ServerPropertiesConfig &config, + int actionPad, + WorldManagerTickProc tickProc); + + /** + * **Wait Until Server Action Returns To Idle** + * + * Waits until server action state reaches `Idle` + * サーバーアクションの待機処理 + * + * @param actionPad padId to monitor + * @param timeoutMs Timeout in milliseconds + * @param tickProc Tick callback run inside the wait loop + * @param handleActionsProc Optional action handler callback + * @return `true` when `Idle` is reached before timeout + */ + bool WaitForWorldActionIdle( + int actionPad, + DWORD timeoutMs, + WorldManagerTickProc tickProc, + WorldManagerHandleActionsProc handleActionsProc); +} diff --git a/Minecraft.Server/docs/DEVELOPMENT.en.md b/Minecraft.Server/docs/DEVELOPMENT.en.md new file mode 100644 index 000000000..5348f020a --- /dev/null +++ b/Minecraft.Server/docs/DEVELOPMENT.en.md @@ -0,0 +1,284 @@ +# Minecraft.Server Developer Guide (English) + +This document is for contributors who are new to `Minecraft.Server` and need a practical map for adding or modifying features safely. + +## 1. What This Server Does + +`Minecraft.Server` is the dedicated-server executable entry for this codebase. + +Core responsibilities: +- Switch the process working directory to the executable folder before relative file I/O +- Load, normalize, and repair `server.properties` +- Initialize dedicated runtime systems, connection logging, and access control +- Load or create the target world and keep `level-id` aligned with the actual save destination +- Run the dedicated main loop (network tick, XUI actions, autosave, CLI input) +- Maintain operator-facing access files such as `banned-players.json` and `banned-ips.json` +- Perform an initial save for newly created worlds and then shut down safely + +## 2. Important Files + +### Startup and Runtime +- `Windows64/ServerMain.cpp` + - `PrintUsage()` and `ParseCommandLine()` + - `SetExeWorkingDirectory()` + - Runtime setup and shutdown flow + - Initial save path for newly created worlds + - Main loop, autosave scheduler, and CLI polling + +### World Selection and Save Load +- `WorldManager.h` +- `WorldManager.cpp` + - Finds matching save by `level-id` first, then world-name fallback + - Applies storage title + save ID consistently + - Wait helpers for async storage/server action completion + +### Server Properties +- `ServerProperties.h` +- `ServerProperties.cpp` + - Default values and normalization ranges + - Parse/repair/write `server.properties` + - Exposes `ServerPropertiesConfig` + - `SaveServerPropertiesConfig()` rewrites `level-name`, `level-id`, and `white-list` + +### Access Control, Ban, and Whitelist Storage +- `Access/Access.h` +- `Access/Access.cpp` + - Process-wide access-control facade + - Published snapshot model used by console commands and login checks +- `Access/BanManager.h` +- `Access/BanManager.cpp` + - Reads/writes `banned-players.json` and `banned-ips.json` + - Normalizes identifiers and filters expired entries from snapshots +- `Access/WhitelistManager.h` +- `Access/WhitelistManager.cpp` + - Reads/writes `whitelist.json` + - Normalizes XUID-based whitelist entries used by login validation and CLI commands + +### Logging and Connection Audit +- `ServerLogger.h` +- `ServerLogger.cpp` + - Log level parsing + - Colored/timestamped console logs + - General categories such as `startup`, `world-io`, `console`, `access`, `network`, and `shutdown` +- `ServerLogManager.h` +- `ServerLogManager.cpp` + - Accepted/rejected TCP connection logs + - Login/disconnect audit logs + - Remote-IP cache used by `ban-ip ` + +### Console Command System +- `Console/ServerCli.cpp` (facade) +- `Console/ServerCliInput.cpp` (linenoise input thread + completion bridge) +- `Console/ServerCliParser.cpp` (tokenization, quoted args, completion context) +- `Console/ServerCliEngine.cpp` (dispatch, completion, helpers) +- `Console/ServerCliRegistry.cpp` (command registration + lookup) +- `Console/commands/*` (individual commands) + +## 3. End-to-End Startup Flow + +Main flow in `Windows64/ServerMain.cpp`: +1. `SetExeWorkingDirectory()` switches the current directory to the executable folder. +2. Load and normalize `server.properties` via `LoadServerPropertiesConfig()`. +3. Copy config into `DedicatedServerConfig`, then apply CLI overrides (`-port`, `-ip`/`-bind`, `-name`, `-maxplayers`, `-seed`, `-loglevel`, `-help`/`--help`/`-h`). +4. Initialize process state, `ServerLogManager`, and `Access::Initialize(".")`. +5. Initialize window/device/profile/network/thread-local systems. +6. Set host/game options from `ServerPropertiesConfig`. +7. Bootstrap world with `BootstrapWorldForServer(...)`. +8. If world bootstrap resolves a different normalized save ID, persist it with `SaveServerPropertiesConfig()`. +9. Start hosted game thread (`RunNetworkGameThreadProc`). +10. If a brand-new world was created, explicitly request one initial save. +11. Enter the main loop: + - `TickCoreSystems()` + - `HandleXuiActions()` + - `serverCli.Poll()` + - autosave scheduling +12. On shutdown: + - stop CLI input + - request save-on-exit / halt server + - wait for network shutdown completion + - terminate log, access, network, and device systems + +## 4. Current Operator Surface + +### 4.1 Launch Arguments +- `-port <1-65535>` +- `-ip ` or `-bind ` +- `-name ` (runtime max 16 chars) +- `-maxplayers <1-8>` +- `-seed ` +- `-loglevel ` +- `-help`, `--help`, `-h` + +Notes: +- CLI overrides affect only the current process. +- The only values currently written back by the server are `level-name` and `level-id`, and that happens when world bootstrap resolves identity changes. + +### 4.2 Built-in Console Commands +- `help` / `?` +- `stop` +- `list` +- `ban [reason ...]` + - currently requires the target player to be online +- `ban-ip [reason ...]` + - accepts a literal IPv4/IPv6 address or an online player's current remote IP +- `pardon ` +- `pardon-ip
` + - only accepts a literal address +- `banlist` +- `tp ` / `teleport` +- `gamemode [player]` / `gm` + +CLI behavior notes: +- Command parsing accepts both `cmd` and `/cmd`. +- Quoted arguments are supported by `ServerCliParser`. +- Completion is implemented per command via `Complete(...)`. + +### 4.3 Files Written Next to the Executable +- `server.properties` +- `banned-players.json` +- `banned-ips.json` + +This follows from `SetExeWorkingDirectory()`, so these files are resolved relative to `Minecraft.Server.exe`, not the shell directory you launched from. + +## 5. Common Development Tasks + +### 5.1 Add a New CLI Command + +Use this pattern when adding commands like `/kick`, `/time`, etc. + +1. Add files under `Console/commands/` + - `CliCommandYourCommand.h` + - `CliCommandYourCommand.cpp` +2. Implement `IServerCliCommand` + - `Name()`, `Usage()`, `Description()`, `Execute(...)` + - optional: `Aliases()` and `Complete(...)` +3. Register the command in `ServerCliEngine::RegisterDefaultCommands()`. +4. Add source/header to build definitions: + - `CMakeLists.txt` (`MINECRAFT_SERVER_SOURCES`) + - `Minecraft.Server/Minecraft.Server.vcxproj` (`` / ``) +5. Manual verify: + - command appears in `help` + - command executes correctly + - completion works for both `cmd` and `/cmd` + - quoted arguments behave as expected + +Implementation references: +- `CliCommandHelp.cpp` for a simple no-arg command +- `CliCommandTp.cpp` for multi-arg + completion + runtime checks +- `CliCommandGamemode.cpp` for argument parsing and aliases +- `CliCommandBanIp.cpp` for access-backed behavior with connection metadata + +### 5.2 Add or Change a `server.properties` Key + +1. Add/update the field in `ServerPropertiesConfig` (`ServerProperties.h`). +2. Add a default entry to `kServerPropertyDefaults` (`ServerProperties.cpp`). +3. Load and normalize the value in `LoadServerPropertiesConfig()`. + - Use existing helpers for bool/int/string/int64/log level/level type. +4. If this value should be written back, update `SaveServerPropertiesConfig()`. + - Note: today that function intentionally only persists world identity. +5. Apply it to runtime where needed: + - `ApplyServerPropertiesToDedicatedConfig(...)` + - host options in `ServerMain.cpp` (`app.SetGameHostOption(...)`) + - `PrintUsage()` / `ParseCommandLine()` if the key also gets a CLI override +6. Manual verify: + - missing key regeneration + - invalid value normalization + - clamped ranges still make sense + - runtime behavior reflects the new value + +Normalization details worth remembering: +- `level-id` is normalized to a safe save ID and length-limited. +- `server-name` is capped to 16 runtime chars. +- `max-players` is clamped to `1..8`. +- `autosave-interval` is clamped to `5..3600`. +- `level-type` normalizes to `default` or `flat`. + +### 5.3 Change Ban / Access Behavior + +Primary code lives in `Access/Access.cpp`, `Access/BanManager.cpp`, and `ServerLogManager.cpp`. + +When changing this area: +- Keep `BanManager` responsible for storage/caching, not live-network policy. +- Keep the clone-and-publish snapshot pattern in `Access.cpp` so readers never block on disk I/O. +- Remember that `ban-ip ` depends on `ServerLogManager::TryGetConnectionRemoteIp(...)`. +- Keep expired entries out of `SnapshotBannedPlayers()` / `SnapshotBannedIps()` output. +- Verify: + - clean boot creates empty ban files when missing + - `ban`, `ban-ip`, `pardon`, `pardon-ip`, and `banlist` still work + - online bans disconnect live targets immediately + - manual edits still reload safely if you later add or extend reload paths + +### 5.4 Change World Load/Create Behavior + +Primary code is in `WorldManager.cpp`. + +Current matching policy: +1. Match by `level-id` (`UTF8SaveFilename`) first. +2. Fall back to world-name match on title/file name. + +When changing this logic: +- Keep `ApplyWorldStorageTarget(...)` usage consistent (title + save ID together). +- Preserve periodic ticking in wait loops (`tickProc`) to avoid async deadlocks. +- Keep timeout/error logs specific enough for diagnosis. +- Verify: + - existing world is reused correctly + - no accidental new save directory creation + - shutdown save still succeeds + - newly created worlds still get the explicit initial save from `ServerMain.cpp` + +### 5.5 Add Logging for New Feature Work + +Use `ServerLogger` helpers: +- `LogDebug`, `LogInfo`, `LogWarn`, `LogError` +- formatted variants `LogDebugf`, `LogInfof`, etc. + +Use `ServerLogManager` when the event is specifically part of the transport/login/disconnect lifecycle. + +Recommended categories: +- `startup` for init/shutdown lifecycle +- `world-io` for save/world operations +- `console` for CLI command handling +- `access` for ban/access control state +- `network` for connection/login audit + +## 6. Build and Run + +From repository root: + +```powershell +cmake -S . -B build -G "Visual Studio 17 2022" -A x64 +cmake --build build --config Debug --target MinecraftServer +cd .\build\Debug +.\Minecraft.Server.exe -port 25565 -bind 0.0.0.0 -maxplayers 8 -name DedicatedServer +``` + +Notes: +- The process switches its working directory to the executable directory at startup. +- `server.properties`, `banned-players.json`, and `banned-ips.json` are therefore read/written next to the executable. +- For Visual Studio workflow, see root `COMPILE.md`. + +## 7. Safety Checklist Before Commit + +- the server starts without crash when `server.properties` is missing or sparse +- missing access files are recreated on a clean boot +- existing world loads by expected `level-id` +- new world creation still performs the explicit initial save +- CLI input and completion remain responsive +- `banlist` output stays sane after adding/removing bans +- no busy-wait path removed from async wait loops +- both CMake and `.vcxproj` include newly added source files + +## 8. Quick Troubleshooting + +- Unknown command: + - check `RegisterDefaultCommands()` and build-file entries +- `server.properties` or ban files seem to load from the wrong folder: + - remember `SetExeWorkingDirectory()` moves the working directory to the executable folder +- Autosave or shutdown save timing out: + - confirm wait loops still call `TickCoreSystems()` and `HandleXuiActions()` where required +- World not reused on restart: + - inspect `level-id` normalization and matching logic in `WorldManager.cpp` +- `ban-ip ` cannot resolve an address: + - confirm the player is currently online and `ServerLogManager` has a cached remote IP for that connection +- Settings not applied: + - confirm the value is loaded into `ServerPropertiesConfig`, optionally copied into `DedicatedServerConfig`, and then applied in `ServerMain.cpp` diff --git a/Minecraft.Server/docs/DEVELOPMENT.ja.md b/Minecraft.Server/docs/DEVELOPMENT.ja.md new file mode 100644 index 000000000..70d05aaa4 --- /dev/null +++ b/Minecraft.Server/docs/DEVELOPMENT.ja.md @@ -0,0 +1,286 @@ +# Minecraft.Server 開発ガイド (日本語) + +この文書は、`Minecraft.Server` に新しく入る開発者が、安全に機能追加や改修を行うための実践的な地図として使うことを想定しています + +## 1. このサーバーが担うこと + +`Minecraft.Server` は、このコードベースにおける専用サーバー実行ファイルのエントリーポイントです + +主な責務: +- 相対パスのファイル I/O を行う前に、カレントディレクトリを実行ファイルのあるフォルダへ切り替える +- `server.properties` を読み込み、正規化し、不足や不正値を補完する +- 専用サーバー向けランタイム、接続ログ、アクセス制御を初期化する +- 対象ワールドをロードまたは新規作成し、実際のセーブ先と `level-id` を整合させる +- 専用サーバーのメインループを回す (network tick, XUI actions, autosave, CLI input) +- `banned-players.json` や `banned-ips.json` など運用向けファイルを維持する +- 新規ワールドの初回保存を実行し、その後安全にシャットダウンする + +## 2. 重要ファイル + +### 起動とランタイム +- `Windows64/ServerMain.cpp` + - `PrintUsage()` と `ParseCommandLine()` + - `SetExeWorkingDirectory()` + - 起動/終了フロー + - 新規ワールド初回保存の経路 + - メインループ、オートセーブ、CLI ポーリング + +### ワールド選択とセーブ読込 +- `WorldManager.h` +- `WorldManager.cpp` + - `level-id` 優先、その後 world 名フォールバックでセーブ探索 + - storage title と save ID を常にセットで適用 + - 非同期 storage/server action 完了待ちの helper を提供 + +### サーバー設定 +- `ServerProperties.h` +- `ServerProperties.cpp` + - 既定値と正規化レンジ + - `server.properties` の読込/補修/書込 + - `ServerPropertiesConfig` の提供 + - `SaveServerPropertiesConfig()` は `level-name` / `level-id` / `white-list` を書き換える + +### アクセス制御と BAN / Whitelist 永続化 +- `Access/Access.h` +- `Access/Access.cpp` + - プロセス全体で使うアクセス制御 facade + - コンソールコマンドとログイン判定から参照される公開スナップショット管理 +- `Access/BanManager.h` +- `Access/BanManager.cpp` + - `banned-players.json` と `banned-ips.json` の読込/書込 + - 識別子の正規化と、期限切れエントリを除いた snapshot 出力 +- `Access/WhitelistManager.h` +- `Access/WhitelistManager.cpp` + - `whitelist.json` の読込/書込 + - ログイン判定と CLI で使う XUID whitelist の正規化管理 + +### ログと接続監査 +- `ServerLogger.h` +- `ServerLogger.cpp` + - ログレベル解釈 + - 色付き/タイムスタンプ付きコンソールログ + - `startup`, `world-io`, `console`, `access`, `network`, `shutdown` などのカテゴリ +- `ServerLogManager.h` +- `ServerLogManager.cpp` + - TCP 接続 accept/reject ログ + - ログイン/切断の監査ログ + - `ban-ip ` が使う remote IP キャッシュ + +### コンソールコマンドシステム +- `Console/ServerCli.cpp` (facade) +- `Console/ServerCliInput.cpp` (linenoise 入力スレッド + completion bridge) +- `Console/ServerCliParser.cpp` (トークン分解、クォート、補完コンテキスト) +- `Console/ServerCliEngine.cpp` (実行ディスパッチ、補完、共通ヘルパー) +- `Console/ServerCliRegistry.cpp` (登録と名前解決) +- `Console/commands/*` (各コマンド実装) + +## 3. 起動フロー全体 + +`Windows64/ServerMain.cpp` の主な流れ: +1. `SetExeWorkingDirectory()` でカレントディレクトリを実行ファイルのフォルダへ切り替える +2. `LoadServerPropertiesConfig()` で `server.properties` を読み込み、正規化する +3. `DedicatedServerConfig` へ反映したあと、CLI 引数で上書きする (`-port`, `-ip`/`-bind`, `-name`, `-maxplayers`, `-seed`, `-loglevel`, `-help`/`--help`/`-h`) +4. プロセス状態、`ServerLogManager`、`Access::Initialize(".")` を初期化する +5. window/device/profile/network/thread-local 系を初期化する +6. `ServerPropertiesConfig` をゲームホスト設定へ反映する +7. `BootstrapWorldForServer(...)` でワールドを決定する +8. 読み込まれたセーブ ID が正規化後に変わった場合は、`SaveServerPropertiesConfig()` で書き戻す +9. `RunNetworkGameThreadProc` でホストゲームスレッドを起動する +10. 新規ワールドが作成された場合は、専用サーバー側で明示的に初回保存を要求する +11. メインループに入る: + - `TickCoreSystems()` + - `HandleXuiActions()` + - `serverCli.Poll()` + - オートセーブスケジュール +12. 終了時: + - CLI 入力を停止 + - save-on-exit を要求してサーバー停止 + - ネットワーク停止完了を待機 + - ログ/アクセス制御/ネットワーク/デバイスを終了 + +## 4. 現在の運用インターフェース + +### 4.1 起動引数 +- `-port <1-65535>` +- `-ip ` または `-bind ` +- `-name ` (実行時上限 16 文字) +- `-maxplayers <1-8>` +- `-seed ` +- `-loglevel ` +- `-help`, `--help`, `-h` + +補足: +- CLI による上書きは、その起動中のプロセスにだけ効きます +- 現在サーバーが書き戻す値は `level-name` と `level-id` だけで、ワールド解決時に識別情報が変わった場合に限られます + +### 4.2 組み込みコンソールコマンド +- `help` / `?` +- `stop` +- `list` +- `ban [reason ...]` + - 現状では対象プレイヤーがオンラインである必要があります +- `ban-ip [reason ...]` + - リテラル IPv4/IPv6 か、オンラインプレイヤーの現在 IP を対象にできます +- `pardon ` +- `pardon-ip
` + - リテラルアドレスのみ受け付けます +- `banlist` +- `tp ` / `teleport` +- `gamemode [player]` / `gm` + +CLI 挙動の補足: +- `cmd` と `/cmd` の両方を受け付けます +- `ServerCliParser` により引用符付き引数を扱えます +- 補完は各コマンドの `Complete(...)` で実装します + +### 4.3 実行ファイル横に書かれるファイル +- `server.properties` +- `banned-players.json` +- `banned-ips.json` + +これは `SetExeWorkingDirectory()` による挙動ですつまり、これらのファイルはシェル上の起動場所ではなく `Minecraft.Server.exe` 基準で解決されます + +## 5. よくある開発作業 + +### 5.1 CLI コマンドを追加する + +`/kick` や `/time` のようなコマンド追加時の基本手順: + +1. `Console/commands/` にファイルを追加 + - `CliCommandYourCommand.h` + - `CliCommandYourCommand.cpp` +2. `IServerCliCommand` を実装 + - `Name()`, `Usage()`, `Description()`, `Execute(...)` + - 必要なら `Aliases()` と `Complete(...)` +3. `ServerCliEngine::RegisterDefaultCommands()` に登録する +4. ビルド定義に追加する + - `CMakeLists.txt` (`MINECRAFT_SERVER_SOURCES`) + - `Minecraft.Server/Minecraft.Server.vcxproj` (`` / ``) +5. 手動確認 + - `help` に表示される + - 実行結果が期待通り + - 補完が `cmd` と `/cmd` の両方で動く + - 引用符付き引数が期待通り処理される + +参考実装: +- `CliCommandHelp.cpp` (単純コマンド) +- `CliCommandTp.cpp` (複数引数 + 補完 + 実行時チェック) +- `CliCommandGamemode.cpp` (引数解釈 + エイリアス) +- `CliCommandBanIp.cpp` (接続メタデータを使うアクセス制御系コマンド) + +### 5.2 `server.properties` キーを追加/変更する + +1. `ServerProperties.h` の `ServerPropertiesConfig` にフィールドを追加/更新する +2. `ServerProperties.cpp` の `kServerPropertyDefaults` に既定値を追加する +3. `LoadServerPropertiesConfig()` で読み込みと正規化を実装する + - bool/int/string/int64/log level/level type 用の既存 helper を使う +4. 書き戻し対象にしたいなら `SaveServerPropertiesConfig()` を更新する + - ただし現状この関数は、意図的にワールド識別情報だけを永続化します +5. 実行時反映箇所を更新する: + - `ApplyServerPropertiesToDedicatedConfig(...)` + - `ServerMain.cpp` の `app.SetGameHostOption(...)` + - CLI 上書きも持たせるなら `PrintUsage()` / `ParseCommandLine()` +6. 手動確認: + - 欠損キーの自動補完 + - 不正値の正規化 + - clamp 範囲が妥当か + - 実行時挙動に反映されるか + +> 覚えておくと良い正規化ポイント +- `level-id` は安全な save ID に正規化され、長さ制限も掛かる +- `server-name` は実行時 16 文字まで +- `max-players` は `1..8` に clamp される(あとで増やす必要あり) +- `autosave-interval` は `5..3600` に clamp される +- `level-type` は `default` または `flat` に正規化される + +### 5.3 BAN / アクセス制御挙動を変更する + +主な実装は `Access/Access.cpp`, `Access/BanManager.cpp`, `ServerLogManager.cpp` にあります + +変更時の注意: +- `BanManager` は storage/caching に責務を寄せ、 live-network policy を持ち込みすぎない +- `Access.cpp` の clone-and-publish スナップショット方式を保ち、読取側がディスク I/O で止まらないようにする +- `ban-ip ` は `ServerLogManager::TryGetConnectionRemoteIp(...)` に依存することを忘れない +- `SnapshotBannedPlayers()` / `SnapshotBannedIps()` には期限切れエントリを混ぜない +- 確認項目: + - 欠損時に空の BAN ファイルが初回起動で生成される + - `ban`, `ban-ip`, `pardon`, `pardon-ip`, `banlist` が動く + - オンライン対象の BAN が即時切断まで到達する + - 将来 reload 経路を増やしても手動編集が安全に再読込できる + +### 5.4 ワールドロード/新規作成ロジックを変更する + +主な実装は `WorldManager.cpp` にあります + +現在の探索ポリシー: +1. `level-id` (`UTF8SaveFilename`) 完全一致を優先 +2. 失敗時に world 名一致へフォールバック + +変更時の注意: +- `ApplyWorldStorageTarget(...)` で title と save ID を常にセットで扱う +- 待機ループで `tickProc` を回し続ける + - これを止めると非同期進行が止まり、タイムアウトしやすくなる +- タイムアウトや失敗ログは具体的に残す +- 確認項目 + - 既存ワールドを正しく再利用できるか + - 意図しない新規セーブ先が増えていないか + - 終了時保存が成功するか + - 新規ワールド時の明示的初回保存が `ServerMain.cpp` から維持されているか + +### 5.5 ログを追加する + +`ServerLogger` の API を利用: +- `LogDebug`, `LogInfo`, `LogWarn`, `LogError` +- フォーマット付きは `LogDebugf`, `LogInfof` など + +transport/login/disconnect ライフサイクルに属するイベントなら `ServerLogManager` 側を使います + +推奨カテゴリ: +- `startup`: 起動ライフサイクル +- `shutdown`: 停止ライフサイクル +- `world-io`: ワールド/保存処理 +- `console`: CLI コマンド処理 +- `access`: BAN/アクセス制御状態 +- `network`: 接続/ログイン監査 + +## 6. ビルドと実行 + +リポジトリルートで実行: + +```powershell +cmake -S . -B build -G "Visual Studio 17 2022" -A x64 +cmake --build build --config Debug --target MinecraftServer +cd .\build\Debug +.\Minecraft.Server.exe -port 25565 -bind 0.0.0.0 -name DedicatedServer +``` + +補足: +- プロセスは起動時にカレントディレクトリを実行ファイルの場所へ切り替えます +- `server.properties`, `banned-players.json`, `banned-ips.json` はそのため実行ファイル横に読み書きされます +- Visual Studio ワークフローはルートの `COMPILE.md` を参照してください + +## 7. 変更前チェックリスト + +- `server.properties` が欠損または疎でもクラッシュせず起動できる +- 欠損したアクセス制御ファイルがクリーンブート時に再生成される +- 既存ワールドが期待した `level-id` でロードされる +- 新規ワールド作成時の明示的初回保存が維持される +- CLI 入力と補完が引き続き応答する +- `banlist` 出力が BAN 追加/解除後も破綻しない +- 非同期待機ループから `TickCoreSystems()` など busy-wait 防止用ティックを消していない +- 新規追加したソースが CMake と `.vcxproj` の両方に入っている + +## 8. クイックトラブルシュート + +- コマンドが認識されない: + - `RegisterDefaultCommands()` とビルド定義を確認する +- `server.properties` や BAN ファイルの読込先が想定と違う: + - `SetExeWorkingDirectory()` により実行ファイルのフォルダへ移動していることを確認する +- オートセーブ/終了時保存がタイムアウトする: + - 待機ループ内で `TickCoreSystems()` と `HandleXuiActions()` を回しているか確認する +- 再起動時に同じワールドを使わない: + - `level-id` の正規化と `WorldManager.cpp` の一致判定を確認する +- `ban-ip ` で IP を解決できない: + - 対象プレイヤーがオンラインで、`ServerLogManager` に接続 IP がキャッシュされているか確認する +- 設定変更が効かない: + - 値が `ServerPropertiesConfig` にロードされ、必要なら `DedicatedServerConfig` にコピーされ、その後 `ServerMain.cpp` で反映されているか確認する diff --git a/Minecraft.Server/vendor/linenoise/LICENSE b/Minecraft.Server/vendor/linenoise/LICENSE new file mode 100644 index 000000000..d73915664 --- /dev/null +++ b/Minecraft.Server/vendor/linenoise/LICENSE @@ -0,0 +1,25 @@ +This vendored component is based on the linenoise project idea/API. + +Copyright (c) 2010-2014, Salvatore Sanfilippo +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Minecraft.Server/vendor/linenoise/linenoise.c b/Minecraft.Server/vendor/linenoise/linenoise.c new file mode 100644 index 000000000..a5b8ac5f6 --- /dev/null +++ b/Minecraft.Server/vendor/linenoise/linenoise.c @@ -0,0 +1,649 @@ +#include "linenoise.h" + +#include +#include +#include +#include +#include +#include + +#define LINENOISE_MAX_LINE 4096 +#define LINENOISE_MAX_PROMPT 128 + +typedef struct linenoiseHistory { + char **items; + int len; + int cap; + int maxLen; +} linenoiseHistory; + +static linenoiseCompletionCallback *g_completionCallback = NULL; +static volatile LONG g_stopRequested = 0; +static linenoiseHistory g_history = { NULL, 0, 0, 128 }; +/* Guards redraw/log interleaving so prompt and log lines do not overlap. */ +static CRITICAL_SECTION g_ioLock; +static volatile LONG g_ioLockState = 0; /* 0=not init, 1=init in progress, 2=ready */ +/* Snapshot of current editor line used to restore prompt after external output. */ +static volatile LONG g_editorActive = 0; +static char g_editorPrompt[LINENOISE_MAX_PROMPT] = { 0 }; +static char g_editorBuf[LINENOISE_MAX_LINE] = { 0 }; +static int g_editorLen = 0; +static int g_editorPos = 0; +static int g_editorPrevLen = 0; + +/** + * Lazily initialize the console I/O critical section. + * This avoids static init order issues and keeps startup cost minimal. + */ +static void linenoiseEnsureIoLockInit(void) +{ + LONG state = InterlockedCompareExchange(&g_ioLockState, 0, 0); + if (state == 2) + return; + + if (state == 0 && InterlockedCompareExchange(&g_ioLockState, 1, 0) == 0) + { + InitializeCriticalSection(&g_ioLock); + InterlockedExchange(&g_ioLockState, 2); + return; + } + + while (InterlockedCompareExchange(&g_ioLockState, 0, 0) != 2) + { + Sleep(0); + } +} + +static void linenoiseLockIo(void) +{ + linenoiseEnsureIoLockInit(); + EnterCriticalSection(&g_ioLock); +} + +static void linenoiseUnlockIo(void) +{ + LeaveCriticalSection(&g_ioLock); +} + +/** + * Save current prompt/buffer/cursor state for later redraw. + * Called after each redraw while editor is active. + */ +static void linenoiseUpdateEditorState(const char *prompt, const char *buf, int len, int pos, int prevLen) +{ + if (prompt == NULL) + prompt = ""; + if (buf == NULL) + buf = ""; + + strncpy_s(g_editorPrompt, sizeof(g_editorPrompt), prompt, _TRUNCATE); + strncpy_s(g_editorBuf, sizeof(g_editorBuf), buf, _TRUNCATE); + g_editorLen = len; + g_editorPos = pos; + g_editorPrevLen = prevLen; + InterlockedExchange(&g_editorActive, 1); +} + +static void linenoiseDeactivateEditorState(void) +{ + InterlockedExchange(&g_editorActive, 0); + g_editorPrompt[0] = 0; + g_editorBuf[0] = 0; + g_editorLen = 0; + g_editorPos = 0; + g_editorPrevLen = 0; +} + +static char *linenoiseStrdup(const char *src) +{ + size_t n = strlen(src) + 1; + char *out = (char *)malloc(n); + if (out == NULL) + return NULL; + memcpy(out, src, n); + return out; +} + +static void linenoiseEnsureHistoryCapacity(int wanted) +{ + if (wanted <= g_history.cap) + return; + + int newCap = g_history.cap == 0 ? 32 : g_history.cap; + while (newCap < wanted) + newCap *= 2; + + char **newItems = (char **)realloc(g_history.items, sizeof(char *) * (size_t)newCap); + if (newItems == NULL) + return; + + g_history.items = newItems; + g_history.cap = newCap; +} + +static void linenoiseClearCompletions(linenoiseCompletions *lc) +{ + size_t i = 0; + for (i = 0; i < lc->len; ++i) + { + free(lc->cvec[i]); + } + free(lc->cvec); + lc->cvec = NULL; + lc->len = 0; +} + +void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) +{ + char **newVec = (char **)realloc(lc->cvec, sizeof(char *) * (lc->len + 1)); + if (newVec == NULL) + return; + + lc->cvec = newVec; + lc->cvec[lc->len] = linenoiseStrdup(str); + if (lc->cvec[lc->len] == NULL) + return; + + lc->len += 1; +} + +void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) +{ + g_completionCallback = fn; +} + +void linenoiseFree(void *ptr) +{ + free(ptr); +} + +int linenoiseHistorySetMaxLen(int len) +{ + if (len <= 0) + return 0; + + g_history.maxLen = len; + while (g_history.len > g_history.maxLen) + { + free(g_history.items[0]); + memmove(g_history.items, g_history.items + 1, sizeof(char *) * (size_t)(g_history.len - 1)); + g_history.len -= 1; + } + + return 1; +} + +int linenoiseHistoryAdd(const char *line) +{ + if (line == NULL || line[0] == 0) + return 0; + + if (g_history.len > 0) + { + const char *last = g_history.items[g_history.len - 1]; + if (last != NULL && strcmp(last, line) == 0) + return 1; + } + + linenoiseEnsureHistoryCapacity(g_history.len + 1); + if (g_history.cap <= g_history.len) + return 0; + + g_history.items[g_history.len] = linenoiseStrdup(line); + if (g_history.items[g_history.len] == NULL) + return 0; + + g_history.len += 1; + + while (g_history.len > g_history.maxLen) + { + free(g_history.items[0]); + memmove(g_history.items, g_history.items + 1, sizeof(char *) * (size_t)(g_history.len - 1)); + g_history.len -= 1; + } + + return 1; +} + +void linenoiseRequestStop(void) +{ + InterlockedExchange(&g_stopRequested, 1); +} + +void linenoiseResetStop(void) +{ + InterlockedExchange(&g_stopRequested, 0); +} + +static int linenoiseIsStopRequested(void) +{ + return InterlockedCompareExchange(&g_stopRequested, 0, 0) != 0; +} + +static void linenoiseWriteHint(const char *hint, size_t hintLen) +{ + HANDLE stdoutHandle; + CONSOLE_SCREEN_BUFFER_INFO originalInfo; + int hasColorConsole = 0; + + if (hint == NULL || hintLen == 0) + { + return; + } + + stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); + if (stdoutHandle != INVALID_HANDLE_VALUE && stdoutHandle != NULL) + { + if (GetConsoleScreenBufferInfo(stdoutHandle, &originalInfo)) + { + hasColorConsole = 1; + /* Draw predictive tail in dim gray, then restore original console colors. */ + SetConsoleTextAttribute(stdoutHandle, FOREGROUND_INTENSITY); + } + } + + fwrite(hint, 1, hintLen, stdout); + + if (hasColorConsole) + { + SetConsoleTextAttribute(stdoutHandle, originalInfo.wAttributes); + } +} + +static int linenoiseStartsWithIgnoreCase(const char *full, const char *prefix) +{ + while (*prefix != 0) + { + if (tolower((unsigned char)*full) != tolower((unsigned char)*prefix)) + { + return 0; + } + ++full; + ++prefix; + } + return 1; +} + +static size_t linenoiseBuildHint(const char *buf, char *hint, size_t hintSize) +{ + linenoiseCompletions lc; + size_t inputLen = 0; + size_t i = 0; + + if (hint == NULL || hintSize == 0) + { + return 0; + } + hint[0] = 0; + + if (buf == NULL || buf[0] == 0 || g_completionCallback == NULL) + { + return 0; + } + + lc.len = 0; + lc.cvec = NULL; + /* Reuse the completion callback and derive a "ghost text" suffix from the first extending match. */ + g_completionCallback(buf, &lc); + + inputLen = strlen(buf); + for (i = 0; i < lc.len; ++i) + { + const char *candidate = lc.cvec[i]; + if (candidate == NULL) + { + continue; + } + if (strlen(candidate) <= inputLen) + { + continue; + } + if (!linenoiseStartsWithIgnoreCase(candidate, buf)) + { + continue; + } + + /* Keep only the part not yet typed by the user (rendered as hint text). */ + strncpy_s(hint, hintSize, candidate + inputLen, _TRUNCATE); + break; + } + + linenoiseClearCompletions(&lc); + return strlen(hint); +} + +static void linenoiseRedrawUnsafe(const char *prompt, const char *buf, int len, int pos, int *prevLen) +{ + int i; + char hint[LINENOISE_MAX_LINE] = {0}; + int renderedLen = len; + /* Hint length contributes to the rendered width so stale tail characters can be cleared correctly. */ + int hintLen = (int)linenoiseBuildHint(buf, hint, sizeof(hint)); + if (hintLen > 0) + { + renderedLen += hintLen; + } + + fputc('\r', stdout); + fputs(prompt, stdout); + if (len > 0) + { + fwrite(buf, 1, (size_t)len, stdout); + } + if (hintLen > 0) + { + linenoiseWriteHint(hint, (size_t)hintLen); + } + + if (*prevLen > renderedLen) + { + for (i = renderedLen; i < *prevLen; ++i) + { + fputc(' ', stdout); + } + } + + fputc('\r', stdout); + fputs(prompt, stdout); + if (pos > 0) + { + /* Cursor positioning reflects only real user input, not the ghost hint suffix. */ + fwrite(buf, 1, (size_t)pos, stdout); + } + + fflush(stdout); + *prevLen = renderedLen; + linenoiseUpdateEditorState(prompt, buf, len, pos, *prevLen); +} + +static void linenoiseRedraw(const char *prompt, const char *buf, int len, int pos, int *prevLen) +{ + linenoiseLockIo(); + linenoiseRedrawUnsafe(prompt, buf, len, pos, prevLen); + linenoiseUnlockIo(); +} + +static int linenoiseStartsWith(const char *full, const char *prefix) +{ + while (*prefix != 0) + { + if (*full != *prefix) + return 0; + ++full; + ++prefix; + } + return 1; +} + +static int linenoiseComputeCommonPrefix(const linenoiseCompletions *lc, const char *seed, char *out, size_t outSize) +{ + size_t commonLen = 0; + size_t i; + + if (lc->len == 0 || outSize == 0) + return 0; + + strncpy_s(out, outSize, lc->cvec[0], _TRUNCATE); + commonLen = strlen(out); + + for (i = 1; i < lc->len; ++i) + { + const char *candidate = lc->cvec[i]; + size_t j = 0; + + while (j < commonLen && out[j] != 0 && candidate[j] != 0 && out[j] == candidate[j]) + ++j; + + commonLen = j; + out[commonLen] = 0; + + if (commonLen == 0) + break; + } + + if (strlen(out) <= strlen(seed)) + return 0; + + return linenoiseStartsWith(out, seed); +} + +static void linenoiseApplyCompletion(const char *prompt, char *buf, int *len, int *pos, int *prevLen) +{ + linenoiseCompletions lc; + int i; + + if (g_completionCallback == NULL) + { + Beep(750, 15); + return; + } + + lc.len = 0; + lc.cvec = NULL; + g_completionCallback(buf, &lc); + + if (lc.len == 0) + { + Beep(750, 15); + linenoiseClearCompletions(&lc); + return; + } + + if (lc.len == 1) + { + strncpy_s(buf, LINENOISE_MAX_LINE, lc.cvec[0], _TRUNCATE); + *len = (int)strlen(buf); + *pos = *len; + linenoiseRedraw(prompt, buf, *len, *pos, prevLen); + linenoiseClearCompletions(&lc); + return; + } + + { + char common[LINENOISE_MAX_LINE] = { 0 }; + if (linenoiseComputeCommonPrefix(&lc, buf, common, sizeof(common))) + { + strncpy_s(buf, LINENOISE_MAX_LINE, common, _TRUNCATE); + *len = (int)strlen(buf); + *pos = *len; + linenoiseRedraw(prompt, buf, *len, *pos, prevLen); + } + } + + linenoiseLockIo(); + fputc('\n', stdout); + for (i = 0; i < (int)lc.len; ++i) + { + fputs(lc.cvec[i], stdout); + fputs(" ", stdout); + } + fputc('\n', stdout); + linenoiseRedrawUnsafe(prompt, buf, *len, *pos, prevLen); + linenoiseUnlockIo(); + linenoiseClearCompletions(&lc); +} + +char *linenoise(const char *prompt) +{ + char buf[LINENOISE_MAX_LINE]; + int len = 0; + int pos = 0; + int prevLen = 0; + int historyIndex = g_history.len; + + if (prompt == NULL) + prompt = ""; + + buf[0] = 0; + linenoiseLockIo(); + linenoiseUpdateEditorState(prompt, buf, len, pos, prevLen); + fputs(prompt, stdout); + fflush(stdout); + linenoiseUnlockIo(); + + while (!linenoiseIsStopRequested()) + { + if (!_kbhit()) + { + Sleep(10); + continue; + } + + { + int c = _getwch(); + + if (c == 0 || c == 224) + { + int ext = _getwch(); + if (ext == 72) + { + if (g_history.len > 0 && historyIndex > 0) + { + historyIndex -= 1; + strncpy_s(buf, sizeof(buf), g_history.items[historyIndex], _TRUNCATE); + len = (int)strlen(buf); + pos = len; + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + } + else if (ext == 80) + { + if (g_history.len > 0 && historyIndex < g_history.len) + { + historyIndex += 1; + if (historyIndex == g_history.len) + buf[0] = 0; + else + strncpy_s(buf, sizeof(buf), g_history.items[historyIndex], _TRUNCATE); + + len = (int)strlen(buf); + pos = len; + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + } + else if (ext == 75) + { + if (pos > 0) + { + pos -= 1; + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + } + else if (ext == 77) + { + if (pos < len) + { + pos += 1; + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + } + continue; + } + + if (c == 3) + { + linenoiseLockIo(); + linenoiseDeactivateEditorState(); + fputc('\n', stdout); + fflush(stdout); + linenoiseUnlockIo(); + return NULL; + } + + if (c == '\r' || c == '\n') + { + char *out; + linenoiseLockIo(); + linenoiseDeactivateEditorState(); + fputc('\n', stdout); + fflush(stdout); + linenoiseUnlockIo(); + + out = linenoiseStrdup(buf); + return out; + } + + if (c == '\t') + { + linenoiseApplyCompletion(prompt, buf, &len, &pos, &prevLen); + continue; + } + + if (c == 8) + { + if (pos > 0 && len > 0) + { + memmove(buf + pos - 1, buf + pos, (size_t)(len - pos + 1)); + pos -= 1; + len -= 1; + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + continue; + } + + if (isprint((unsigned char)c) && len < LINENOISE_MAX_LINE - 1) + { + if (pos == len) + { + buf[pos++] = (char)c; + len += 1; + buf[len] = 0; + } + else + { + memmove(buf + pos + 1, buf + pos, (size_t)(len - pos + 1)); + buf[pos] = (char)c; + pos += 1; + len += 1; + } + linenoiseRedraw(prompt, buf, len, pos, &prevLen); + } + } + } + + linenoiseLockIo(); + linenoiseDeactivateEditorState(); + fputc('\n', stdout); + fflush(stdout); + linenoiseUnlockIo(); + return NULL; +} + +void linenoiseExternalWriteBegin(void) +{ + int i; + int totalChars = 0; + + /* Lock shared console state and clear current prompt area before external output. */ + linenoiseLockIo(); + if (InterlockedCompareExchange(&g_editorActive, 0, 0) == 0) + { + return; + } + + totalChars = (int)strlen(g_editorPrompt) + g_editorPrevLen; + if (totalChars < 0) + { + totalChars = 0; + } + + fputc('\r', stdout); + for (i = 0; i < totalChars; ++i) + { + fputc(' ', stdout); + } + fputc('\r', stdout); + fflush(stdout); +} + +void linenoiseExternalWriteEnd(void) +{ + /* Restore prompt line after external output has been printed. */ + if (InterlockedCompareExchange(&g_editorActive, 0, 0) != 0) + { + int prevLen = g_editorPrevLen; + linenoiseRedrawUnsafe(g_editorPrompt, g_editorBuf, g_editorLen, g_editorPos, &prevLen); + g_editorPrevLen = prevLen; + } + linenoiseUnlockIo(); +} diff --git a/Minecraft.Server/vendor/linenoise/linenoise.h b/Minecraft.Server/vendor/linenoise/linenoise.h new file mode 100644 index 000000000..6f7a0d2b3 --- /dev/null +++ b/Minecraft.Server/vendor/linenoise/linenoise.h @@ -0,0 +1,37 @@ +#ifndef VENDORED_LINENOISE_H +#define VENDORED_LINENOISE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct linenoiseCompletions { + size_t len; + char **cvec; +} linenoiseCompletions; + +typedef void(linenoiseCompletionCallback)(const char *buf, linenoiseCompletions *lc); + +char *linenoise(const char *prompt); +void linenoiseFree(void *ptr); + +void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn); +void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str); + +int linenoiseHistoryAdd(const char *line); +int linenoiseHistorySetMaxLen(int len); + +void linenoiseRequestStop(void); +void linenoiseResetStop(void); + +/* Wrap external stdout/stderr writes so active prompt can be cleared/restored safely. */ +void linenoiseExternalWriteBegin(void); +void linenoiseExternalWriteEnd(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Minecraft.Server/vendor/nlohmann/LICENSE.MIT b/Minecraft.Server/vendor/nlohmann/LICENSE.MIT new file mode 100644 index 000000000..a1dacc8db --- /dev/null +++ b/Minecraft.Server/vendor/nlohmann/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2025 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Minecraft.Server/vendor/nlohmann/json.hpp b/Minecraft.Server/vendor/nlohmann/json.hpp new file mode 100644 index 000000000..82d69f7c5 --- /dev/null +++ b/Minecraft.Server/vendor/nlohmann/json.hpp @@ -0,0 +1,25526 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_DIAGNOSTIC_POSITIONS + #define JSON_DIAGNOSTIC_POSITIONS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_DIAGNOSTIC_POSITIONS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#ifdef JSON_HAS_CPP_17 + #include // optional +#endif +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2016 - 2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) + #define JSON_HAS_CPP_23 + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows calling any std function as if (e.g., with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // char_traits +#include // tuple +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& +is_complete_type < +detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template