diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index d2c04172b7..a0f17daaf2 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -65,6 +65,16 @@ std::string VulkanVendorString(uint32_t vendorId) { } } +const char *PresentModeString(VkPresentModeKHR presentMode) { + switch (presentMode) { + case VK_PRESENT_MODE_IMMEDIATE_KHR: return "IMMEDIATE"; + case VK_PRESENT_MODE_MAILBOX_KHR: return "MAILBOX"; + case VK_PRESENT_MODE_FIFO_KHR: return "FIFO"; + case VK_PRESENT_MODE_FIFO_RELAXED_KHR: return "FIFO_RELAXED"; + default: return "UNKNOWN"; + } +} + VulkanContext::VulkanContext() { if (!VulkanLoad()) { init_error_ = "Failed to load Vulkan driver library"; @@ -165,8 +175,13 @@ VkResult VulkanContext::CreateInstance(const char *app_name, int app_ver, uint32 } VulkanContext::~VulkanContext() { + assert(instance_ == VK_NULL_HANDLE); +} + +void VulkanContext::DestroyInstance() { vkDestroyInstance(instance_, nullptr); VulkanFree(); + instance_ = VK_NULL_HANDLE; } void VulkanContext::BeginFrame() { @@ -214,6 +229,7 @@ bool VulkanContext::InitObjects() { } void VulkanContext::DestroyObjects() { + ILOG("VulkanContext::DestroyObjects (including swapchain)"); if (swapchain_ != VK_NULL_HANDLE) vkDestroySwapchainKHR(device_, swapchain_, nullptr); swapchain_ = VK_NULL_HANDLE; @@ -580,12 +596,15 @@ void VulkanContext::InitSurfaceAndroid(ANativeWindow *wnd, int width, int height void VulkanContext::ReinitSurfaceAndroid(int width, int height) { if (surface_ != VK_NULL_HANDLE) { + ILOG("Destroying Android Vulkan surface (%d, %d)", width_, height_); vkDestroySurfaceKHR(instance_, surface_, nullptr); surface_ = VK_NULL_HANDLE; } VkResult U_ASSERT_ONLY res; + ILOG("Creating Android Vulkan surface (%d, %d)", width, height); + VkAndroidSurfaceCreateInfoKHR android = { VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR }; android.flags = 0; android.window = native_window; @@ -710,7 +729,7 @@ bool VulkanContext::InitSwapchain() { // to fall back in a sensible way. VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; for (size_t i = 0; i < presentModeCount; i++) { - ILOG("Supported present mode: %d", presentModes[i]); + ILOG("Supported present mode: %d (%s)", presentModes[i], PresentModeString(presentModes[i])); } for (size_t i = 0; i < presentModeCount; i++) { if (swapchainPresentMode == VK_PRESENT_MODE_MAX_ENUM_KHR) { @@ -734,7 +753,7 @@ bool VulkanContext::InitSwapchain() { // HACK swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; #endif - ILOG("Chosen present mode: %d", swapchainPresentMode); + ILOG("Chosen present mode: %d (%s)", swapchainPresentMode, PresentModeString(swapchainPresentMode)); delete[] presentModes; // Determine the number of VkImage's to use in the swap chain (we desire to // own only 1 image at a time, besides the images being displayed and @@ -797,6 +816,7 @@ VkFence VulkanContext::CreateFence(bool presignalled) { } void VulkanContext::DestroyDevice() { + ILOG("VulkanContext::DestroyDevice (performing deletes)"); // If there happen to be any pending deletes, now is a good time. for (int i = 0; i < ARRAY_SIZE(frame_); i++) { frame_[i].deleteList.PerformDeletes(device_); @@ -962,3 +982,103 @@ const char *VulkanResultToString(VkResult res) { return "VK_ERROR_...(unknown)"; } } + +void VulkanDeleteList::Take(VulkanDeleteList &del) { + assert(cmdPools_.size() == 0); + assert(descPools_.size() == 0); + assert(modules_.size() == 0); + assert(buffers_.size() == 0); + assert(bufferViews_.size() == 0); + assert(images_.size() == 0); + assert(imageViews_.size() == 0); + assert(deviceMemory_.size() == 0); + assert(samplers_.size() == 0); + assert(pipelines_.size() == 0); + assert(pipelineCaches_.size() == 0); + assert(renderPasses_.size() == 0); + assert(framebuffers_.size() == 0); + assert(callbacks_.size() == 0); + cmdPools_ = std::move(del.cmdPools_); + descPools_ = std::move(del.descPools_); + modules_ = std::move(del.modules_); + buffers_ = std::move(del.buffers_); + bufferViews_ = std::move(del.bufferViews_); + images_ = std::move(del.images_); + imageViews_ = std::move(del.imageViews_); + deviceMemory_ = std::move(del.deviceMemory_); + samplers_ = std::move(del.samplers_); + pipelines_ = std::move(del.pipelines_); + pipelineCaches_ = std::move(del.pipelineCaches_); + renderPasses_ = std::move(del.renderPasses_); + framebuffers_ = std::move(del.framebuffers_); + pipelineLayouts_ = std::move(del.pipelineLayouts_); + descSetLayouts_ = std::move(del.descSetLayouts_); + callbacks_ = std::move(del.callbacks_); +} + +void VulkanDeleteList::PerformDeletes(VkDevice device) { + for (auto &cmdPool : cmdPools_) { + vkDestroyCommandPool(device, cmdPool, nullptr); + } + cmdPools_.clear(); + for (auto &descPool : descPools_) { + vkDestroyDescriptorPool(device, descPool, nullptr); + } + descPools_.clear(); + for (auto &module : modules_) { + vkDestroyShaderModule(device, module, nullptr); + } + modules_.clear(); + for (auto &buf : buffers_) { + vkDestroyBuffer(device, buf, nullptr); + } + buffers_.clear(); + for (auto &bufView : bufferViews_) { + vkDestroyBufferView(device, bufView, nullptr); + } + bufferViews_.clear(); + for (auto &image : images_) { + vkDestroyImage(device, image, nullptr); + } + images_.clear(); + for (auto &imageView : imageViews_) { + vkDestroyImageView(device, imageView, nullptr); + } + imageViews_.clear(); + for (auto &mem : deviceMemory_) { + vkFreeMemory(device, mem, nullptr); + } + deviceMemory_.clear(); + for (auto &sampler : samplers_) { + vkDestroySampler(device, sampler, nullptr); + } + samplers_.clear(); + for (auto &pipeline : pipelines_) { + vkDestroyPipeline(device, pipeline, nullptr); + } + pipelines_.clear(); + for (auto &pcache : pipelineCaches_) { + vkDestroyPipelineCache(device, pcache, nullptr); + } + pipelineCaches_.clear(); + for (auto &renderPass : renderPasses_) { + vkDestroyRenderPass(device, renderPass, nullptr); + } + renderPasses_.clear(); + for (auto &framebuffer : framebuffers_) { + vkDestroyFramebuffer(device, framebuffer, nullptr); + } + framebuffers_.clear(); + for (auto &pipeLayout : pipelineLayouts_) { + vkDestroyPipelineLayout(device, pipeLayout, nullptr); + } + pipelineLayouts_.clear(); + for (auto &descSetLayout : descSetLayouts_) { + vkDestroyDescriptorSetLayout(device, descSetLayout, nullptr); + } + descSetLayouts_.clear(); + for (auto &callback : callbacks_) { + callback.func(callback.userdata); + } + callbacks_.clear(); +} diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 8b1044c093..07f82ead75 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -71,6 +71,7 @@ class VulkanDeleteList { }; public: + // NOTE: These all take reference handles so they can zero the input value. void QueueDeleteCommandPool(VkCommandPool &pool) { cmdPools_.push_back(pool); pool = VK_NULL_HANDLE; } void QueueDeleteDescriptorPool(VkDescriptorPool &pool) { descPools_.push_back(pool); pool = VK_NULL_HANDLE; } void QueueDeleteShaderModule(VkShaderModule &module) { modules_.push_back(module); module = VK_NULL_HANDLE; } @@ -88,105 +89,8 @@ public: void QueueDeleteDescriptorSetLayout(VkDescriptorSetLayout &descSetLayout) { descSetLayouts_.push_back(descSetLayout); descSetLayout = VK_NULL_HANDLE; } void QueueCallback(void(*func)(void *userdata), void *userdata) { callbacks_.push_back(Callback(func, userdata)); } - void Take(VulkanDeleteList &del) { - assert(cmdPools_.size() == 0); - assert(descPools_.size() == 0); - assert(modules_.size() == 0); - assert(buffers_.size() == 0); - assert(bufferViews_.size() == 0); - assert(images_.size() == 0); - assert(imageViews_.size() == 0); - assert(deviceMemory_.size() == 0); - assert(samplers_.size() == 0); - assert(pipelines_.size() == 0); - assert(pipelineCaches_.size() == 0); - assert(renderPasses_.size() == 0); - assert(framebuffers_.size() == 0); - assert(callbacks_.size() == 0); - cmdPools_ = std::move(del.cmdPools_); - descPools_ = std::move(del.descPools_); - modules_ = std::move(del.modules_); - buffers_ = std::move(del.buffers_); - bufferViews_ = std::move(del.bufferViews_); - images_ = std::move(del.images_); - imageViews_ = std::move(del.imageViews_); - deviceMemory_ = std::move(del.deviceMemory_); - samplers_ = std::move(del.samplers_); - pipelines_ = std::move(del.pipelines_); - pipelineCaches_ = std::move(del.pipelineCaches_); - renderPasses_ = std::move(del.renderPasses_); - framebuffers_ = std::move(del.framebuffers_); - pipelineLayouts_ = std::move(del.pipelineLayouts_); - descSetLayouts_ = std::move(del.descSetLayouts_); - callbacks_ = std::move(del.callbacks_); - } - - void PerformDeletes(VkDevice device) { - for (auto &cmdPool : cmdPools_) { - vkDestroyCommandPool(device, cmdPool, nullptr); - } - cmdPools_.clear(); - for (auto &descPool : descPools_) { - vkDestroyDescriptorPool(device, descPool, nullptr); - } - descPools_.clear(); - for (auto &module : modules_) { - vkDestroyShaderModule(device, module, nullptr); - } - modules_.clear(); - for (auto &buf : buffers_) { - vkDestroyBuffer(device, buf, nullptr); - } - buffers_.clear(); - for (auto &bufView : bufferViews_) { - vkDestroyBufferView(device, bufView, nullptr); - } - bufferViews_.clear(); - for (auto &image : images_) { - vkDestroyImage(device, image, nullptr); - } - images_.clear(); - for (auto &imageView : imageViews_) { - vkDestroyImageView(device, imageView, nullptr); - } - imageViews_.clear(); - for (auto &mem : deviceMemory_) { - vkFreeMemory(device, mem, nullptr); - } - deviceMemory_.clear(); - for (auto &sampler : samplers_) { - vkDestroySampler(device, sampler, nullptr); - } - samplers_.clear(); - for (auto &pipeline : pipelines_) { - vkDestroyPipeline(device, pipeline, nullptr); - } - pipelines_.clear(); - for (auto &pcache : pipelineCaches_) { - vkDestroyPipelineCache(device, pcache, nullptr); - } - pipelineCaches_.clear(); - for (auto &renderPass : renderPasses_) { - vkDestroyRenderPass(device, renderPass, nullptr); - } - renderPasses_.clear(); - for (auto &framebuffer : framebuffers_) { - vkDestroyFramebuffer(device, framebuffer, nullptr); - } - framebuffers_.clear(); - for (auto &pipeLayout : pipelineLayouts_) { - vkDestroyPipelineLayout(device, pipeLayout, nullptr); - } - pipelineLayouts_.clear(); - for (auto &descSetLayout : descSetLayouts_) { - vkDestroyDescriptorSetLayout(device, descSetLayout, nullptr); - } - descSetLayouts_.clear(); - for (auto &callback : callbacks_) { - callback.func(callback.userdata); - } - callbacks_.clear(); - } + void Take(VulkanDeleteList &del); + void PerformDeletes(VkDevice device); private: std::vector cmdPools_; @@ -214,7 +118,8 @@ public: ~VulkanContext(); VkResult CreateInstance(const char *app_name, int app_ver, uint32_t flags); - + void DestroyInstance(); + int GetBestPhysicalDevice(); void ChooseDevice(int physical_device); bool EnableDeviceExtension(const char *extension); diff --git a/Common/Vulkan/VulkanImage.cpp b/Common/Vulkan/VulkanImage.cpp index 75f78f95b4..256d6791ce 100644 --- a/Common/Vulkan/VulkanImage.cpp +++ b/Common/Vulkan/VulkanImage.cpp @@ -350,11 +350,11 @@ void VulkanTexture::UploadMip(VkCommandBuffer cmd, int mip, int mipWidth, int mi vkCmdCopyBufferToImage(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); } -void VulkanTexture::EndCreate(VkCommandBuffer cmd) { +void VulkanTexture::EndCreate(VkCommandBuffer cmd, bool vertexTexture) { TransitionImageLayout2(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, vertexTexture ? VK_PIPELINE_STAGE_VERTEX_SHADER_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); } diff --git a/Common/Vulkan/VulkanImage.h b/Common/Vulkan/VulkanImage.h index b84913c0d0..26f51cc2dd 100644 --- a/Common/Vulkan/VulkanImage.h +++ b/Common/Vulkan/VulkanImage.h @@ -33,7 +33,7 @@ public: // When using UploadMip, initialLayout should be VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL. bool CreateDirect(VkCommandBuffer cmd, int w, int h, int numMips, VkFormat format, VkImageLayout initialLayout, VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, const VkComponentMapping *mapping = nullptr); void UploadMip(VkCommandBuffer cmd, int mip, int mipWidth, int mipHeight, VkBuffer buffer, uint32_t offset, size_t rowLength); // rowLength is in pixels - void EndCreate(VkCommandBuffer cmd); + void EndCreate(VkCommandBuffer cmd, bool vertexTexture = false); void Destroy(); diff --git a/Common/Vulkan/VulkanMemory.cpp b/Common/Vulkan/VulkanMemory.cpp index 260be7d9d6..57b219b472 100644 --- a/Common/Vulkan/VulkanMemory.cpp +++ b/Common/Vulkan/VulkanMemory.cpp @@ -78,7 +78,6 @@ void VulkanPushBuffer::Destroy(VulkanContext *vulkan) { vulkan->Delete().QueueDeleteBuffer(info.buffer); vulkan->Delete().QueueDeleteDeviceMemory(info.deviceMemory); } - buffers_.clear(); } diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index e99d606fdb..2b5a67e6f0 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -64,6 +64,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "GuardBand", &flags_.GuardBand); CheckSetting(iniFile, gameID, "RequireBufferedRendering", &flags_.RequireBufferedRendering); CheckSetting(iniFile, gameID, "RequireBlockTransfer", &flags_.RequireBlockTransfer); + CheckSetting(iniFile, gameID, "DisableReadbacks", &flags_.DisableReadbacks); } void Compatibility::CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag) { diff --git a/Core/Compatibility.h b/Core/Compatibility.h index 438de9fb8f..4de13a63e4 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -55,6 +55,7 @@ struct CompatFlags { bool FakeMipmapChange; bool RequireBufferedRendering; bool RequireBlockTransfer; + bool DisableReadbacks; bool HackFixVideo; bool HackFixHangs; bool HackLatchedFramebuffer; @@ -85,4 +86,4 @@ private: void CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag); CompatFlags flags_; -}; \ No newline at end of file +}; diff --git a/Core/Core.cpp b/Core/Core.cpp index 55783375a8..73696842f6 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -172,7 +172,7 @@ bool UpdateScreenScale(int width, int height) { dp_yres = new_dp_yres; pixel_xres = width; pixel_yres = height; - INFO_LOG(SYSTEM, "pixel_res: %dx%d", pixel_xres, pixel_yres); + INFO_LOG(SYSTEM, "pixel_res: %dx%d. Calling NativeResized()", pixel_xres, pixel_yres); NativeResized(); return true; } diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 2630cde19f..3c8170b829 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -301,7 +301,9 @@ public: } else { // Older save state. Let's still reload, but this may not pick up new flags, etc. bool foundBroken = false; - for (auto func : importedFuncs) { + auto importedFuncsState = importedFuncs; + importedFuncs.clear(); + for (auto func : importedFuncsState) { if (func.moduleName[KERNELOBJECT_MAX_NAME_LENGTH] != '\0' || !Memory::IsValidAddress(func.stubAddr)) { foundBroken = true; } else { diff --git a/Core/MIPS/x86/CompBranch.cpp b/Core/MIPS/x86/CompBranch.cpp index b87cd5e6f9..7d3a52091a 100644 --- a/Core/MIPS/x86/CompBranch.cpp +++ b/Core/MIPS/x86/CompBranch.cpp @@ -545,7 +545,9 @@ void Jit::BranchVFPUFlag(MIPSOpcode op, Gen::CCFlags cc, bool likely) { CONDITIONAL_LOG; if (js.inDelaySlot) { - ERROR_LOG_REPORT(JIT, "Branch in VFPU delay slot at %08x in block starting at %08x", GetCompilerPC(), js.blockStart); + // I think we can safely just warn-log this without reporting, it's pretty clear that this type + // of branch is ignored. + WARN_LOG(JIT, "Branch in VFPU delay slot at %08x in block starting at %08x", GetCompilerPC(), js.blockStart); return; } int offset = _IMM16 << 2; diff --git a/GPU/Common/DrawEngineCommon.h b/GPU/Common/DrawEngineCommon.h index 99023d63f1..cdaa579a19 100644 --- a/GPU/Common/DrawEngineCommon.h +++ b/GPU/Common/DrawEngineCommon.h @@ -155,6 +155,7 @@ protected: int numPatches; class TessellationDataTransfer { protected: + // TODO: These aren't used by all backends. int prevSize; int prevSizeTex; int prevSizeCol; diff --git a/GPU/Common/FramebufferCommon.cpp b/GPU/Common/FramebufferCommon.cpp index b8ad7bb896..4922db1919 100644 --- a/GPU/Common/FramebufferCommon.cpp +++ b/GPU/Common/FramebufferCommon.cpp @@ -1314,7 +1314,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, FlushBeforeCopy(); if (srcH == 0 || srcY + srcH > srcBuffer->bufferHeight) { WARN_LOG_REPORT_ONCE(btdcpyheight, G3D, "Memcpy fbo download %08x -> %08x skipped, %d+%d is taller than %d", src, dst, srcY, srcH, srcBuffer->bufferHeight); - } else if (g_Config.bBlockTransferGPU && !srcBuffer->memoryUpdated) { + } else if (g_Config.bBlockTransferGPU && !srcBuffer->memoryUpdated && !PSP_CoreParameter().compat.flags().DisableReadbacks) { ReadFramebufferToMemory(srcBuffer, true, 0, srcY, srcBuffer->width, srcH); srcBuffer->usageFlags = (srcBuffer->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR; } diff --git a/GPU/Common/ShaderUniforms.cpp b/GPU/Common/ShaderUniforms.cpp index f54c3f16d3..2c29ccc52d 100644 --- a/GPU/Common/ShaderUniforms.cpp +++ b/GPU/Common/ShaderUniforms.cpp @@ -7,6 +7,7 @@ #include "math/math_util.h" #include "math/lin/vec3.h" #include "GPU/GPUState.h" +#include "GPU/Common/GPUStateUtils.h" #include "GPU/Math3D.h" #include "Core/Reporting.h" #include "Core/Config.h" @@ -191,30 +192,27 @@ void BaseUpdateUniforms(UB_VS_FS_Base *ub, uint64_t dirtyUniforms, bool flipView } if (dirtyUniforms & DIRTY_DEPTHRANGE) { - float viewZScale = gstate.getViewportZScale(); - float viewZCenter = gstate.getViewportZCenter(); + // Same formulas as D3D9 now. Should work for both Vulkan and D3D11. - // We had to scale and translate Z to account for our clamped Z range. - // Therefore, we also need to reverse this to round properly. - // - // Example: scale = 65535.0, center = 0.0 - // Resulting range = -65535 to 65535, clamped to [0, 65535] - // gstate_c.vpDepthScale = 2.0f - // gstate_c.vpZOffset = -1.0f - // - // The projection already accounts for those, so we need to reverse them. - // - // Additionally, D3D9 uses a range from [0, 1]. We double and move the center. - viewZScale *= (1.0f / gstate_c.vpDepthScale) * 2.0f; - viewZCenter -= 65535.0f * gstate_c.vpZOffset + 32768.5f; + // Depth is [0, 1] mapping to [minz, maxz], not too hard. + float vpZScale = gstate.getViewportZScale(); + float vpZCenter = gstate.getViewportZCenter(); + // These are just the reverse of the formulas in GPUStateUtils. + float halfActualZRange = vpZScale / gstate_c.vpDepthScale; + float minz = -((gstate_c.vpZOffset * halfActualZRange) - vpZCenter) - halfActualZRange; + float viewZScale = halfActualZRange * 2.0f; + // Account for the half pixel offset. + float viewZCenter = minz + (DepthSliceFactor() / 256.0f) * 0.5f; float viewZInvScale; + if (viewZScale != 0.0) { viewZInvScale = 1.0f / viewZScale; } else { viewZInvScale = 0.0; } + float data[4] = { viewZScale, viewZCenter, viewZCenter, viewZInvScale }; ub->depthRange[0] = viewZScale; ub->depthRange[1] = viewZCenter; ub->depthRange[2] = viewZCenter; diff --git a/GPU/Common/SoftwareTransformCommon.cpp b/GPU/Common/SoftwareTransformCommon.cpp index f55c793c47..fa34e321d5 100644 --- a/GPU/Common/SoftwareTransformCommon.cpp +++ b/GPU/Common/SoftwareTransformCommon.cpp @@ -137,13 +137,6 @@ void SoftwareTransform( bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0; bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled(); - // TODO: Split up into multiple draw calls for GLES 2.0 where you can't guarantee support for more than 0x10000 verts. - -#if defined(MOBILE_DEVICE) - if (vertexCount > 0x10000/3) - vertexCount = 0x10000/3; -#endif - float uscale = 1.0f; float vscale = 1.0f; if (throughmode) { diff --git a/GPU/D3D11/DrawEngineD3D11.h b/GPU/D3D11/DrawEngineD3D11.h index 48b52063bf..7838c79cea 100644 --- a/GPU/D3D11/DrawEngineD3D11.h +++ b/GPU/D3D11/DrawEngineD3D11.h @@ -146,6 +146,8 @@ public: void Resized() override; + void ClearInputLayoutMap(); + private: void DecodeVerts(); void DoFlush(); @@ -154,8 +156,6 @@ private: void ApplyDrawStateLate(bool applyStencilRef, uint8_t stencilRef); void ResetShaderBlending(); - void ClearInputLayoutMap(); - ID3D11InputLayout *SetupDecFmtForDraw(D3D11VertexShader *vshader, const DecVtxFormat &decFmt, u32 pspFmt); void MarkUnreliable(VertexArrayInfoD3D11 *vai); diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index 057716bf00..3c402a2025 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -278,6 +278,7 @@ void GPU_D3D11::DeviceLost() { // Simply drop all caches and textures. // FBOs appear to survive? Or no? shaderManagerD3D11_->ClearShaders(); + drawEngine_.ClearInputLayoutMap(); textureCacheD3D11_->Clear(false); framebufferManagerD3D11_->DeviceLost(); } @@ -742,6 +743,7 @@ void GPU_D3D11::ClearCacheNextFrame() { void GPU_D3D11::ClearShaderCache() { shaderManagerD3D11_->ClearShaders(); + drawEngine_.ClearInputLayoutMap(); } void GPU_D3D11::DoState(PointerWrap &p) { @@ -749,13 +751,12 @@ void GPU_D3D11::DoState(PointerWrap &p) { // TODO: Some of these things may not be necessary. // None of these are necessary when saving. - if (p.mode == p.MODE_READ) { + if (p.mode == p.MODE_READ && !PSP_CoreParameter().frozen) { textureCacheD3D11_->Clear(true); drawEngine_.ClearTrackedVertexArrays(); gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); framebufferManagerD3D11_->DestroyAllFBOs(); - shaderManagerD3D11_->ClearShaders(); } } diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index 7459d45df6..bc85e33e0f 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -681,13 +681,12 @@ void GPU_DX9::DoState(PointerWrap &p) { // TODO: Some of these things may not be necessary. // None of these are necessary when saving. - if (p.mode == p.MODE_READ) { + if (p.mode == p.MODE_READ && !PSP_CoreParameter().frozen) { textureCacheDX9_->Clear(true); drawEngine_.ClearTrackedVertexArrays(); gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); framebufferManagerDX9_->DestroyAllFBOs(); - shaderManagerDX9_->ClearCache(true); } } diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index d917437b83..fe1f1e0653 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -701,8 +701,15 @@ rotateVBO: params.allowSeparateAlphaClear = true; int maxIndex = indexGen.MaxIndex(); + int vertexCount = indexGen.VertexCount(); + + // TODO: Split up into multiple draw calls for GLES 2.0 where you can't guarantee support for more than 0x10000 verts. +#if defined(MOBILE_DEVICE) + if (vertexCount > 0x10000 / 3) + vertexCount = 0x10000 / 3; +#endif SoftwareTransform( - prim, indexGen.VertexCount(), + prim, vertexCount, dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); ApplyDrawStateLate(); diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index b8e7adbd06..781f4c5cd7 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -930,12 +930,10 @@ void GPU_GLES::DoState(PointerWrap &p) { // In Freeze-Frame mode, we don't want to do any of this. if (p.mode == p.MODE_READ && !PSP_CoreParameter().frozen) { textureCacheGL_->Clear(true); - depalShaderCache_.Clear(); drawEngine_.ClearTrackedVertexArrays(); gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); framebufferManagerGL_->DestroyAllFBOs(); - shaderManagerGL_->ClearCache(true); } } diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.cpp b/GPU/Vulkan/DepalettizeShaderVulkan.cpp index ce71a9babd..a080b27416 100644 --- a/GPU/Vulkan/DepalettizeShaderVulkan.cpp +++ b/GPU/Vulkan/DepalettizeShaderVulkan.cpp @@ -60,14 +60,26 @@ static VkFormat GetClutDestFormat(GEPaletteFormat format, VkComponentMapping *co DepalShaderCacheVulkan::DepalShaderCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan) : draw_(draw), vulkan_(vulkan) { - std::string errors; - vshader_ = CompileShaderModule(vulkan_, VK_SHADER_STAGE_VERTEX_BIT, depal_vs, &errors); - assert(vshader_ != VK_NULL_HANDLE); + DeviceRestore(draw, vulkan); } DepalShaderCacheVulkan::~DepalShaderCacheVulkan() { + DeviceLost(); +} + +void DepalShaderCacheVulkan::DeviceLost() { Clear(); vulkan_->Delete().QueueDeleteShaderModule(vshader_); + draw_ = nullptr; + vulkan_ = nullptr; +} + +void DepalShaderCacheVulkan::DeviceRestore(Draw::DrawContext *draw, VulkanContext *vulkan) { + draw_ = draw; + vulkan_ = vulkan; + std::string errors; + vshader_ = CompileShaderModule(vulkan_, VK_SHADER_STAGE_VERTEX_BIT, depal_vs, &errors); + assert(vshader_ != VK_NULL_HANDLE); } DepalShaderVulkan *DepalShaderCacheVulkan::GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat) { diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.h b/GPU/Vulkan/DepalettizeShaderVulkan.h index bba40a2c09..f06057e0c1 100644 --- a/GPU/Vulkan/DepalettizeShaderVulkan.h +++ b/GPU/Vulkan/DepalettizeShaderVulkan.h @@ -52,6 +52,8 @@ class DepalShaderCacheVulkan : public DepalShaderCacheCommon { public: DepalShaderCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan); ~DepalShaderCacheVulkan(); + void DeviceLost(); + void DeviceRestore(Draw::DrawContext *draw, VulkanContext *vulkan); // This also uploads the palette and binds the correct texture. DepalShaderVulkan *GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 580c5bef20..a6022747fb 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -93,8 +93,6 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan, Draw::DrawContext *dra indexGen.Setup(decIndex); InitDeviceObjects(); - - tessDataTransfer = new TessellationDataTransferVulkan(vulkan, draw); } void DrawEngineVulkan::InitDeviceObjects() { @@ -206,6 +204,8 @@ void DrawEngineVulkan::InitDeviceObjects() { assert(VK_SUCCESS == res); vertexCache_ = new VulkanPushBuffer(vulkan_, VERTEX_CACHE_SIZE); + + tessDataTransfer = new TessellationDataTransferVulkan(vulkan_, draw_); } DrawEngineVulkan::~DrawEngineVulkan() { @@ -214,8 +214,6 @@ DrawEngineVulkan::~DrawEngineVulkan() { FreeMemoryPages(splineBuffer, SPLINE_BUFFER_SIZE); DestroyDeviceObjects(); - - delete tessDataTransfer; } void DrawEngineVulkan::FrameData::Destroy(VulkanContext *vulkan) { @@ -241,6 +239,9 @@ void DrawEngineVulkan::FrameData::Destroy(VulkanContext *vulkan) { } void DrawEngineVulkan::DestroyDeviceObjects() { + delete tessDataTransfer; + tessDataTransfer = nullptr; + for (int i = 0; i < VulkanContext::MAX_INFLIGHT_FRAMES; i++) { frame_[i].Destroy(vulkan_); } @@ -249,11 +250,9 @@ void DrawEngineVulkan::DestroyDeviceObjects() { if (nullSampler_ != VK_NULL_HANDLE) vulkan_->Delete().QueueDeleteSampler(nullSampler_); if (pipelineLayout_ != VK_NULL_HANDLE) - vkDestroyPipelineLayout(vulkan_->GetDevice(), pipelineLayout_, nullptr); - pipelineLayout_ = VK_NULL_HANDLE; + vulkan_->Delete().QueueDeletePipelineLayout(pipelineLayout_); if (descriptorSetLayout_ != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(vulkan_->GetDevice(), descriptorSetLayout_, nullptr); - descriptorSetLayout_ = VK_NULL_HANDLE; + vulkan_->Delete().QueueDeleteDescriptorSetLayout(descriptorSetLayout_); if (nullTexture_) { nullTexture_->Destroy(); delete nullTexture_; @@ -262,6 +261,7 @@ void DrawEngineVulkan::DestroyDeviceObjects() { vertexCache_->Destroy(vulkan_); delete vertexCache_; vertexCache_ = nullptr; + vai_.Clear(); // Need to clear this to get rid of all remaining references to the dead buffers. } void DrawEngineVulkan::DeviceLost() { @@ -269,8 +269,9 @@ void DrawEngineVulkan::DeviceLost() { DirtyAllUBOs(); } -void DrawEngineVulkan::DeviceRestore(VulkanContext *vulkan) { +void DrawEngineVulkan::DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw) { vulkan_ = vulkan; + draw_ = draw; InitDeviceObjects(); } @@ -293,6 +294,9 @@ void DrawEngineVulkan::BeginFrame() { frame->pushVertex->Begin(vulkan_); frame->pushIndex->Begin(vulkan_); + // TODO: How can we make this nicer... + ((TessellationDataTransferVulkan *)tessDataTransfer)->SetPushBuffer(frame->pushUBO); + // TODO : Find a better place to do this. if (!nullTexture_) { ILOG("INIT : Creating null texture"); @@ -538,8 +542,8 @@ VkDescriptorSet DrawEngineVulkan::GetOrCreateDescriptorSet(VkImageView imageView _assert_msg_(G3D, result == VK_SUCCESS, "Ran out of descriptors in pool. sz=%d", (int)frame->descSets.size()); // We just don't write to the slots we don't care about. - VkWriteDescriptorSet writes[7]; - memset(writes, 0, sizeof(writes)); + // We need 8 now that we support secondary texture bindings. + VkWriteDescriptorSet writes[8]{}; // Main texture int n = 0; VkDescriptorImageInfo tex{}; @@ -581,8 +585,10 @@ VkDescriptorSet DrawEngineVulkan::GetOrCreateDescriptorSet(VkImageView imageView VkSampler sampler = ((TessellationDataTransferVulkan *)tessDataTransfer)->GetSampler(); for (int i = 0; i < 3; i++) { VulkanTexture *texture = ((TessellationDataTransferVulkan *)tessDataTransfer)->GetTexture(i); - VkImageView imageView = texture->GetImageView(); - if (i == 0 || imageView) { + if (texture) { + assert(texture->GetImageView()); + VkImageView imageView = texture->GetImageView(); + tess_tex[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; tess_tex[i].imageView = imageView; tess_tex[i].sampler = sampler; @@ -1083,48 +1089,99 @@ void DrawEngineVulkan::UpdateUBOs(FrameData *frame) { } } +DrawEngineVulkan::TessellationDataTransferVulkan::TessellationDataTransferVulkan(VulkanContext *vulkan, Draw::DrawContext *draw) + : TessellationDataTransfer(), vulkan_(vulkan), draw_(draw) { + CreateSampler(); +} + +DrawEngineVulkan::TessellationDataTransferVulkan::~TessellationDataTransferVulkan() { + for (int i = 0; i < 3; i++) + delete data_tex[i]; + vulkan_->Delete().QueueDeleteSampler(sampler); +} + +// TODO: Consolidate the three textures into one, with height 3. +// This can be done for all the backends. void DrawEngineVulkan::TessellationDataTransferVulkan::PrepareBuffers(float *&pos, float *&tex, float *&col, int size, bool hasColor, bool hasTexCoords) { - int rowPitch; - ILOG("INIT : Prep tess"); + assert(size > 0); VkCommandBuffer cmd = (VkCommandBuffer)draw_->GetNativeObject(Draw::NativeObject::INIT_COMMANDBUFFER); // Position - if (prevSize < size) { - prevSize = size; + delete data_tex[0]; + data_tex[0] = new VulkanTexture(vulkan_, nullptr); // TODO: Should really use an allocator. + bool success = data_tex[0]->CreateDirect(cmd, size, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + assert(success); - data_tex[0]->CreateDirect(cmd, size, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - } - pos = (float *)data_tex[0]->Lock(0, &rowPitch); + pos = (float *)push_->Push(size * sizeof(float) * 4, &posOffset_, &posBuf_); + posSize_ = size; // Texcoords + delete data_tex[1]; if (hasTexCoords) { - if (prevSizeTex < size) { - prevSizeTex = size; + data_tex[1] = new VulkanTexture(vulkan_, nullptr); // TODO: Should really use an allocator. + success = data_tex[1]->CreateDirect(cmd, size, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + assert(success); - data_tex[1]->CreateDirect(cmd, size, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - } - tex = (float *)data_tex[1]->Lock(0, &rowPitch); + tex = (float *)push_->Push(size * sizeof(float) * 4, &texOffset_, &texBuf_); + texSize_ = size; + } else { + data_tex[1] = nullptr; + tex = nullptr; + texSize_ = 0; } // Color - int sizeColor = hasColor ? size : 1; - if (prevSizeCol < sizeColor) { - prevSizeCol = sizeColor; + colSize_ = hasColor ? size : 1; + delete data_tex[2]; + data_tex[2] = new VulkanTexture(vulkan_, nullptr); // TODO: Should really use an allocator. + success = data_tex[2]->CreateDirect(cmd, colSize_, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + assert(success); - data_tex[2]->CreateDirect(cmd, sizeColor, 1, 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - } - col = (float *)data_tex[2]->Lock(0, &rowPitch); + col = (float *)push_->Push(colSize_ * sizeof(float) * 4, &colOffset_, &colBuf_); } void DrawEngineVulkan::TessellationDataTransferVulkan::SendDataToShader(const float *pos, const float *tex, const float *col, int size, bool hasColor, bool hasTexCoords) { VkCommandBuffer cmd = (VkCommandBuffer)draw_->GetNativeObject(Draw::NativeObject::INIT_COMMANDBUFFER); // Position - data_tex[0]->Unlock(cmd); + data_tex[0]->UploadMip(cmd, 0, posSize_, 1, posBuf_, posOffset_, posSize_); + data_tex[0]->EndCreate(cmd, true); // Texcoords - if (hasTexCoords) - data_tex[1]->Unlock(cmd); + if (hasTexCoords) { + data_tex[1]->UploadMip(cmd, 0, texSize_, 1, texBuf_, texOffset_, texSize_); + data_tex[1]->EndCreate(cmd, true); + } // Color - data_tex[2]->Unlock(cmd); + data_tex[2]->UploadMip(cmd, 0, colSize_, 1, colBuf_, colOffset_, colSize_); + data_tex[2]->EndCreate(cmd, true); +} + +void DrawEngineVulkan::TessellationDataTransferVulkan::CreateSampler() { + VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + samp.compareOp = VK_COMPARE_OP_NEVER; + samp.flags = 0; + samp.magFilter = VK_FILTER_NEAREST; + samp.minFilter = VK_FILTER_NEAREST; + samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) { + // Docs say the min of this value and the supported max are used. + samp.maxAnisotropy = 1 << g_Config.iAnisotropyLevel; + samp.anisotropyEnable = true; + } else { + samp.maxAnisotropy = 1.0f; + samp.anisotropyEnable = false; + } + + samp.maxLod = 1.0f; + samp.minLod = 0.0f; + samp.mipLodBias = 0.0f; + + VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler); + assert(res == VK_SUCCESS); } diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 2322dfdc45..48641131dc 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -137,7 +137,7 @@ public: } void DeviceLost(); - void DeviceRestore(VulkanContext *vulkan); + void DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw); void SetupVertexDecoder(u32 vertType); void SetupVertexDecoderInternal(u32 vertType); @@ -261,56 +261,34 @@ private: // Hardware tessellation class TessellationDataTransferVulkan : public TessellationDataTransfer { + public: + TessellationDataTransferVulkan(VulkanContext *vulkan, Draw::DrawContext *draw); + ~TessellationDataTransferVulkan(); + + void SetPushBuffer(VulkanPushBuffer *push) { push_ = push; } + void SendDataToShader(const float *pos, const float *tex, const float *col, int size, bool hasColor, bool hasTexCoords) override; + void PrepareBuffers(float *&pos, float *&tex, float *&col, int size, bool hasColor, bool hasTexCoords) override; + + VulkanTexture *GetTexture(int i) const { return data_tex[i]; } + + VkSampler GetSampler() const { return sampler; } + void CreateSampler(); private: VulkanContext *vulkan_; Draw::DrawContext *draw_; - VulkanTexture *data_tex[3]; - VkSampler sampler; - public: - TessellationDataTransferVulkan(VulkanContext *vulkan, Draw::DrawContext *draw) - : TessellationDataTransfer(), vulkan_(vulkan), draw_(draw), data_tex(), sampler() { - for (int i = 0; i < 3; i++) - data_tex[i] = new VulkanTexture(vulkan_); + VulkanTexture *data_tex[3]{}; + VkSampler sampler = VK_NULL_HANDLE; + VulkanPushBuffer *push_; // Updated each frame. - CreateSampler(); - } - ~TessellationDataTransferVulkan() { - for (int i = 0; i < 3; i++) - delete data_tex[i]; + int posSize_ = 0; + uint32_t posOffset_ = 0; + VkBuffer posBuf_ = 0; + int texSize_ = 0; + uint32_t texOffset_ = 0; + VkBuffer texBuf_ = 0; + int colSize_ = 0; + uint32_t colOffset_ = 0; + VkBuffer colBuf_ = 0; - vulkan_->Delete().QueueDeleteSampler(sampler); - } - void SendDataToShader(const float *pos, const float *tex, const float *col, int size, bool hasColor, bool hasTexCoords) override; - void PrepareBuffers(float *&pos, float *&tex, float *&col, int size, bool hasColor, bool hasTexCoords) override; - VulkanTexture *GetTexture(int i) const { return data_tex[i]; } - VkSampler GetSampler() const { return sampler; } - void CreateSampler() { - VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; - samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samp.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - samp.compareOp = VK_COMPARE_OP_NEVER; - samp.flags = 0; - samp.magFilter =VK_FILTER_NEAREST; - samp.minFilter = VK_FILTER_NEAREST; - samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - - if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) { - // Docs say the min of this value and the supported max are used. - samp.maxAnisotropy = 1 << g_Config.iAnisotropyLevel; - samp.anisotropyEnable = true; - } else { - samp.maxAnisotropy = 1.0f; - samp.anisotropyEnable = false; - } - - samp.maxLod = 1.0f; - samp.minLod = 0.0f; - samp.mipLodBias = 0.0f; - - VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler); - assert(res == VK_SUCCESS); - } }; }; diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index 6abc89637b..9cb3019553 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -88,8 +88,7 @@ FramebufferManagerVulkan::FramebufferManagerVulkan(Draw::DrawContext *draw, Vulk convBufSize_(0), textureCacheVulkan_(nullptr), shaderManagerVulkan_(nullptr), - pipelinePostShader_(VK_NULL_HANDLE), - depalVulkan_(draw, vulkan) { + pipelinePostShader_(VK_NULL_HANDLE) { InitDeviceObjects(); @@ -593,8 +592,9 @@ void FramebufferManagerVulkan::DeviceLost() { DestroyDeviceObjects(); } -void FramebufferManagerVulkan::DeviceRestore(VulkanContext *vulkan) { +void FramebufferManagerVulkan::DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw) { vulkan_ = vulkan; + draw_ = draw; vulkan2D_->DeviceRestore(vulkan_); InitDeviceObjects(); diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index 9c37034842..98ac4d9e25 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -70,7 +70,7 @@ public: void Resized() override; void DeviceLost(); - void DeviceRestore(VulkanContext *vulkan); + void DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw); int GetLineWidth(); void ReformatFramebufferFrom(VirtualFramebuffer *vfb, GEBufferFormat old) override; @@ -120,7 +120,6 @@ private: DrawEngineVulkan *drawEngineVulkan_; VulkanPushBuffer *push_; - DepalShaderCacheVulkan depalVulkan_; enum { MAX_COMMAND_BUFFERS = 32, }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 659762c5bf..5a60a9bcbd 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -177,9 +177,15 @@ void GPU_Vulkan::CheckGPUFeatures() { features |= GPU_SUPPORTS_WIDE_LINES; } if (vulkan_->GetFeaturesEnabled().dualSrcBlend) { - // Work around for Intel driver bug. See issue #10074. - if (vulkan_->GetPhysicalDeviceProperties().vendorID != VULKAN_VENDOR_INTEL) + switch (vulkan_->GetPhysicalDeviceProperties().vendorID) { + case VULKAN_VENDOR_INTEL: + case VULKAN_VENDOR_AMD: + // Work around for Intel driver bug. See issue #10074, and also #10065 (AMD) + break; + default: features |= GPU_SUPPORTS_DUALSOURCE_BLEND; + break; + } } if (vulkan_->GetFeaturesEnabled().logicOp) { features |= GPU_SUPPORTS_LOGIC_OP; @@ -193,6 +199,7 @@ void GPU_Vulkan::CheckGPUFeatures() { } // Mandatory features on Vulkan, which may be checked in "centralized" code + features |= GPU_SUPPORTS_ACCURATE_DEPTH; features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; features |= GPU_SUPPORTS_FBO; features |= GPU_SUPPORTS_BLEND_MINMAX; @@ -781,13 +788,16 @@ void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { } void GPU_Vulkan::InitDeviceObjects() { + ILOG("GPU_Vulkan::InitDeviceObjects"); // Initialize framedata for (int i = 0; i < VulkanContext::MAX_INFLIGHT_FRAMES; i++) { + assert(!frameData_[i].push_); frameData_[i].push_ = new VulkanPushBuffer(vulkan_, 64 * 1024); } } void GPU_Vulkan::DestroyDeviceObjects() { + ILOG("GPU_Vulkan::DestroyDeviceObjects"); for (int i = 0; i < VulkanContext::MAX_INFLIGHT_FRAMES; i++) { if (frameData_[i].push_) { frameData_[i].push_->Destroy(vulkan_); @@ -804,21 +814,25 @@ void GPU_Vulkan::DeviceLost() { drawEngine_.DeviceLost(); pipelineManager_->DeviceLost(); textureCacheVulkan_->DeviceLost(); - depalShaderCache_.Clear(); + depalShaderCache_.DeviceLost(); shaderManagerVulkan_->ClearShaders(); } void GPU_Vulkan::DeviceRestore() { vulkan_ = (VulkanContext *)PSP_CoreParameter().graphicsContext->GetAPIContext(); + draw_ = (Draw::DrawContext *)PSP_CoreParameter().graphicsContext->GetDrawContext(); + InitDeviceObjects(); + CheckGPUFeatures(); BuildReportingInfo(); UpdateCmdInfo(); - framebufferManagerVulkan_->DeviceRestore(vulkan_); - drawEngine_.DeviceRestore(vulkan_); + framebufferManagerVulkan_->DeviceRestore(vulkan_, draw_); + drawEngine_.DeviceRestore(vulkan_, draw_); pipelineManager_->DeviceRestore(vulkan_); - textureCacheVulkan_->DeviceRestore(vulkan_); + textureCacheVulkan_->DeviceRestore(vulkan_, draw_); shaderManagerVulkan_->DeviceRestore(vulkan_); + depalShaderCache_.DeviceRestore(draw_, vulkan_); } void GPU_Vulkan::GetStats(char *buffer, size_t bufsize) { @@ -883,8 +897,6 @@ void GPU_Vulkan::DoState(PointerWrap &p) { gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); framebufferManagerVulkan_->DestroyAllFBOs(); - shaderManagerVulkan_->ClearShaders(); - pipelineManager_->Clear(); } } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 289a8463f1..d94c4ee768 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -119,8 +119,6 @@ private: // Manages state and pipeline objects PipelineManagerVulkan *pipelineManager_; - int lastVsync_; - VkCommandBuffer curCmd_; int vertexCost_ = 0; std::string reportingPrimaryInfo_; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 0af19ca2a7..90d87a8003 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -126,36 +126,14 @@ void SamplerCache::DeviceRestore(VulkanContext *vulkan) { TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan) : TextureCacheCommon(draw), vulkan_(vulkan), - samplerCache_(vulkan), - texelsScaledThisFrame_(0) { + samplerCache_(vulkan) { timesInvalidatedAllThisFrame_ = 0; - lastBoundTexture = nullptr; - allocator_ = new VulkanDeviceAllocator(vulkan_, TEXCACHE_MIN_SLAB_SIZE, TEXCACHE_MAX_SLAB_SIZE); - - VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; - samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samp.magFilter = VK_FILTER_NEAREST; - samp.minFilter = VK_FILTER_NEAREST; - samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &samplerNearest_); + DeviceRestore(vulkan, draw); SetupTextureDecoder(); } TextureCacheVulkan::~TextureCacheVulkan() { - vulkan_->Delete().QueueDeleteSampler(samplerNearest_); - Clear(true); - - if (allocator_) { - allocator_->Destroy(); - - // We have to delete on queue, so this can free its queued deletions. - vulkan_->Delete().QueueCallback([](void *ptr) { - auto allocator = static_cast(ptr); - delete allocator; - }, allocator_); - } + DeviceLost(); } void TextureCacheVulkan::SetFramebufferManager(FramebufferManagerVulkan *fbManager) { @@ -183,17 +161,28 @@ void TextureCacheVulkan::DeviceLost() { } samplerCache_.DeviceLost(); + vulkan_->Delete().QueueDeleteSampler(samplerNearest_); nextTexture_ = nullptr; } -void TextureCacheVulkan::DeviceRestore(VulkanContext *vulkan) { +void TextureCacheVulkan::DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw) { vulkan_ = vulkan; + draw_ = draw; assert(!allocator_); allocator_ = new VulkanDeviceAllocator(vulkan_, TEXCACHE_MIN_SLAB_SIZE, TEXCACHE_MAX_SLAB_SIZE); samplerCache_.DeviceRestore(vulkan); + + VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.magFilter = VK_FILTER_NEAREST; + samp.minFilter = VK_FILTER_NEAREST; + samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &samplerNearest_); } void TextureCacheVulkan::ReleaseTexture(TexCacheEntry *entry, bool delete_them) { diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 1b168fd0f5..fa2b070bfe 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -72,7 +72,7 @@ public: void EndFrame(); void DeviceLost(); - void DeviceRestore(VulkanContext *vulkan); + void DeviceRestore(VulkanContext *vulkan, Draw::DrawContext *draw); void SetFramebufferManager(FramebufferManagerVulkan *fbManager); void SetDepalShaderCache(DepalShaderCacheVulkan *dpCache) { @@ -122,19 +122,19 @@ private: void ApplyTextureFramebuffer(TexCacheEntry *entry, VirtualFramebuffer *framebuffer) override; void BuildTexture(TexCacheEntry *const entry, bool replaceImages) override; - VulkanContext *vulkan_; - VulkanDeviceAllocator *allocator_; - VulkanPushBuffer *push_; + VulkanContext *vulkan_ = nullptr; + VulkanDeviceAllocator *allocator_ = nullptr; + VulkanPushBuffer *push_ = nullptr; SamplerCache samplerCache_; TextureScalerVulkan scaler; - CachedTextureVulkan *lastBoundTexture; + CachedTextureVulkan *lastBoundTexture = nullptr; - int decimationCounter_; - int texelsScaledThisFrame_; - int timesInvalidatedAllThisFrame_; + int decimationCounter_ = 0; + int texelsScaledThisFrame_ = 0; + int timesInvalidatedAllThisFrame_ = 0; FramebufferManagerVulkan *framebufferManagerVulkan_; DepalShaderCacheVulkan *depalShaderCache_; diff --git a/GPU/Vulkan/VulkanUtil.cpp b/GPU/Vulkan/VulkanUtil.cpp index 01d001a0e3..662f5196c1 100644 --- a/GPU/Vulkan/VulkanUtil.cpp +++ b/GPU/Vulkan/VulkanUtil.cpp @@ -46,11 +46,11 @@ void Vulkan2D::DestroyDeviceObjects() { VkDevice device = vulkan_->GetDevice(); if (descriptorSetLayout_ != VK_NULL_HANDLE) { - vkDestroyDescriptorSetLayout(device, descriptorSetLayout_, nullptr); + vulkan_->Delete().QueueDeleteDescriptorSetLayout(descriptorSetLayout_); descriptorSetLayout_ = VK_NULL_HANDLE; } if (pipelineLayout_ != VK_NULL_HANDLE) { - vkDestroyPipelineLayout(device, pipelineLayout_, nullptr); + vulkan_->Delete().QueueDeletePipelineLayout(pipelineLayout_); pipelineLayout_ = VK_NULL_HANDLE; } diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index 65e1cefe9f..f4f1a102f0 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -1127,12 +1127,16 @@ void EmuScreen::deviceLost() { ILOG("EmuScreen::deviceLost()"); if (gpu) gpu->DeviceLost(); + else + ILOG("No gpu to deviceLost!"); } void EmuScreen::deviceRestore() { ILOG("EmuScreen::deviceRestore()"); if (gpu) gpu->DeviceRestore(); + else + ILOG("No gpu to deviceRestore!"); RecreateViews(); } diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index b97edf440d..3c54be8a3c 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -127,6 +127,8 @@ std::unique_ptr uiTexture; ScreenManager *screenManager; std::string config_filename; +bool g_graphicsInited; + #ifdef IOS bool iosCanUseJit; bool targetIsJailbroken; @@ -675,10 +677,13 @@ void NativeInitGraphics(GraphicsContext *graphicsContext) { #endif g_gameInfoCache = new GameInfoCache(); + + g_graphicsInited = true; ILOG("NativeInitGraphics completed"); } void NativeShutdownGraphics() { + g_graphicsInited = false; ILOG("NativeShutdownGraphics"); #ifdef _WIN32 @@ -817,6 +822,7 @@ void NativeRender(GraphicsContext *graphicsContext) { } if (resized) { + ILOG("resized was set to true - resizing"); resized = false; if (uiContext) { @@ -839,6 +845,12 @@ void NativeRender(GraphicsContext *graphicsContext) { graphicsContext->Resize(); screenManager->resized(); + // Do not enable unless you are testing device-loss on Windows +#if 0 + screenManager->deviceLost(); + screenManager->deviceRestore(); +#endif + // TODO: Move this to new GraphicsContext objects for each backend. #ifndef _WIN32 if (GetGPUBackend() == GPUBackend::OPENGL) { @@ -1072,7 +1084,11 @@ void NativeMessageReceived(const char *message, const char *value) { void NativeResized() { // NativeResized can come from any thread so we just set a flag, then process it later. - resized = true; + if (g_graphicsInited) { + resized = true; + } else { + ILOG("NativeResized ignored, not initialized"); + } } void NativeSetRestarting() { diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 4d8e8f152f..01a353cec8 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -128,7 +128,7 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep return false; if (msgCode == 64) // Another useless perf warning that will be seen less and less as we optimize - vkCmdClearAttachments() issued on command buffer object 0x00000195296C6D40 prior to any Draw Cmds. It is recommended you use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw. return false; - + #ifdef _WIN32 std::string msg = message.str(); OutputDebugStringA(msg.c_str()); @@ -218,6 +218,8 @@ void WindowsVulkanContext::Shutdown() { g_Vulkan->DestroyObjects(); g_Vulkan->DestroyDevice(); g_Vulkan->DestroyDebugMsgCallback(); + g_Vulkan->DestroyInstance(); + delete g_Vulkan; g_Vulkan = nullptr; diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index 8517e5bdf1..d1260fce3c 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -189,6 +189,11 @@ static VulkanContext *g_Vulkan; class AndroidVulkanContext : public AndroidGraphicsContext { public: AndroidVulkanContext() : draw_(nullptr) {} + ~AndroidVulkanContext() { + delete g_Vulkan; + g_Vulkan = nullptr; + } + bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) override; void Shutdown() override; void SwapInterval(int interval) override; @@ -270,10 +275,7 @@ static VKAPI_ATTR VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, } bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) { - if (g_Vulkan) { - return false; - } - + ILOG("AndroidVulkanContext::Init"); init_glslang(); g_LogOptions.breakOnError = true; @@ -282,7 +284,10 @@ bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, ILOG("Creating vulkan context"); Version gitVer(PPSSPP_GIT_VERSION); - g_Vulkan = new VulkanContext(); + + if (!g_Vulkan) { + g_Vulkan = new VulkanContext(); + } if (VK_SUCCESS != g_Vulkan->CreateInstance("PPSSPP", gitVer.ToInteger(), VULKAN_FLAG_PRESENT_MAILBOX | VULKAN_FLAG_PRESENT_FIFO_RELAXED)) { ELOG("Failed to create vulkan context: %s", g_Vulkan->InitError().c_str()); delete g_Vulkan; @@ -326,6 +331,7 @@ bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, bool success = draw_->CreatePresets(); // Doesn't fail, we ship the compiler. assert(success); draw_->HandleEvent(Draw::Event::GOT_BACKBUFFER, g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); + ILOG("AndroidVulkanContext::Init completed"); return true; } @@ -334,22 +340,27 @@ void AndroidVulkanContext::Shutdown() { draw_->HandleEvent(Draw::Event::LOST_BACKBUFFER, g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); delete draw_; draw_ = nullptr; + ILOG("Calling NativeShutdownGraphics"); NativeShutdownGraphics(); g_Vulkan->WaitUntilQueueIdle(); g_Vulkan->DestroyObjects(); - g_Vulkan->DestroyDebugMsgCallback(); g_Vulkan->DestroyDevice(); + g_Vulkan->DestroyDebugMsgCallback(); - delete g_Vulkan; - g_Vulkan = nullptr; + g_Vulkan->DestroyInstance(); + + // We keep the g_Vulkan context around to avoid invalidating a ton of pointers around the app. finalize_glslang(); + ILOG("AndroidVulkanContext::Shutdown completed"); } void AndroidVulkanContext::SwapBuffers() { } void AndroidVulkanContext::Resize() { + ILOG("AndroidVulkanContext::Resize begin (%d, %d)", g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); + draw_->HandleEvent(Draw::Event::LOST_BACKBUFFER, g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); g_Vulkan->DestroyObjects(); @@ -357,6 +368,7 @@ void AndroidVulkanContext::Resize() { g_Vulkan->ReinitSurfaceAndroid(pixel_xres, pixel_yres); g_Vulkan->InitObjects(); draw_->HandleEvent(Draw::Event::GOT_BACKBUFFER, g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); + ILOG("AndroidVulkanContext::Resize end (%d, %d)", g_Vulkan->GetBackbufferWidth(), g_Vulkan->GetBackbufferHeight()); } void AndroidVulkanContext::SwapInterval(int interval) { @@ -729,6 +741,9 @@ extern "C" void Java_org_ppsspp_ppsspp_NativeRenderer_displayInit(JNIEnv * env, extern "C" void JNICALL Java_org_ppsspp_ppsspp_NativeApp_backbufferResize(JNIEnv *, jclass, jint bufw, jint bufh, jint format) { ILOG("NativeApp.backbufferResize(%d x %d)", bufw, bufh); + bool new_size = pixel_xres != bufw || pixel_yres != bufh; + int old_w = pixel_xres; + int old_h = pixel_yres; // pixel_*res is the backbuffer resolution. pixel_xres = bufw; pixel_yres = bufh; @@ -755,7 +770,12 @@ extern "C" void JNICALL Java_org_ppsspp_ppsspp_NativeApp_backbufferResize(JNIEnv ILOG("dp_xres=%d dp_yres=%d", dp_xres, dp_yres); ILOG("pixel_xres=%d pixel_yres=%d", pixel_xres, pixel_yres); - NativeResized(); + if (new_size) { + ILOG("Size change detected (previously %d,%d) - calling NativeResized()", old_w, old_h); + NativeResized(); + } else { + ILOG("Size didn't change."); + } } @@ -1124,7 +1144,7 @@ retry: ProcessFrameCommands(env); } - ILOG("After render loop."); + ILOG("Leaving EGL/Vulkan render loop."); g_gameInfoCache->WorkQueue()->Flush(); NativeDeviceLost(); diff --git a/android/src/org/ppsspp/ppsspp/NativeActivity.java b/android/src/org/ppsspp/ppsspp/NativeActivity.java index b48cfae5c1..3f6245e65f 100644 --- a/android/src/org/ppsspp/ppsspp/NativeActivity.java +++ b/android/src/org/ppsspp/ppsspp/NativeActivity.java @@ -58,7 +58,7 @@ public abstract class NativeActivity extends Activity implements SurfaceHolder.C // Remember to loadLibrary your JNI .so in a static {} block // Adjust these as necessary - private static String TAG = "NativeActivity"; + private static String TAG = "PPSSPPNativeActivity"; // Allows us to skip a lot of initialization on secondary calls to onCreate. private static boolean initialized = false; @@ -518,24 +518,30 @@ public abstract class NativeActivity extends Activity implements SurfaceHolder.C } } + private Point desiredSize = new Point(); + @Override public void surfaceCreated(SurfaceHolder holder) { pixelWidth = holder.getSurfaceFrame().width(); pixelHeight = holder.getSurfaceFrame().height(); - Log.d(TAG, "Surface created. pixelWidth=" + pixelWidth + ", pixelHeight=" + pixelHeight); + Log.d(TAG, "Surface created. pixelWidth=" + pixelWidth + ", pixelHeight=" + pixelHeight + " holder: " + holder.toString()); NativeApp.setDisplayParameters(pixelWidth, pixelHeight, (int)densityDpi, refreshRate); - Point sz = new Point(); - getDesiredBackbufferSize(sz); - Log.d(TAG, "Setting fixed size " + sz.x + " x " + sz.y); - if (mGLSurfaceView != null) { - mGLSurfaceView.getHolder().setFixedSize(sz.x, sz.y); - } else { - mSurfaceView.getHolder().setFixedSize(sz.x, sz.y); - } + getDesiredBackbufferSize(desiredSize); + + // Note that desiredSize might be 0,0 here - but that's fine when calling setFixedSize! It means auto. + Log.d(TAG, "Setting fixed size " + desiredSize.x + " x " + desiredSize.y); + holder.setFixedSize(desiredSize.x, desiredSize.y); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + Log.v(TAG, "surfaceChanged: isCreating:" + holder.isCreating() + " holder: " + holder.toString()); + if (holder.isCreating() && desiredSize.x > 0 && desiredSize.y > 0) { + // We have called setFixedSize which will trigger another surfaceChanged after the initial one. This one is the original one + // and we don't care about it. + Log.w(TAG, "holder.isCreating = true, ignoring. width=" + width + " height=" + height + " desWidth=" + desiredSize.x + " desHeight=" + desiredSize.y); + return; + } Log.w(TAG, "Surface changed. Resolution: " + width + "x" + height + " Format: " + format); NativeApp.backbufferResize(width, height, format); mSurface = holder.getSurface(); @@ -647,10 +653,10 @@ public abstract class NativeActivity extends Activity implements SurfaceHolder.C loseAudioFocus(this.audioManager, this.audioFocusChangeListener); NativeApp.pause(); if (!javaGL) { - Log.i(TAG, "Pausing surface view"); mSurfaceView.onPause(); - Log.i(TAG, "Joining render thread"); + Log.i(TAG, "Joining render thread..."); joinRenderLoopThread(); + Log.i(TAG, "Joined render thread"); } else { if (mGLSurfaceView != null) { mGLSurfaceView.onPause(); diff --git a/assets/compat.ini b/assets/compat.ini index 6861e867ab..af21cb5f2b 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -134,6 +134,12 @@ UCKS45022 = true ULJS19009 = true NPJH50141 = true +[DisableReadbacks] +# MotoGP copies the framebuffer to RAM every frame. We have a hack to display it directly, +# which means we don't also need a readback. +ULJS00078 = true +ULUS10153 = true +UCES00373 = true [DrawSyncEatCycles] # This replaced Crash Tag Team Racing hack to also fix Gundam games diff --git a/ext/native/base/logging.h b/ext/native/base/logging.h index 6650d865b9..3bbff36204 100644 --- a/ext/native/base/logging.h +++ b/ext/native/base/logging.h @@ -53,7 +53,7 @@ void OutputDebugStringUTF8(const char *p); // Must only be used for logging #ifndef APP_NAME -#define APP_NAME "NativeApp" +#define APP_NAME "PPSSPP" #endif #ifdef _DEBUG diff --git a/ext/native/gfx_es2/draw_text_android.cpp b/ext/native/gfx_es2/draw_text_android.cpp index cb5ab910a2..c8e7ed1925 100644 --- a/ext/native/gfx_es2/draw_text_android.cpp +++ b/ext/native/gfx_es2/draw_text_android.cpp @@ -29,7 +29,8 @@ TextDrawerAndroid::TextDrawerAndroid(Draw::DrawContext *draw) : TextDrawer(draw) } else { ELOG("Failed to find class: '%s'", textRendererClassName); } - dpiScale_ = 1.0f; + dpiScale_ = CalculateDPIScale(); + ILOG("Initializing TextDrawerAndroid with DPI scale %f", dpiScale_); } TextDrawerAndroid::~TextDrawerAndroid() { @@ -269,7 +270,8 @@ void TextDrawerAndroid::OncePerFrame() { // If DPI changed (small-mode, future proper monitor DPI support), drop everything. float newDpiScale = CalculateDPIScale(); if (newDpiScale != dpiScale_) { - ILOG("Scale changed - wiping cache"); + // TODO: Don't bother if it's a no-op (cache already empty) + ILOG("DPI Scale changed (%f to %f) - wiping font cache (%d items, %d fonts)", dpiScale_, newDpiScale, (int)cache_.size(), (int)fontMap_.size()); dpiScale_ = newDpiScale; ClearCache(); fontMap_.clear(); // size is precomputed using dpiScale_. diff --git a/ext/native/thin3d/VulkanQueueRunner.cpp b/ext/native/thin3d/VulkanQueueRunner.cpp index df43465603..b2d94a6912 100644 --- a/ext/native/thin3d/VulkanQueueRunner.cpp +++ b/ext/native/thin3d/VulkanQueueRunner.cpp @@ -2,13 +2,14 @@ #include "VulkanQueueRunner.h" #include "VulkanRenderManager.h" -// Debug help: adb logcat -s DEBUG NativeActivity NativeApp PPSSPP +// Debug help: adb logcat -s DEBUG PPSSPPNativeActivity PPSSPP // TODO: This is only enough for 4x render resolution / 4x texture upscale for debugger. // Maybe we should use a dynamically allocated one for larger? const uint32_t readbackBufferSize = 2048 * 2048 * 4; void VulkanQueueRunner::CreateDeviceObjects() { + ILOG("VulkanQueueRunner::CreateDeviceObjects"); InitBackbufferRenderPass(); InitRenderpasses(); @@ -36,16 +37,22 @@ void VulkanQueueRunner::CreateDeviceObjects() { } void VulkanQueueRunner::DestroyDeviceObjects() { + ILOG("VulkanQueueRunner::DestroyDeviceObjects"); VkDevice device = vulkan_->GetDevice(); + vulkan_->Delete().QueueDeleteDeviceMemory(readbackMemory_); vkFreeMemory(device, readbackMemory_, nullptr); + readbackMemory_ = VK_NULL_HANDLE; vulkan_->Delete().QueueDeleteBuffer(readbackBuffer_); + readbackBuffer_ = VK_NULL_HANDLE; for (int i = 0; i < ARRAY_SIZE(renderPasses_); i++) { assert(renderPasses_[i] != VK_NULL_HANDLE); - vkDestroyRenderPass(device, renderPasses_[i], nullptr); + vulkan_->Delete().QueueDeleteRenderPass(renderPasses_[i]); + renderPasses_[i] = VK_NULL_HANDLE; } assert(backbufferRenderPass_ != VK_NULL_HANDLE); - vkDestroyRenderPass(device, backbufferRenderPass_, nullptr); + vulkan_->Delete().QueueDeleteRenderPass(backbufferRenderPass_); + backbufferRenderPass_ = VK_NULL_HANDLE; } void VulkanQueueRunner::InitBackbufferRenderPass() { @@ -341,7 +348,6 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c vkCmdPipelineBarrier(cmd, srcStage, dstStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); iter.fb->color.layout = barrier.newLayout; } - iter.fb->Release(); } // Don't execute empty renderpasses. @@ -419,8 +425,8 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c VkClearRect rc{}; rc.baseArrayLayer = 0; rc.layerCount = 1; - rc.rect.extent.width = curWidth; - rc.rect.extent.height = curHeight; + rc.rect.extent.width = (uint32_t)curWidth; + rc.rect.extent.height = (uint32_t)curHeight; VkClearAttachment attachments[2]; if (c.clear.clearMask & VK_IMAGE_ASPECT_COLOR_BIT) { VkClearAttachment &attachment = attachments[numAttachments++]; @@ -436,7 +442,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c attachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT; } if (c.clear.clearMask & VK_IMAGE_ASPECT_STENCIL_BIT) { - attachment.clearValue.depthStencil.stencil = c.clear.clearStencil; + attachment.clearValue.depthStencil.stencil = (uint32_t)c.clear.clearStencil; attachment.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } } @@ -594,10 +600,6 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step rp_begin.clearValueCount = numClearVals; rp_begin.pClearValues = numClearVals ? clearVal : nullptr; vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); - - if (step.render.framebuffer) { - step.render.framebuffer->Release(); - } } void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) { @@ -671,9 +673,6 @@ void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) { } vkCmdCopyImage(cmd, src->depth.image, src->depth.layout, dst->depth.image, dst->depth.layout, 1, ©); } - - src->Release(); - dst->Release(); } void VulkanQueueRunner::PerformBlit(const VKRStep &step, VkCommandBuffer cmd) { @@ -757,9 +756,6 @@ void VulkanQueueRunner::PerformBlit(const VKRStep &step, VkCommandBuffer cmd) { } vkCmdBlitImage(cmd, src->depth.image, src->depth.layout, dst->depth.image, dst->depth.layout, 1, &blit, step.blit.filter); } - - src->Release(); - dst->Release(); } void VulkanQueueRunner::SetupTransitionToTransferSrc(VKRImage &img, VkImageMemoryBarrier &barrier, VkPipelineStageFlags &stage, VkImageAspectFlags aspect) { @@ -860,8 +856,6 @@ void VulkanQueueRunner::PerformReadback(const VKRStep &step, VkCommandBuffer cmd vkCmdCopyImageToBuffer(cmd, srcImage->image, srcImage->layout, readbackBuffer_, 1, ®ion); // NOTE: Can't read the buffer using the CPU here - need to sync first. - - step.readback.src->Release(); } void VulkanQueueRunner::PerformReadbackImage(const VKRStep &step, VkCommandBuffer cmd) { diff --git a/ext/native/thin3d/VulkanRenderManager.cpp b/ext/native/thin3d/VulkanRenderManager.cpp index 03d1d3b0ce..c29b3294e8 100644 --- a/ext/native/thin3d/VulkanRenderManager.cpp +++ b/ext/native/thin3d/VulkanRenderManager.cpp @@ -96,16 +96,6 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int img.format = format; } -bool VKRFramebuffer::Release() { - if (--refcount_ == 0) { - delete this; - return true; - } else if (refcount_ >= 10000 || refcount_ < 0) { - ELOG("Refcount (%d) invalid for object %p - corrupt?", refcount_.load(), this); - } - return false; -} - VulkanRenderManager::VulkanRenderManager(VulkanContext *vulkan) : vulkan_(vulkan), queueRunner_(vulkan) { VkSemaphoreCreateInfo semaphoreCreateInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; semaphoreCreateInfo.flags = 0; @@ -194,12 +184,12 @@ void VulkanRenderManager::CreateBackbuffers() { run_ = true; // Won't necessarily be 0. threadInitFrame_ = vulkan_->GetCurFrame(); - VLOG("starting thread"); + ILOG("Starting Vulkan submission thread (threadInitFrame_ = %d)", vulkan_->GetCurFrame()); thread_ = std::thread(&VulkanRenderManager::ThreadFunc, this); } } -void VulkanRenderManager::StopThread(bool shutdown) { +void VulkanRenderManager::StopThread() { if (useThread && run_) { run_ = false; // Stop the thread. @@ -215,12 +205,21 @@ void VulkanRenderManager::StopThread(bool shutdown) { } } thread_.join(); - VLOG("thread joined."); + ILOG("Vulkan submission thread joined. Frame=%d", vulkan_->GetCurFrame()); + + // Eat whatever has been queued up for this frame if anything. + Wipe(); // Wait for any fences to finish and be resignaled, so we don't have sync issues. + // Also clean out any queued data, which might refer to things that might not be valid + // when we restart... for (int i = 0; i < vulkan_->GetInflightFrames(); i++) { auto &frameData = frameData_[i]; + if (frameData.readyForRun || frameData.hasInitCommands || frameData.steps.size() != 0) { + Crash(); + } frameData.readyForRun = false; + frameData.steps.clear(); std::unique_lock lock(frameData.push_mutex); while (!frameData.readyForFence) { @@ -228,11 +227,13 @@ void VulkanRenderManager::StopThread(bool shutdown) { frameData.push_condVar.wait(lock); } } + } else { + ILOG("Vulkan submission thread was already stopped."); } } void VulkanRenderManager::DestroyBackbuffers() { - StopThread(false); + StopThread(); vulkan_->WaitUntilQueueIdle(); VkDevice device = vulkan_->GetDevice(); @@ -253,7 +254,8 @@ void VulkanRenderManager::DestroyBackbuffers() { } VulkanRenderManager::~VulkanRenderManager() { - StopThread(true); + ILOG("VulkanRenderManager destructor"); + StopThread(); vulkan_->WaitUntilQueueIdle(); VkDevice device = vulkan_->GetDevice(); @@ -274,6 +276,7 @@ void VulkanRenderManager::ThreadFunc() { setCurrentThreadName("RenderMan"); int threadFrame = threadInitFrame_; bool nextFrame = false; + bool firstFrame = true; while (true) { { if (nextFrame) { @@ -301,9 +304,17 @@ void VulkanRenderManager::ThreadFunc() { assert(frameData.type == VKRRunType::END || frameData.type == VKRRunType::SYNC); } VLOG("PULL: Running frame %d", threadFrame); + if (firstFrame) { + ILOG("Running first frame (%d)", threadFrame); + firstFrame = false; + } Run(threadFrame); VLOG("PULL: Finished frame %d", threadFrame); } + + // Wait for the device to be done with everything, before tearing stuff down. + vkDeviceWaitIdle(vulkan_->GetDevice()); + VLOG("PULL: Quitting"); } @@ -330,6 +341,9 @@ void VulkanRenderManager::BeginFrame() { // Must be after the fence - this performs deletes. VLOG("PUSH: BeginFrame %d", curFrame); + if (!run_) { + WLOG("BeginFrame while !run_!"); + } vulkan_->BeginFrame(); insideFrame_ = true; @@ -368,9 +382,7 @@ void VulkanRenderManager::BindFramebufferAsRenderTarget(VKRFramebuffer *fb, VKRR curRenderStep_ = nullptr; } if (curRenderStep_ && curRenderStep_->commands.size() == 0) { -#ifdef _DEBUG - ILOG("Empty render step. Usually happens after uploading pixels.."); -#endif + VLOG("Empty render step. Usually happens after uploading pixels.."); } VKRStep *step = new VKRStep{ VKRStepType::RENDER }; @@ -384,9 +396,6 @@ void VulkanRenderManager::BindFramebufferAsRenderTarget(VKRFramebuffer *fb, VKRR step->render.numDraws = 0; step->render.finalColorLayout = !fb ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED; steps_.push_back(step); - if (fb) { - fb->AddRef(); - } curRenderStep_ = step; curWidth_ = fb ? fb->width : vulkan_->GetBackbufferWidth(); @@ -400,7 +409,6 @@ void VulkanRenderManager::CopyFramebufferToMemorySync(VKRFramebuffer *src, int a step->readback.srcRect.offset = { x, y }; step->readback.srcRect.extent = { (uint32_t)w, (uint32_t)h }; steps_.push_back(step); - src->AddRef(); curRenderStep_ = nullptr; @@ -577,8 +585,6 @@ void VulkanRenderManager::CopyFramebuffer(VKRFramebuffer *src, VkRect2D srcRect, step->copy.srcRect = srcRect; step->copy.dst = dst; step->copy.dstPos = dstPos; - src->AddRef(); - dst->AddRef(); std::unique_lock lock(mutex_); steps_.push_back(step); @@ -610,8 +616,6 @@ void VulkanRenderManager::BlitFramebuffer(VKRFramebuffer *src, VkRect2D srcRect, step->blit.dst = dst; step->blit.dstRect = dstRect; step->blit.filter = filter; - src->AddRef(); - dst->AddRef(); std::unique_lock lock(mutex_); steps_.push_back(step); @@ -635,7 +639,6 @@ VkImageView VulkanRenderManager::BindFramebufferAsTexture(VKRFramebuffer *fb, in } curRenderStep_->preTransitions.push_back({ fb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }); - fb->AddRef(); return fb->color.imageView; } @@ -662,29 +665,6 @@ void VulkanRenderManager::Finish() { void VulkanRenderManager::Wipe() { for (auto step : steps_) { - // Need to release held framebuffers. - switch (step->stepType) { - case VKRStepType::RENDER: - for (const auto &iter : step->preTransitions) { - iter.fb->Release(); - } - break; - case VKRStepType::COPY: - step->copy.src->Release(); - step->copy.dst->Release(); - break; - case VKRStepType::BLIT: - step->blit.src->Release(); - step->blit.dst->Release(); - break; - case VKRStepType::READBACK: - step->readback.src->Release(); - break; - case VKRStepType::READBACK_IMAGE: - break; - default: - assert(false); - } delete step; } steps_.clear(); diff --git a/ext/native/thin3d/VulkanRenderManager.h b/ext/native/thin3d/VulkanRenderManager.h index a9faf1ccdd..1c17b42ac4 100644 --- a/ext/native/thin3d/VulkanRenderManager.h +++ b/ext/native/thin3d/VulkanRenderManager.h @@ -29,7 +29,6 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int class VKRFramebuffer { public: VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRenderPass renderPass, int _width, int _height) : vulkan_(vk) { - refcount_ = 1; width = _width; height = _height; @@ -50,6 +49,7 @@ public: vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf); } + ~VKRFramebuffer() { vulkan_->Delete().QueueDeleteImage(color.image); vulkan_->Delete().QueueDeleteImage(depth.image); @@ -60,11 +60,6 @@ public: vulkan_->Delete().QueueDeleteFramebuffer(framebuf); } - void AddRef() { - refcount_++; - } - bool Release(); - int numShadows = 1; // TODO: Support this. VkFramebuffer framebuf = VK_NULL_HANDLE; @@ -73,9 +68,7 @@ public: int width = 0; int height = 0; -private: VulkanContext *vulkan_; - std::atomic refcount_; }; enum class VKRRunType { @@ -222,7 +215,7 @@ private: void FlushSync(); void EndSyncFrame(int frame); - void StopThread(bool shutdown); + void StopThread(); // Permanent objects VkSemaphore acquireSemaphore_; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 1925f057c3..929e84581a 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -193,7 +193,7 @@ public: const std::string &GetSource() const { return source_; } ~VKShaderModule() { if (module_) { - vkDestroyShaderModule(device_, module_, nullptr); + vulkan_->Delete().QueueDeleteShaderModule(module_); } } VkShaderModule Get() const { return module_; } @@ -202,7 +202,7 @@ public: } private: - VkDevice device_; + VulkanContext *vulkan_; VkShaderModule module_; VkShaderStageFlagBits vkstage_; bool ok_; @@ -211,9 +211,9 @@ private: }; bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, const uint8_t *data, size_t size) { + vulkan_ = vulkan; // We'll need this to free it later. - device_ = vulkan->GetDevice(); - this->source_ = (const char *)data; + source_ = (const char *)data; std::vector spirv; if (!GLSLtoSPV(vkstage_, source_.c_str(), spirv)) { return false; @@ -374,7 +374,7 @@ public: void CopyFramebufferImage(Framebuffer *src, int level, int x, int y, int z, Framebuffer *dst, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth, int channelBits) override; bool BlitFramebuffer(Framebuffer *src, int srcX1, int srcY1, int srcX2, int srcY2, Framebuffer *dst, int dstX1, int dstY1, int dstX2, int dstY2, int channelBits, FBBlitFilter filter) override; - bool CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride); + bool CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride) override; // These functions should be self explanatory. void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp) override; @@ -1251,7 +1251,10 @@ public: // Inherits ownership so no AddRef. VKFramebuffer(VKRFramebuffer *fb) : buf_(fb) {} ~VKFramebuffer() { - buf_->Release(); + buf_->vulkan_->Delete().QueueCallback([](void *fb) { + VKRFramebuffer *vfb = static_cast(fb); + delete vfb; + }, buf_); } VKRFramebuffer *GetFB() const { return buf_; } private: diff --git a/ext/native/thread/prioritizedworkqueue.cpp b/ext/native/thread/prioritizedworkqueue.cpp index f3b6d3f0e7..1583738f40 100644 --- a/ext/native/thread/prioritizedworkqueue.cpp +++ b/ext/native/thread/prioritizedworkqueue.cpp @@ -31,7 +31,9 @@ void PrioritizedWorkQueue::Flush() { flush_count++; } queue_.clear(); - ILOG("Flushed %d un-executed tasks", flush_count); + if (flush_count > 0) { + ILOG("PrioritizedWorkQueue: Flushed %d un-executed tasks", flush_count); + } } bool PrioritizedWorkQueue::WaitUntilDone(bool all) {