diff --git a/CMakeLists.txt b/CMakeLists.txt index f4185d47ac..e6f437726e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,9 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/CMakeTests) add_definitions(-DPPSSPP) +# None of these platforms support Vulkan yet. +add_definitions(-DNO_VULKAN) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(_ARCH_64 1) add_definitions(-D_ARCH_64=1) diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index 91be776722..2fb7c33a0b 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -170,6 +170,7 @@ true false MultiThreaded + true Windows @@ -239,6 +240,11 @@ + + + + + @@ -307,6 +313,11 @@ + + + + + diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index cc8b91d6ad..1dcbacabe5 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -58,6 +58,21 @@ + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + @@ -103,6 +118,21 @@ GL\GLInterface + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + @@ -117,5 +147,8 @@ {2c723cf4-75b6-406a-90c0-ebb7a13ba476} + + {c14d66ef-5f7c-4565-975a-72774e7ccfb9} + \ No newline at end of file diff --git a/Common/GraphicsContext.h b/Common/GraphicsContext.h index 9ed4f21d77..f0f419cb1e 100644 --- a/Common/GraphicsContext.h +++ b/Common/GraphicsContext.h @@ -22,6 +22,9 @@ public: virtual void Resize() = 0; + // Needs casting to the appropriate type, unfortunately. Should find a better solution.. + virtual void *GetAPIContext() { return nullptr; } + virtual Thin3DContext *CreateThin3DContext() = 0; }; diff --git a/Common/Vulkan/SPIRVDisasm.cpp b/Common/Vulkan/SPIRVDisasm.cpp new file mode 100644 index 0000000000..85bcde7485 --- /dev/null +++ b/Common/Vulkan/SPIRVDisasm.cpp @@ -0,0 +1,616 @@ +#include + +#include "Common/StringUtils.h" +#include "Common/Vulkan/SPIRVDisasm.h" +#include "ext/vulkan/spirv.hpp" + +#define WRITE p+=sprintf + +struct SpirvID { + std::string name; + int opcode; +}; + +struct OpInfo { + const char *name; + const char *extra; +}; + +static const char *executionModelNames[] = { + "Vertex", // 0, + "TessellationControl", // 1, + "TessellationEvaluation", // 2, + "Geometry", // 3, + "Fragment", // 4, + "GLCompute", // 5, + "Kernel", // 6, +}; + +static const char *storageClassNames[] = { + "UniformConstant", + "Input", + "Uniform", + "Output", + "Workgroup", + "CrossWorkgroup", + "Private", + "Function", + "Generic", + "PushConstant", + "AtomicCounter", + "Image", +}; + +static const char *decorationNames[] = { + "RelaxedPrecision", // 0, + "SpecId", // 1, + "Block", // 2, + "BufferBlock", // 3, + "RowMajor", // 4, + "ColMajor", // 5, + "ArrayStride", // 6, + "MatrixStride", // 7, + "GLSLShared", // 8, + "GLSLPacked", // 9, + "CPacked", // 10, + "BuiltIn", // 11, + nullptr, // 12 + "NoPerspective", // 13, + "Flat", // 14, + "Patch", // 15, + "Centroid", // 16, + "Sample", // 17, + "Invariant", // 18, + "Restrict", // 19, + "Aliased", // 20, + "Volatile", // 21, + "Constant", // 22, + "Coherent", // 23, + "NonWritable", // 24, + "NonReadable", // 25, + "Uniform", // 26, + nullptr, // 27 + "SaturatedConversion", // 28, + "Stream", // 29, + "Location", // 30, + "Component", // 31, + "Index", // 32, + "Binding", // 33, + "DescriptorSet", // 34, + "Offset", // 35, + "XfbBuffer", // 36, + "XfbStride", // 37, + "FuncParamAttr", // 38, + "FPRoundingMode", // 39, + "FPFastMathMode", // 40, + "LinkageAttributes", // 41, + "NoContraction", // 42, + "InputAttachmentIndex", // 43, + "Alignment", // 44, +}; + +static const OpInfo opInfo[] = { + {"Nop"}, // 0, + {"Undef"}, // 1, + {"SourceContinued"}, // 2, + {"Source"}, // 3, + {"SourceExtension"}, // 4, + {"Name"}, // 5, + {"MemberName"}, // 6, + {"String"}, // 7, + {"Line"}, // 8, + {nullptr}, // 9 + {"Extension"}, // 10, + {"ExtInstImport"}, // 11, + {"ExtInst"}, // 12, + {nullptr}, // 13 + {"MemoryModel"}, // 14, + {"EntryPoint"}, // 15, + {"ExecutionMode"}, // 16, + {"Capability"}, // 17, + {nullptr}, // 18 + {"TypeVoid"}, // 19, + {"TypeBool"}, // 20, + {"TypeInt"}, // 21, + {"TypeFloat"}, // 22, + {"TypeVector"}, // 23, + {"TypeMatrix"}, // 24, + {"TypeImage"}, // 25, + {"TypeSampler"}, // 26, + {"TypeSampledImage"}, // 27, + {"TypeArray"}, // 28, + {"TypeRuntimeArray"}, // 29, + {"TypeStruct"}, // 30, + {"TypeOpaque"}, // 31, + {"TypePointer"}, // 32, + {"TypeFunction"}, // 33, + {"TypeEvent"}, // 34, + {"TypeDeviceEvent"}, // 35, + {"TypeReserveId"}, // 36, + {"TypeQueue"}, // 37, + {"TypePipe"}, // 38, + {"TypeForwardPointer"}, // 39, + {nullptr}, // 40 + {"ConstantTrue"}, // 41, + {"ConstantFalse"}, // 42, + {"Constant"}, // 43, + {"ConstantComposite"}, // 44, + {"ConstantSampler"}, // 45, + {"ConstantNull"}, // 46, + {nullptr}, // 47 + {"SpecConstantTrue"}, // 48, + {"SpecConstantFalse"}, // 49, + {"SpecConstant"}, // 50, + {"SpecConstantComposite"}, // 51, + {"SpecConstantOp"}, // 52, + {nullptr}, // 53 + {"Function"}, // 54, + {"FunctionParameter"}, // 55, + {"FunctionEnd"}, // 56, + {"FunctionCall"}, // 57, + {nullptr}, // 58 + {"Variable"}, // 59, + {"ImageTexelPointer"}, // 60, + {"Load"}, // 61, + {"Store"}, // 62, + {"CopyMemory"}, // 63, + {"CopyMemorySized"}, // 64, + {"AccessChain"}, // 65, + {"InBoundsAccessChain"}, // 66, + {"PtrAccessChain"}, // 67, + {"ArrayLength"}, // 68, + {"GenericPtrMemSemantics"}, // 69, + {"InBoundsPtrAccessChain"}, // 70, + {"Decorate"}, // 71, + {"MemberDecorate"}, // 72, + {"DecorationGroup"}, // 73, + {"GroupDecorate"}, // 74, + {"GroupMemberDecorate"}, // 75, + {nullptr}, // 76 + {"VectorExtractDynamic"}, // 77, + {"VectorInsertDynamic"}, // 78, + {"VectorShuffle"}, // 79, + {"CompositeConstruct"}, // 80, + {"CompositeExtract"}, // 81, + {"CompositeInsert"}, // 82, + {"CopyObject"}, // 83, + {"Transpose"}, // 84, + {nullptr}, // 85 + {"SampledImage"}, // 86, + {"ImageSampleImplicitLod"}, // 87, + {"ImageSampleExplicitLod"}, // 88, + {"ImageSampleDrefImplicitLod"}, // 89, + {"ImageSampleDrefExplicitLod"}, // 90, + {"ImageSampleProjImplicitLod"}, // 91, + {"ImageSampleProjExplicitLod"}, // 92, + {"ImageSampleProjDrefImplicitLod"}, // 93, + {"ImageSampleProjDrefExplicitLod"}, // 94, + {"ImageFetch"}, // 95, + {"ImageGather"}, // 96, + {"ImageDrefGather"}, // 97, + {"ImageRead"}, // 98, + {"ImageWrite"}, // 99, + {"Image"}, // 100, + {"ImageQueryFormat"}, // 101, + {"ImageQueryOrder"}, // 102, + {"ImageQuerySizeLod"}, // 103, + {"ImageQuerySize"}, // 104, + {"ImageQueryLod"}, // 105, + {"ImageQueryLevels"}, // 106, + {"ImageQuerySamples"}, // 107, + {nullptr}, // 108 + {"ConvertFToU"}, // 109, + {"ConvertFToS"}, // 110, + {"ConvertSToF"}, // 111, + {"ConvertUToF"}, // 112, + {"UConvert"}, // 113, + {"SConvert"}, // 114, + {"FConvert"}, // 115, + {"QuantizeToF16"}, // 116, + {"ConvertPtrToU"}, // 117, + {"SatConvertSToU"}, // 118, + {"SatConvertUToS"}, // 119, + {"ConvertUToPtr"}, // 120, + {"PtrCastToGeneric"}, // 121, + {"GenericCastToPtr"}, // 122, + {"GenericCastToPtrExplicit"}, // 123, + {"Bitcast"}, // 124, + {nullptr}, // 125 + {"SNegate"}, // 126, + {"FNegate"}, // 127, + {"IAdd"}, // 128, + {"FAdd", "+"}, // 129, + {"ISub"}, // 130, + {"FSub", "-"}, // 131, + {"IMul"}, // 132, + {"FMul", "*"}, // 133, + {"UDiv"}, // 134, + {"SDiv"}, // 135, + {"FDiv", "/"}, // 136, + {"UMod"}, // 137, + {"SRem"}, // 138, + {"SMod"}, // 139, + {"FRem"}, // 140, + {"FMod", "%"}, // 141, + {"VectorTimesScalar"}, // 142, + {"MatrixTimesScalar"}, // 143, + {"VectorTimesMatrix"}, // 144, + {"MatrixTimesVector"}, // 145, + {"MatrixTimesMatrix"}, // 146, + {"OuterProduct"}, // 147, + {"Dot", " dot "}, // 148, + {"IAddCarry"}, // 149, + {"ISubBorrow"}, // 150, + {"UMulExtended"}, // 151, + {"SMulExtended"}, // 152, + {nullptr}, // 153 + {"Any"}, // 154, + {"All"}, // 155, + {"IsNan"}, // 156, + {"IsInf"}, // 157, + {"IsFinite"}, // 158, + {"IsNormal"}, // 159, + {"SignBitSet"}, // 160, + {"LessOrGreater"}, // 161, + {"Ordered"}, // 162, + {"Unordered"}, // 163, + {"LogicalEqual"}, // 164, + {"LogicalNotEqual"}, // 165, + {"LogicalOr"}, // 166, + {"LogicalAnd"}, // 167, + {"LogicalNot"}, // 168, + {"Select"}, // 169, + {"IEqual"}, // 170, + {"INotEqual"}, // 171, + {"UGreaterThan"}, // 172, + {"SGreaterThan"}, // 173, + {"UGreaterThanEqual"}, // 174, + {"SGreaterThanEqual"}, // 175, + {"ULessThan"}, // 176, + {"SLessThan"}, // 177, + {"ULessThanEqual"}, // 178, + {"SLessThanEqual"}, // 179, + {"FOrdEqual", "=="}, // 180, + {"FUnordEqual", "=="}, // 181, + {"FOrdNotEqual", "!="}, // 182, + {"FUnordNotEqual", "!="}, // 183, + {"FOrdLessThan"}, // 184, + {"FUnordLessThan"}, // 185, + {"FOrdGreaterThan"}, // 186, + {"FUnordGreaterThan"}, // 187, + {"FOrdLessThanEqual"}, // 188, + {"FUnordLessThanEqual"}, // 189, + {"FOrdGreaterThanEqual"}, // 190, + {"FUnordGreaterThanEqual"}, // 191, + { nullptr }, // 192 + { nullptr }, // 193 + {"ShiftRightLogical"}, // 194, + {"ShiftRightArithmetic"}, // 195, + {"ShiftLeftLogical"}, // 196, + {"BitwiseOr", "|"}, // 197, + {"BitwiseXor", "^"}, // 198, + {"BitwiseAnd", "&"}, // 199, + {"Not", "~"}, // 200, + {"BitFieldInsert"}, // 201, + {"BitFieldSExtract"}, // 202, + {"BitFieldUExtract"}, // 203, + {"BitReverse"}, // 204, + {"BitCount"}, // 205, + {nullptr}, + {"DPdx"}, // 207, + {"DPdy"}, // 208, + {"Fwidth"}, // 209, + {"DPdxFine"}, // 210, + {"DPdyFine"}, // 211, + {"FwidthFine"}, // 212, + {"DPdxCoarse"}, // 213, + {"DPdyCoarse"}, // 214, + {"FwidthCoarse"}, // 215, + {nullptr}, // 216 + {nullptr}, // 217 + {"EmitVertex"}, // 218, + {"EndPrimitive"}, // 219, + {"EmitStreamVertex"}, // 220, + {"EndStreamPrimitive"}, // 221, + {nullptr}, // 222 + {nullptr}, // 223 + {"ControlBarrier"}, // 224, + {"MemoryBarrier"}, // 225, + {nullptr}, // 226 + {"AtomicLoad"}, // 227, + {"AtomicStore"}, // 228, + {"AtomicExchange"}, // 229, + {"AtomicCompareExchange"}, // 230, + {"AtomicCompareExchangeWeak"}, // 231, + {"AtomicIIncrement"}, // 232, + {"AtomicIDecrement"}, // 233, + {"AtomicIAdd"}, // 234, + {"AtomicISub"}, // 235, + {"AtomicSMin"}, // 236, + {"AtomicUMin"}, // 237, + {"AtomicSMax"}, // 238, + {"AtomicUMax"}, // 239, + {"AtomicAnd"}, // 240, + {"AtomicOr"}, // 241, + {"AtomicXor"}, // 242, + { nullptr }, // 243, + { nullptr }, // 244, + {"Phi"}, // 245, + {"LoopMerge"}, // 246, + {"SelectionMerge"}, // 247, + {"Label"}, // 248, + {"Branch"}, // 249, + {"BranchConditional"}, // 250, + {"Switch"}, // 251, + {"Kill"}, // 252, + {"Return"}, // 253, + {"ReturnValue"}, // 254, + {"Unreachable"}, // 255, + {"LifetimeStart"}, // 256, + {"LifetimeStop"}, // 257, + { nullptr }, + {"GroupAsyncCopy"}, // 259, + {"GroupWaitEvents"}, // 260, + {"GroupAll"}, // 261, + {"GroupAny"}, // 262, + {"GroupBroadcast"}, // 263, + {"GroupIAdd"}, // 264, + {"GroupFAdd"}, // 265, + {"GroupFMin"}, // 266, + {"GroupUMin"}, // 267, + {"GroupSMin"}, // 268, + {"GroupFMax"}, // 269, + {"GroupUMax"}, // 270, + {"GroupSMax"}, // 271, + {nullptr}, // 272 + {nullptr}, // 273 + {"ReadPipe"}, // 274, + {"WritePipe"}, // 275, + {"ReservedReadPipe"}, // 276, + {"ReservedWritePipe"}, // 277, + {"ReserveReadPipePackets"}, // 278, + {"ReserveWritePipePackets"}, // 279, + {"CommitReadPipe"}, // 280, + {"CommitWritePipe"}, // 281, + {"IsValidReserveId"}, // 282, + {"GetNumPipePackets"}, // 283, + {"GetMaxPipePackets"}, // 284, + {"GroupReserveReadPipePackets"}, // 285, + {"GroupReserveWritePipePackets"}, // 286, + {"GroupCommitReadPipe"}, // 287, + {"GroupCommitWritePipe"}, // 288, + { nullptr }, // 289 + { nullptr }, // 290 + {"EnqueueMarker"}, // 291, + {"EnqueueKernel"}, // 292, + {"GetKernelNDrangeSubGroupCount"}, // 293, + {"GetKernelNDrangeMaxSubGroupSize"}, // 294, + {"GetKernelWorkGroupSize"}, // 295, + {"GetKernelPreferredWorkGroupSizeMultiple"}, // 296, + {"RetainEvent"}, // 297, + {"ReleaseEvent"}, // 298, + {"CreateUserEvent"}, // 299, + {"IsValidEvent"}, // 300, + {"SetUserEventStatus"}, // 301, + {"CaptureEventProfilingInfo"}, // 302, + {"GetDefaultQueue"}, // 303, + {"BuildNDRange"}, // 304, + {"ImageSparseSampleImplicitLod"}, // 305, + {"ImageSparseSampleExplicitLod"}, // 306, + {"ImageSparseSampleDrefImplicitLod"}, // 307, + {"ImageSparseSampleDrefExplicitLod"}, // 308, + {"ImageSparseSampleProjImplicitLod"}, // 309, + {"ImageSparseSampleProjExplicitLod"}, // 310, + {"ImageSparseSampleProjDrefImplicitLod"}, // 311, + {"ImageSparseSampleProjDrefExplicitLod"}, // 312, + {"ImageSparseFetch"}, // 313, + {"ImageSparseGather"}, // 314, + {"ImageSparseDrefGather"}, // 315, + {"ImageSparseTexelsResident"}, // 316, + {"NoLine"}, // 317, + {"AtomicFlagTestAndSet"}, // 318, + {"AtomicFlagClear"}, // 319, +}; + +static std::string ReadSpirvString(const std::vector &spirv, int offset, int *outOffset = nullptr) { + bool done = false; + std::string temp; + while (!done) { + uint32_t data = spirv[offset++]; + for (int i = 0; i < 4; i++) { + char c = (char)(data & 0xff); + if (!c) { + done = true; + break; + } + temp.push_back(data); + data >>= 8; + } + if (offset == (int)spirv.size()) + break; + } + if (outOffset) + *outOffset = offset; + return temp; +} + +bool DisassembleSPIRV(std::vector spirv, std::string *output) { + if (spirv.size() < 10) { + *output = "Too small"; + return false; + } + uint32_t magic = spirv[0]; + uint32_t version = spirv[1]; + uint32_t generator = spirv[2]; + + int bound = (int)spirv[3]; // Max ID used in file. + // spirv[4] is reserved for schema. + std::vector ids; + ids.resize(bound); + for (int i = 0; i < bound; i++) { + ids[i].name = StringFromFormat("%%%d", i); + } + + if (magic != 0x07230203) { + *output = "Not SPIRV"; + return false; + } + + int indent = 0; + + char *buffer = new char[1024 * 1024]; + char *p = buffer; + + WRITE(p, "// ======= SPIR-V version %08x =======\n// Max ID: %d\n", version, bound); // GLSL ES + + int i = 5; + while (i < (int)spirv.size()) { + uint32_t d = spirv[i]; + int wordCount = d >> 16; + int opcode = d & 0xFFFF; + const OpInfo &op = opInfo[opcode]; + int target = (i < (int)spirv.size() - 1) ? spirv[(i + 1)] : 0; // Not always, but used often enough that we get it here. + int source, source2, resType; + std::string name; + switch (opcode) { + case spv::OpTypeVoid: + case spv::OpTypeBool: + case spv::OpTypeInt: + case spv::OpTypeFloat: + case spv::OpTypeMatrix: + case spv::OpTypeImage: + case spv::OpTypeSampler: + case spv::OpTypeSampledImage: + case spv::OpTypeRuntimeArray: + case spv::OpTypeOpaque: + case spv::OpTypePointer: + case spv::OpTypeFunction: + case spv::OpTypeEvent: + case spv::OpTypeDeviceEvent: + case spv::OpTypeReserveId: + case spv::OpTypeQueue: + case spv::OpTypePipe: + case spv::OpTypeForwardPointer: + ids[target].name = op.name + 4; // Remove "Type" + ids[target].opcode = opcode; + break; + case spv::OpTypeVector: + source = spirv[i + 2]; + source2 = spirv[i + 3]; + ids[target].name = ids[source].name + StringFromFormat("%d", source2); break; + break; + case spv::OpTypeArray: + source = spirv[i + 2]; + source2 = spirv[i + 3]; + ids[target].name = ids[source].name + "[" + ids[source2].name + "]"; break; + break; + case spv::OpTypeStruct: + { + ids[target].name = "struct" + ids[target].name; + WRITE(p, "struct {\n"); + if (wordCount == 3) { + source = spirv[i + 2]; + WRITE(p, " %s\n", ids[source].name.c_str()); + } else { + int numMembers = (wordCount - 2) / 2; + for (int m = 0; m < numMembers; m++) { + int id = spirv[i + 2 + m]; + int type = spirv[i + 2 + m + numMembers]; + WRITE(p, " %s %s;\n", ids[type].name.c_str(), ids[id].name.c_str()); + } + } + WRITE(p, "};\n"); + } + break; + case spv::OpVariable: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + source2 = spirv[i + 4]; + ids[target].name = storageClassNames[source]; + break; + case spv::OpDecorate: + source = spirv[i + 2]; + ids[target].name += std::string("[") + decorationNames[source] + "]"; + break; + case spv::OpName: + ids[target].name = ReadSpirvString(spirv, i + 2); + // WRITE(p, "Name %d: '%s'\n", target, ids[target].name.c_str()); + break; + case spv::OpMemberName: + break; + case spv::OpStore: + source = spirv[i + 2]; + WRITE(p, "Store(%s, %s)\n", ids[target].name.c_str(), ids[source].name.c_str()); + break; + case spv::OpLoad: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + WRITE(p, "%s (%s) := Load(%s)\n", ids[target].name.c_str(), ids[resType].name.c_str(), ids[source].name.c_str()); + break; + case spv::OpFAdd: + case spv::OpFMul: + case spv::OpFDiv: + case spv::OpFSub: + resType = spirv[i + 2]; + source = spirv[i + 3]; + source2 = spirv[i + 4]; + WRITE(p, "%s (%s) := %s %s %s\n", ids[target].name.c_str(), ids[resType].name.c_str(), ids[source].name.c_str(), op.extra, ids[source2].name.c_str()); + break; + + case spv::OpCapability: + case spv::OpMemoryModel: + case spv::OpExtInstImport: + case spv::OpExecutionMode: + case spv::OpGroupAsyncCopy: + case spv::OpSource: + case spv::OpExtension: + // hide these for now + break; + + case spv::OpEntryPoint: + source = spirv[i + 1]; + source2 = spirv[i + 2]; + name = ReadSpirvString(spirv, i + 3); + WRITE(p, "EntryPoint %s: '%s' %s : %s\n", executionModelNames[target], ids[source].name.c_str(), ids[source2].name.c_str(), name.c_str()); + break; + + case spv::OpFunction: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + ids[target].name = ids[resType].name + "()"; + WRITE(p, "Function %s {\n", ids[target].name.c_str()); + break; + + case spv::OpLabel: + WRITE(p, "label %s:\n", ids[target].name.c_str()); + break; + + case spv::OpReturnValue: + WRITE(p, "return %s\n", ids[target].name.c_str()); + break; + + case spv::OpReturn: + WRITE(p, "return\n"); + break; + + case spv::OpFunctionEnd: + WRITE(p, "}\n"); + break; + + case spv::OpSourceExtension: + break; + + default: + WRITE(p, "%s (%d data words)\n", op.name, wordCount - 1); + break; + } + i += wordCount; + } + + *output = buffer; + delete[] buffer; + return true; +} \ No newline at end of file diff --git a/Common/Vulkan/SPIRVDisasm.h b/Common/Vulkan/SPIRVDisasm.h new file mode 100644 index 0000000000..d5d036fbb4 --- /dev/null +++ b/Common/Vulkan/SPIRVDisasm.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include + +// Mostly just a toy to understand SPIR-V better. Not an accurate SPIR-V disassembler, +// and the result will not reassemble. + +bool DisassembleSPIRV(std::vector spirv, std::string *output); \ No newline at end of file diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp new file mode 100644 index 0000000000..5fb745b513 --- /dev/null +++ b/Common/Vulkan/VulkanContext.cpp @@ -0,0 +1,1541 @@ +#define __STDC_LIMIT_MACROS +#include +#include +#include +#include +#include + +#include "base/basictypes.h" +#include "VulkanContext.h" + +#ifdef USE_CRT_DBG +#undef new +#endif + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4996) +#endif + +#include "ext/glslang/SPIRV/GlslangToSpv.h" + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef USE_CRT_DBG +#define new DBG_NEW +#endif + +using namespace std; + +static const char *validationLayers[] = { + "VK_LAYER_GOOGLE_unique_objects", + //"VK_LAYER_LUNARG_standard_validation", + /* + "VK_LAYER_GOOGLE_threading", + "VK_LAYER_LUNARG_draw_state", + "VK_LAYER_LUNARG_image", + "VK_LAYER_LUNARG_mem_tracker", + "VK_LAYER_LUNARG_object_tracker", + "VK_LAYER_LUNARG_param_checker", + */ +}; + +static VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names); + +VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) + : device_(nullptr), + gfx_queue_(VK_NULL_HANDLE), +#ifdef _WIN32 + connection(nullptr), + window(nullptr), +#elif defined(ANDROID) + native_window(nullptr), +#endif + graphics_queue_family_index_(-1), + surface_(VK_NULL_HANDLE), + prepared(false), + use_staging_buffer_(false), + instance_(VK_NULL_HANDLE), + width(0), + height(0), + flags_(flags), + swapchain_format(VK_FORMAT_UNDEFINED), + swapchainImageCount(0), + swap_chain_(VK_NULL_HANDLE), + cmd_pool_(VK_NULL_HANDLE), + queue_count(0), + curFrame_(0) +{ + if (!VulkanLoad()) { + init_error_ = "Failed to load Vulkan driver library"; + // No DLL? + return; + } + // List extensions to try to enable. + instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME); +#ifdef _WIN32 + instance_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); +#elif defined(ANDROID) + instance_extension_names.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME); +#endif + device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + + if (flags & VULKAN_FLAG_VALIDATE) { + for (int i = 0; i < ARRAY_SIZE(validationLayers); i++) { + instance_layer_names.push_back(validationLayers[i]); + device_layer_names.push_back(validationLayers[i]); + } + instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); + } + + VkApplicationInfo app_info = {}; + app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app_info.pNext = NULL; + app_info.pApplicationName = app_name; + app_info.applicationVersion = app_ver; + app_info.pEngineName = app_name; + // Let's increment this when we make major engine/context changes. + app_info.engineVersion = 1; + // Don't specify the API patch version. + app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0); + + VkInstanceCreateInfo inst_info = {}; + inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + inst_info.pNext = NULL; + inst_info.flags = 0; + inst_info.pApplicationInfo = &app_info; + inst_info.enabledLayerCount = (uint32_t)instance_layer_names.size(); + inst_info.ppEnabledLayerNames = instance_layer_names.size() ? instance_layer_names.data() : NULL; + inst_info.enabledExtensionCount = (uint32_t)instance_extension_names.size(); + inst_info.ppEnabledExtensionNames = instance_extension_names.size() ? instance_extension_names.data() : NULL; + + VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); + if (res != VK_SUCCESS) { + if (res == VK_ERROR_LAYER_NOT_PRESENT) { + WLOG("Validation on but layers not available - dropping layers"); + // Drop the validation layers and try again. + instance_layer_names.clear(); + device_layer_names.clear(); + inst_info.enabledLayerCount = 0; + inst_info.ppEnabledLayerNames = NULL; + res = vkCreateInstance(&inst_info, NULL, &instance_); + if (res != VK_SUCCESS) + ELOG("Failed to create instance even without validation: %d", res); + } else { + ELOG("Failed to create instance : %d", res); + } + } + if (res != VK_SUCCESS) { + init_error_ = "Failed to create Vulkan instance"; + return; + } + + VulkanLoadInstanceFunctions(instance_); + + uint32_t gpu_count = 1; + res = vkEnumeratePhysicalDevices(instance_, &gpu_count, NULL); + assert(gpu_count); + physical_devices_.resize(gpu_count); + res = vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices_.data()); + if (res != VK_SUCCESS) { + init_error_ = "Failed to enumerate physical devices"; + return; + } + + InitGlobalLayerProperties(); + InitGlobalExtensionProperties(); + + if (!CheckLayers(instance_layer_properties, instance_layer_names)) { + ELOG("CheckLayers failed"); + init_error_ = "Failed to validate instance layers"; + return; + } + + InitDeviceLayerProperties(); + if (!CheckLayers(device_layer_properties, device_layer_names)) { + ELOG("CheckLayers failed (2)"); + init_error_ = "Failed to validate device layers"; + return; + } +} + +VulkanContext::~VulkanContext() { + vkDestroyInstance(instance_, NULL); + VulkanFree(); +} + +void TransitionToPresent(VkCommandBuffer cmd, VkImage image) { + VkImageMemoryBarrier prePresentBarrier = {}; + prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + prePresentBarrier.pNext = NULL; + prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + prePresentBarrier.dstAccessMask = 0; + prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + prePresentBarrier.subresourceRange.baseMipLevel = 0; + prePresentBarrier.subresourceRange.levelCount = 1; + prePresentBarrier.subresourceRange.baseArrayLayer = 0; + prePresentBarrier.subresourceRange.layerCount = 1; + prePresentBarrier.image = image; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); +} + +void TransitionFromPresent(VkCommandBuffer cmd, VkImage image) { + VkImageMemoryBarrier prePresentBarrier = {}; + prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + prePresentBarrier.pNext = NULL; + prePresentBarrier.srcAccessMask = 0; + prePresentBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + prePresentBarrier.subresourceRange.baseMipLevel = 0; + prePresentBarrier.subresourceRange.levelCount = 1; + prePresentBarrier.subresourceRange.baseArrayLayer = 0; + prePresentBarrier.subresourceRange.layerCount = 1; + prePresentBarrier.image = image; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); +} + +VkCommandBuffer VulkanContext::GetInitCommandBuffer() { + FrameData *frame = &frame_[curFrame_]; + if (!frame->hasInitCommands) { + VulkanBeginCommandBuffer(frame->cmdInit); + frame->hasInitCommands = true; + } + return frame_[curFrame_].cmdInit; +} + +void VulkanContext::QueueBeforeSurfaceRender(VkCommandBuffer cmd) { + cmdQueue_.push_back(cmd); +} + +VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { + FrameData *frame = &frame_[curFrame_]; + + // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. + // Now, I wonder if we should do this early in the frame or late? Right now we do it early, which should be fine. + VkResult res = vkAcquireNextImageKHR(device_, swap_chain_, UINT64_MAX, acquireSemaphore, NULL, ¤t_buffer); + + // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR + // return codes + assert(res == VK_SUCCESS); + + // Make sure the very last command buffer from the frame before the previous has been fully executed. + WaitAndResetFence(frame->fence); + + // Process pending deletes. + frame->deleteList.PerformDeletes(device_); + + VkCommandBufferBeginInfo begin; + begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin.pNext = NULL; + begin.flags = 0; + begin.pInheritanceInfo = nullptr; + res = vkBeginCommandBuffer(frame->cmdBuf, &begin); + + TransitionFromPresent(frame->cmdBuf, swapChainBuffers[current_buffer].image); + + VkRenderPassBeginInfo rp_begin; + rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rp_begin.pNext = NULL; + rp_begin.renderPass = surface_render_pass_; + rp_begin.framebuffer = framebuffers_[current_buffer]; + rp_begin.renderArea.offset.x = 0; + rp_begin.renderArea.offset.y = 0; + rp_begin.renderArea.extent.width = width; + rp_begin.renderArea.extent.height = height; + rp_begin.clearValueCount = 2; + rp_begin.pClearValues = clear_values; + + // We don't really need to record this at this point in time, but hey, at some point we'll start this + // pass anyway so might as well do it now (although you can imagine getting away with just a stretchblt and not + // even starting a final render pass if there's nothing to overlay... hm. Uncommon though on mobile). + vkCmdBeginRenderPass(frame->cmdBuf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); + return frame->cmdBuf; +} + +void VulkanContext::EndSurfaceRenderPass() { + FrameData *frame = &frame_[curFrame_]; + vkCmdEndRenderPass(frame->cmdBuf); + + TransitionToPresent(frame->cmdBuf, swapChainBuffers[current_buffer].image); + + VkResult res = vkEndCommandBuffer(frame->cmdBuf); + assert(res == VK_SUCCESS); + + // So the sequence will be, cmdInit, [cmdQueue_], frame->cmdBuf. + // This way we bunch up all the initialization needed for the frame, we render to + // other buffers before the back buffer, and then last we render to the backbuffer. + + int numCmdBufs = 0; + std::vector cmdBufs; + if (frame->hasInitCommands) { + vkEndCommandBuffer(frame->cmdInit); + cmdBufs.push_back(frame->cmdInit); + frame->hasInitCommands = false; + } + for (auto cmd : cmdQueue_) { + cmdBufs.push_back(cmd); + } + cmdQueue_.clear(); + cmdBufs.push_back(frame->cmdBuf); + + VkSubmitInfo submit_info[1] = {}; + submit_info[0].pNext = NULL; + submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info[0].waitSemaphoreCount = 1; + submit_info[0].pWaitSemaphores = &acquireSemaphore; + VkPipelineStageFlags waitStage[1] = { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT }; + submit_info[0].pWaitDstStageMask = waitStage; + submit_info[0].commandBufferCount = (uint32_t)cmdBufs.size(); + submit_info[0].pCommandBuffers = cmdBufs.data(); + submit_info[0].signalSemaphoreCount = 0; + submit_info[0].pSignalSemaphores = NULL; + res = vkQueueSubmit(gfx_queue_, 1, submit_info, frame->fence); + assert(res == VK_SUCCESS); + + VkPresentInfoKHR present; + present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + present.pNext = NULL; + present.swapchainCount = 1; + present.pSwapchains = &swap_chain_; + present.pImageIndices = ¤t_buffer; + present.pWaitSemaphores = NULL; + present.waitSemaphoreCount = 0; + present.pResults = NULL; + + res = vkQueuePresentKHR(gfx_queue_, &present); + // TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI + // return codes + assert(!res); + + frame->deleteList.Take(globalDeleteList_); + curFrame_ ^= 1; +} + +void VulkanContext::WaitUntilQueueIdle() { + // Should almost never be used + vkQueueWaitIdle(gfx_queue_); +} + +bool VulkanContext::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return false; +} + +void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { + VkResult U_ASSERT_ONLY res; + VkCommandBufferBeginInfo cmd_buf_info = {}; + cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_info.pNext = NULL; + cmd_buf_info.pInheritanceInfo = nullptr; + cmd_buf_info.flags = 0; + res = vkBeginCommandBuffer(cmd, &cmd_buf_info); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitObjects(bool depthPresent) { + InitQueue(); + InitCommandPool(); + + // Create frame data + + VkCommandBufferAllocateInfo cmd_alloc = {}; + cmd_alloc.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cmd_alloc.pNext = NULL; + cmd_alloc.commandPool = cmd_pool_; + cmd_alloc.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cmd_alloc.commandBufferCount = 4; + + VkCommandBuffer cmdBuf[4]; + VkResult res = vkAllocateCommandBuffers(device_, &cmd_alloc, cmdBuf); + assert(res == VK_SUCCESS); + + frame_[0].cmdBuf = cmdBuf[0]; + frame_[0].cmdInit = cmdBuf[1]; + frame_[0].fence = CreateFence(true); // So it can be instantly waited on + frame_[1].cmdBuf = cmdBuf[2]; + frame_[1].cmdInit = cmdBuf[3]; + frame_[1].fence = CreateFence(true); + + VkCommandBuffer cmd = GetInitCommandBuffer(); + InitSwapchain(cmd); + InitDepthStencilBuffer(cmd); + + InitSurfaceRenderPass(depthPresent, true); + InitFramebuffers(depthPresent); + + // The init command buffer will be executed as part of the first frame. +} + +void VulkanContext::DestroyObjects() { + VkCommandBuffer cmdBuf[4] = { frame_[0].cmdBuf, frame_[0].cmdInit, frame_[1].cmdBuf, frame_[1].cmdInit}; + + vkFreeCommandBuffers(device_, cmd_pool_, sizeof(cmdBuf)/sizeof(cmdBuf[0]), cmdBuf); + vkDestroyFence(device_, frame_[0].fence, nullptr); + vkDestroyFence(device_, frame_[1].fence, nullptr); + + DestroyFramebuffers(); + DestroySurfaceRenderPass(); + DestroyDepthStencilBuffer(); + DestroySwapChain(); + DestroyCommandPool(); +} + +VkResult VulkanContext::InitLayerExtensionProperties(layer_properties &layer_props) { + VkExtensionProperties *instance_extensions; + uint32_t instance_extension_count; + VkResult res; + char *layer_name = NULL; + + layer_name = layer_props.properties.layerName; + + do { + res = vkEnumerateInstanceExtensionProperties(layer_name, &instance_extension_count, NULL); + if (res) + return res; + + if (instance_extension_count == 0) { + return VK_SUCCESS; + } + + layer_props.extensions.resize(instance_extension_count); + instance_extensions = layer_props.extensions.data(); + res = vkEnumerateInstanceExtensionProperties( + layer_name, + &instance_extension_count, + instance_extensions); + } while (res == VK_INCOMPLETE); + + return res; +} + +VkResult VulkanContext::InitGlobalExtensionProperties() { + uint32_t instance_extension_count; + VkResult res; + + do { + res = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); + if (res) + return res; + + if (instance_extension_count == 0) { + return VK_SUCCESS; + } + + instance_extension_properties.resize(instance_extension_count); + res = vkEnumerateInstanceExtensionProperties( + NULL, + &instance_extension_count, + instance_extension_properties.data()); + } while (res == VK_INCOMPLETE); + + return res; +} + +VkResult VulkanContext::InitGlobalLayerProperties() { + uint32_t instance_layer_count; + VkLayerProperties *vk_props = NULL; + VkResult res; + + /* + * It's possible, though very rare, that the number of + * instance layers could change. For example, installing something + * could include new layers that the loader would pick up + * between the initial query for the count and the + * request for VkLayerProperties. The loader indicates that + * by returning a VK_INCOMPLETE status and will update the + * the count parameter. + * The count parameter will be updated with the number of + * entries loaded into the data pointer - in case the number + * of layers went down or is smaller than the size given. + */ + do { + res = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL); + if (res) + return res; + + if (instance_layer_count == 0) { + return VK_SUCCESS; + } + + vk_props = (VkLayerProperties *)realloc(vk_props, instance_layer_count * sizeof(VkLayerProperties)); + + res = vkEnumerateInstanceLayerProperties(&instance_layer_count, vk_props); + } while (res == VK_INCOMPLETE); + + // Now gather the extension list for each instance layer. + for (uint32_t i = 0; i < instance_layer_count; i++) { + layer_properties layer_props; + layer_props.properties = vk_props[i]; + res = InitLayerExtensionProperties(layer_props); + if (res) + return res; + instance_layer_properties.push_back(layer_props); + } + free(vk_props); + + return res; +} + +VkResult VulkanContext::InitDeviceExtensionProperties(layer_properties &layer_props) { + VkExtensionProperties *device_extensions; + uint32_t device_extension_count; + VkResult res; + char *layer_name = NULL; + + layer_name = layer_props.properties.layerName; + do { + res = vkEnumerateDeviceExtensionProperties( + physical_devices_[0], + layer_name, &device_extension_count, NULL); + if (res) + return res; + + if (device_extension_count == 0) { + return VK_SUCCESS; + } + + layer_props.extensions.resize(device_extension_count); + device_extensions = layer_props.extensions.data(); + res = vkEnumerateDeviceExtensionProperties( + physical_devices_[0], + layer_name, + &device_extension_count, + device_extensions); + } while (res == VK_INCOMPLETE); + + return res; +} + +/* + * TODO: function description here + */ +VkResult VulkanContext::InitDeviceLayerProperties() { + uint32_t device_layer_count; + VkLayerProperties *vk_props = NULL; + VkResult res; + + /* + * It's possible, though very rare, that the number of + * instance layers could change. For example, installing something + * could include new layers that the loader would pick up + * between the initial query for the count and the + * request for VkLayerProperties. The loader indicates that + * by returning a VK_INCOMPLETE status and will update the + * the count parameter. + * The count parameter will be updated with the number of + * entries loaded into the data pointer - in case the number + * of layers went down or is smaller than the size given. + */ + do { + res = vkEnumerateDeviceLayerProperties(physical_devices_[0], &device_layer_count, NULL); + if (res) + return res; + + if (device_layer_count == 0) { + return VK_SUCCESS; + } + + vk_props = (VkLayerProperties *)realloc(vk_props, device_layer_count * sizeof(VkLayerProperties)); + + res = vkEnumerateDeviceLayerProperties(physical_devices_[0], &device_layer_count, vk_props); + } while (res == VK_INCOMPLETE); + + /* + * Now gather the extension list for each device layer. + */ + for (uint32_t i = 0; i < device_layer_count; i++) { + layer_properties layer_props; + layer_props.properties = vk_props[i]; + res = InitDeviceExtensionProperties(layer_props); + if (res) + return res; + device_layer_properties.push_back(layer_props); + } + free(vk_props); + + return res; +} + +/* + * Return 1 (true) if all layer names specified in check_names + * can be found in given layer properties. + */ +static VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names) { + uint32_t check_count = (uint32_t)layer_names.size(); + uint32_t layer_count = (uint32_t)layer_props.size(); + for (uint32_t i = 0; i < check_count; i++) { + VkBool32 found = 0; + for (uint32_t j = 0; j < layer_count; j++) { + if (!strcmp(layer_names[i], layer_props[j].properties.layerName)) { + found = 1; + } + } + if (!found) { + std::cout << "Cannot find layer: " << layer_names[i] << std::endl; + return 0; + } + } + return 1; +} + +VkResult VulkanContext::CreateDevice(int physical_device) { + VkResult res; + VkDeviceQueueCreateInfo queue_info = {}; + + if (!init_error_.empty()) { + ELOG("Vulkan init failed: %s", init_error_.c_str()); + return VK_ERROR_INITIALIZATION_FAILED; + } + + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, nullptr); + assert(queue_count >= 1); + + queue_props.resize(queue_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, queue_props.data()); + assert(queue_count >= 1); + + bool found = false; + for (int i = 0; i < (int)queue_count; i++) { + if (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + queue_info.queueFamilyIndex = i; + found = true; + break; + } + } + assert(found); + assert(queue_count >= 1); + + // This is as good a place as any to do this + vkGetPhysicalDeviceMemoryProperties(physical_devices_[0], &memory_properties); + vkGetPhysicalDeviceProperties(physical_devices_[0], &gpu_props); + + float queue_priorities[1] = { 0.0 }; + queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_info.pNext = nullptr; + queue_info.queueCount = 1; + queue_info.pQueuePriorities = queue_priorities; + + // Optional features + vkGetPhysicalDeviceFeatures(physical_devices_[0], &featuresAvailable_); + memset(&featuresEnabled_, 0, sizeof(featuresEnabled_)); + + // Enable a few safe ones if they are available. + if (featuresAvailable_.dualSrcBlend) { + featuresEnabled_.dualSrcBlend = true; + } + if (featuresAvailable_.largePoints) { + featuresEnabled_.largePoints = true; + } + if (featuresAvailable_.wideLines) { + featuresEnabled_.wideLines = true; + } + if (featuresAvailable_.geometryShader) { + featuresEnabled_.geometryShader = true; + } + if (featuresAvailable_.logicOp) { + featuresEnabled_.logicOp = true; + } + if (featuresAvailable_.depthClamp) { + featuresEnabled_.depthClamp = true; + } + if (featuresAvailable_.depthBounds) { + featuresEnabled_.depthBounds = true; + } + if (featuresAvailable_.samplerAnisotropy) { + featuresEnabled_.samplerAnisotropy = true; + } + + VkDeviceCreateInfo device_info = {}; + device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + device_info.pNext = NULL; + device_info.queueCreateInfoCount = 1; + device_info.pQueueCreateInfos = &queue_info; + device_info.enabledLayerCount = (uint32_t)device_layer_names.size(); + device_info.ppEnabledLayerNames = + device_info.enabledLayerCount ? device_layer_names.data() : NULL; + device_info.enabledExtensionCount = (uint32_t)device_extension_names.size(); + device_info.ppEnabledExtensionNames = + device_info.enabledExtensionCount ? device_extension_names.data() : NULL; + device_info.pEnabledFeatures = &featuresEnabled_; + + res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); + if (res != VK_SUCCESS) { + init_error_ = "Unable to create Vulkan device"; + ELOG("Unable to create Vulkan device"); + } else { + VulkanLoadDeviceFunctions(device_); + } + + return res; +} + +VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata) { + VkResult res; + VkDebugReportCallbackEXT msg_callback; + + if (!(flags_ & VULKAN_FLAG_VALIDATE)) { + WLOG("Not registering debug report callback - extension not enabled!"); + return VK_SUCCESS; + } + ILOG("Registering debug report callback"); + + VkDebugReportCallbackCreateInfoEXT cb = {}; + cb.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; + cb.pNext = nullptr; + cb.flags = bits; + cb.pfnCallback = dbgFunc; + cb.pUserData = userdata; + res = vkCreateDebugReportCallbackEXT(instance_, &cb, nullptr, &msg_callback); + switch (res) { + case VK_SUCCESS: + msg_callbacks.push_back(msg_callback); + break; + case VK_ERROR_OUT_OF_HOST_MEMORY: + return VK_ERROR_INITIALIZATION_FAILED; + default: + return VK_ERROR_INITIALIZATION_FAILED; + } + return res; +} + +void VulkanContext::DestroyDebugMsgCallback() { + while (msg_callbacks.size() > 0) { + vkDestroyDebugReportCallbackEXT(instance_, msg_callbacks.back(), nullptr); + msg_callbacks.pop_back(); + } +} + +void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { + VkResult U_ASSERT_ONLY res; + bool U_ASSERT_ONLY pass; + VkImageCreateInfo image_info = {}; + // const VkFormat depth_format = VK_FORMAT_D16_UNORM; + // int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + + const VkFormat depth_format = VK_FORMAT_D24_UNORM_S8_UINT; + int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + + VkFormatProperties props; + vkGetPhysicalDeviceFormatProperties(physical_devices_[0], depth_format, &props); + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + } else if (props.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + image_info.tiling = VK_IMAGE_TILING_LINEAR; + } else { + /* Try other depth formats? */ + std::cout << "VK_FORMAT_D16_UNORM Unsupported.\n"; + exit(-1); + } + + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.pNext = NULL; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = depth_format; + image_info.extent.width = width; + image_info.extent.height = height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.queueFamilyIndexCount = 0; + image_info.pQueueFamilyIndices = NULL; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + image_info.flags = 0; + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + + VkMemoryRequirements mem_reqs; + + depth.format = depth_format; + + /* Create image */ + res = vkCreateImage(device_, &image_info, NULL, &depth.image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(device_, depth.image, &mem_reqs); + + mem_alloc.allocationSize = mem_reqs.size; + /* Use the memory properties to determine the type of memory required */ + pass = MemoryTypeFromProperties(mem_reqs.memoryTypeBits, + 0, /* No requirements */ + &mem_alloc.memoryTypeIndex); + assert(pass); + + /* Allocate memory */ + res = vkAllocateMemory(device_, &mem_alloc, NULL, &depth.mem); + assert(res == VK_SUCCESS); + + /* Bind memory */ + res = vkBindImageMemory(device_, depth.image, depth.mem, 0); + assert(res == VK_SUCCESS); + + /* Set the image layout to depth stencil optimal */ + TransitionImageLayout(cmd, depth.image, + aspectMask, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + + /* Create image view */ + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = depth.image; + view_info.format = depth_format; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = aspectMask; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.flags = 0; + + res = vkCreateImageView(device_, &view_info, NULL, &depth.view); + assert(res == VK_SUCCESS); +} + +#ifdef _WIN32 +void VulkanContext::InitSurfaceWin32(HINSTANCE conn, HWND wnd) { + connection = conn; + window = wnd; + + RECT rc; + GetClientRect(wnd, &rc); + width = rc.right - rc.left; + height = rc.bottom - rc.top; + + VkResult U_ASSERT_ONLY res; + + VkWin32SurfaceCreateInfoKHR win32; + win32.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + win32.pNext = nullptr; + win32.flags = 0; + win32.hwnd = wnd; + win32.hinstance = conn; + res = vkCreateWin32SurfaceKHR(instance_, &win32, nullptr, &surface_); + + assert(res == VK_SUCCESS); +} +#elif defined(ANDROID) +void VulkanContext::InitSurfaceAndroid(ANativeWindow *wnd, int width, int height) { + native_window = wnd; + + VkResult U_ASSERT_ONLY res; + + VkAndroidSurfaceCreateInfoKHR android; + android.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; + android.pNext = nullptr; + android.flags = 0; + android.window = native_window; + res = vkCreateAndroidSurfaceKHR(instance_, &android, nullptr, &surface_); + assert(res == VK_SUCCESS); + + this->width = width; + this->height = height; +} + +#endif + +void VulkanContext::InitQueue() { + // Iterate over each queue to learn whether it supports presenting: + VkBool32* supportsPresent = new VkBool32[queue_count]; + for (uint32_t i = 0; i < queue_count; i++) { + vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface_, &supportsPresent[i]); + } + + // Search for a graphics queue and a present queue in the array of queue + // families, try to find one that supports both + uint32_t graphicsQueueNodeIndex = UINT32_MAX; + uint32_t presentQueueNodeIndex = UINT32_MAX; + for (uint32_t i = 0; i < queue_count; i++) { + if ((queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { + if (graphicsQueueNodeIndex == UINT32_MAX) { + graphicsQueueNodeIndex = i; + } + + if (supportsPresent[i] == VK_TRUE) { + graphicsQueueNodeIndex = i; + presentQueueNodeIndex = i; + break; + } + } + } + if (presentQueueNodeIndex == UINT32_MAX) { + // If didn't find a queue that supports both graphics and present, then + // find a separate present queue. + for (uint32_t i = 0; i < queue_count; ++i) { + if (supportsPresent[i] == VK_TRUE) { + presentQueueNodeIndex = i; + break; + } + } + } + delete[] supportsPresent; + + // Generate error if could not find both a graphics and a present queue + if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { + std::cout << "Could not find a graphics and a present queue"; + exit(-1); + } + + graphics_queue_family_index_ = graphicsQueueNodeIndex; + + // Get the list of VkFormats that are supported: + uint32_t formatCount; + VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface_, &formatCount, NULL); + assert(res == VK_SUCCESS); + VkSurfaceFormatKHR *surfFormats = new VkSurfaceFormatKHR[formatCount]; + res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface_, &formatCount, surfFormats); + assert(res == VK_SUCCESS); + // If the format list includes just one entry of VK_FORMAT_UNDEFINED, + // the surface has no preferred format. Otherwise, at least one + // supported format will be returned. + if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { + ILOG("swapchain_format: Falling back to B8G8R8A8_UNORM"); + swapchain_format = VK_FORMAT_B8G8R8A8_UNORM; + } else { + assert(formatCount >= 1); + swapchain_format = surfFormats[0].format; + ILOG("swapchain_format: %d (/%d)", swapchain_format, formatCount); + } + delete[] surfFormats; + + vkGetDeviceQueue(device_, graphics_queue_family_index_, 0, &gfx_queue_); + ILOG("gfx_queue_: %p", gfx_queue_); + + VkSemaphoreCreateInfo acquireSemaphoreCreateInfo; + acquireSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + acquireSemaphoreCreateInfo.pNext = NULL; + acquireSemaphoreCreateInfo.flags = 0; + + res = vkCreateSemaphore(device_, + &acquireSemaphoreCreateInfo, + NULL, + &acquireSemaphore); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { + VkResult U_ASSERT_ONLY res; + VkSurfaceCapabilitiesKHR surfCapabilities; + + res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], surface_, &surfCapabilities); + assert(res == VK_SUCCESS); + + uint32_t presentModeCount; + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface_, &presentModeCount, NULL); + assert(res == VK_SUCCESS); + VkPresentModeKHR *presentModes = new VkPresentModeKHR[presentModeCount]; + assert(presentModes); + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface_, &presentModeCount, presentModes); + assert(res == VK_SUCCESS); + + VkExtent2D swapChainExtent; + // width and height are either both -1, or both not -1. + if (surfCapabilities.currentExtent.width == (uint32_t)-1) { + // If the surface size is undefined, the size is set to + // the size of the images requested. + ILOG("initSwapchain: %dx%d", width, height); + swapChainExtent.width = width; + swapChainExtent.height = height; + } else { + // If the surface size is defined, the swap chain size must match + swapChainExtent = surfCapabilities.currentExtent; + } + + // TODO: Find a better way to specify the prioritized present mode while being able + // to fall back in a sensible way. + VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_MAX_ENUM; + for (size_t i = 0; i < presentModeCount; i++) { + ILOG("Supported present mode: %d", presentModes[i]); + } + for (size_t i = 0; i < presentModeCount; i++) { + if (swapchainPresentMode == VK_PRESENT_MODE_MAX_ENUM) { + // Default to the first present mode from the list. + swapchainPresentMode = presentModes[i]; + } + if ((flags_ & VULKAN_FLAG_PRESENT_MAILBOX) && presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { + swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; + break; + } + if ((flags_ & VULKAN_FLAG_PRESENT_FIFO_RELAXED) && presentModes[i] == VK_PRESENT_MODE_FIFO_RELAXED_KHR) { + swapchainPresentMode = VK_PRESENT_MODE_FIFO_RELAXED_KHR; + break; + } + if ((flags_ & VULKAN_FLAG_PRESENT_IMMEDIATE) && presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR) { + swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; + break; + } + } +#ifdef ANDROID + // HACK + swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; +#endif + ILOG("Chosen present mode: %d", 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 + // queued for display): + uint32_t desiredNumberOfSwapChainImages = surfCapabilities.minImageCount + 1; + ILOG("numSwapChainImages: %d", desiredNumberOfSwapChainImages); + if ((surfCapabilities.maxImageCount > 0) && + (desiredNumberOfSwapChainImages > surfCapabilities.maxImageCount)) + { + // Application must settle for fewer images than desired: + desiredNumberOfSwapChainImages = surfCapabilities.maxImageCount; + } + + VkSurfaceTransformFlagBitsKHR preTransform; + if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { + preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + } else { + preTransform = surfCapabilities.currentTransform; + } + + VkSwapchainCreateInfoKHR swap_chain_info = {}; + swap_chain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + swap_chain_info.pNext = NULL; + swap_chain_info.surface = surface_; + swap_chain_info.minImageCount = desiredNumberOfSwapChainImages; + swap_chain_info.imageFormat = swapchain_format; + swap_chain_info.imageExtent.width = swapChainExtent.width; + swap_chain_info.imageExtent.height = swapChainExtent.height; + swap_chain_info.preTransform = preTransform; + swap_chain_info.imageArrayLayers = 1; + swap_chain_info.presentMode = swapchainPresentMode; + swap_chain_info.oldSwapchain = VK_NULL_HANDLE; + swap_chain_info.clipped = true; + swap_chain_info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + swap_chain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + swap_chain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + swap_chain_info.queueFamilyIndexCount = 0; + swap_chain_info.pQueueFamilyIndices = NULL; + swap_chain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + + res = vkCreateSwapchainKHR(device_, &swap_chain_info, NULL, &swap_chain_); + assert(res == VK_SUCCESS); + + res = vkGetSwapchainImagesKHR(device_, swap_chain_, + &swapchainImageCount, NULL); + assert(res == VK_SUCCESS); + + VkImage* swapchainImages = (VkImage*)malloc(swapchainImageCount * sizeof(VkImage)); + assert(swapchainImages); + res = vkGetSwapchainImagesKHR(device_, swap_chain_, &swapchainImageCount, swapchainImages); + assert(res == VK_SUCCESS); + + for (uint32_t i = 0; i < swapchainImageCount; i++) { + swap_chain_buffer sc_buffer; + + VkImageViewCreateInfo color_image_view = {}; + color_image_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + color_image_view.pNext = NULL; + color_image_view.format = swapchain_format; + color_image_view.components.r = VK_COMPONENT_SWIZZLE_R; + color_image_view.components.g = VK_COMPONENT_SWIZZLE_G; + color_image_view.components.b = VK_COMPONENT_SWIZZLE_B; + color_image_view.components.a = VK_COMPONENT_SWIZZLE_A; + color_image_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + color_image_view.subresourceRange.baseMipLevel = 0; + color_image_view.subresourceRange.levelCount = 1; + color_image_view.subresourceRange.baseArrayLayer = 0; + color_image_view.subresourceRange.layerCount = 1; + color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D; + color_image_view.flags = 0; + + sc_buffer.image = swapchainImages[i]; + + // TODO: Pre-set them to PRESENT_SRC_KHR, as the first thing we do after acquiring + // in image to render to will be to transition them away from that. + TransitionImageLayout(cmd, sc_buffer.image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + + color_image_view.image = sc_buffer.image; + + res = vkCreateImageView(device_, + &color_image_view, NULL, &sc_buffer.view); + swapChainBuffers.push_back(sc_buffer); + assert(res == VK_SUCCESS); + } + free(swapchainImages); + + current_buffer = 0; +} + +void VulkanContext::InitSurfaceRenderPass(bool include_depth, bool clear) { + VkResult U_ASSERT_ONLY res; + /* Need attachments for render target and depth buffer */ + VkAttachmentDescription attachments[2]; + attachments[0].format = swapchain_format; + attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; + attachments[0].loadOp = clear?VK_ATTACHMENT_LOAD_OP_CLEAR:VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].flags = 0; + + if (include_depth) { + attachments[1].format = depth.format; + attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; + attachments[1].loadOp = clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachments[1].flags = 0; + } + + VkAttachmentReference color_reference = {}; + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkAttachmentReference depth_reference = {}; + depth_reference.attachment = 1; + depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.flags = 0; + subpass.inputAttachmentCount = 0; + subpass.pInputAttachments = NULL; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_reference; + subpass.pResolveAttachments = NULL; + subpass.pDepthStencilAttachment = include_depth?&depth_reference:NULL; + subpass.preserveAttachmentCount = 0; + subpass.pPreserveAttachments = NULL; + + VkRenderPassCreateInfo rp_info = {}; + rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + rp_info.pNext = NULL; + rp_info.attachmentCount = include_depth ? 2 : 1; + rp_info.pAttachments = attachments; + rp_info.subpassCount = 1; + rp_info.pSubpasses = &subpass; + rp_info.dependencyCount = 0; + rp_info.pDependencies = NULL; + + res = vkCreateRenderPass(device_, &rp_info, NULL, &surface_render_pass_); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitFramebuffers(bool include_depth) { + VkResult U_ASSERT_ONLY res; + VkImageView attachments[2]; + attachments[1] = depth.view; + + ILOG("InitFramebuffers: %dx%d", width, height); + VkFramebufferCreateInfo fb_info = {}; + fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + fb_info.pNext = NULL; + fb_info.renderPass = surface_render_pass_; + fb_info.attachmentCount = include_depth ? 2 : 1; + fb_info.pAttachments = attachments; + fb_info.width = width; + fb_info.height = height; + fb_info.layers = 1; + + framebuffers_.resize(swapchainImageCount); + + for (uint32_t i = 0; i < swapchainImageCount; i++) { + attachments[0] = swapChainBuffers[i].view; + res = vkCreateFramebuffer(device_, &fb_info, NULL, &framebuffers_[i]); + assert(res == VK_SUCCESS); + } +} + +void VulkanContext::InitCommandPool() { + VkResult U_ASSERT_ONLY res; + + VkCommandPoolCreateInfo cmd_pool_info = {}; + cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cmd_pool_info.pNext = NULL; + cmd_pool_info.queueFamilyIndex = graphics_queue_family_index_; + cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; + + res = vkCreateCommandPool(device_, &cmd_pool_info, NULL, &cmd_pool_); + assert(res == VK_SUCCESS); +} + +VkFence VulkanContext::CreateFence(bool presignalled) { + VkFence fence; + VkFenceCreateInfo fenceInfo; + fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceInfo.pNext = NULL; + fenceInfo.flags = presignalled ? VK_FENCE_CREATE_SIGNALED_BIT : 0; + vkCreateFence(device_, &fenceInfo, NULL, &fence); + return fence; +} + +void VulkanContext::WaitAndResetFence(VkFence fence) { + vkWaitForFences(device_, 1, &fence, true, UINT64_MAX); + vkResetFences(device_, 1, &fence); +} + +void VulkanContext::DestroyCommandPool() { + vkDestroyCommandPool(device_, cmd_pool_, NULL); + cmd_pool_ = VK_NULL_HANDLE; +} + +void VulkanContext::DestroyDepthStencilBuffer() { + vkDestroyImageView(device_, depth.view, NULL); + vkDestroyImage(device_, depth.image, NULL); + vkFreeMemory(device_, depth.mem, NULL); + depth.view = VK_NULL_HANDLE; + depth.image = VK_NULL_HANDLE; + depth.mem = VK_NULL_HANDLE; +} + +void VulkanContext::DestroySwapChain() { + for (uint32_t i = 0; i < swapchainImageCount; i++) { + vkDestroyImageView(device_, swapChainBuffers[i].view, NULL); + } + vkDestroySwapchainKHR(device_, swap_chain_, NULL); + swap_chain_ = VK_NULL_HANDLE; + swapChainBuffers.clear(); + vkDestroySemaphore(device_, acquireSemaphore, NULL); +} + +void VulkanContext::DestroyFramebuffers() { + for (uint32_t i = 0; i < framebuffers_.size(); i++) { + vkDestroyFramebuffer(device_, framebuffers_[i], NULL); + } + framebuffers_.clear(); +} + +void VulkanContext::DestroySurfaceRenderPass() { + vkDestroyRenderPass(device_, surface_render_pass_, NULL); + surface_render_pass_ = NULL; +} + +void VulkanContext::DestroyDevice() { + vkDestroyDevice(device_, NULL); + device_ = NULL; +} + +VkPipelineCache VulkanContext::CreatePipelineCache() { + VkPipelineCache cache; + VkPipelineCacheCreateInfo pc; + pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + pc.pNext = nullptr; + pc.pInitialData = nullptr; + pc.initialDataSize = 0; + pc.flags = 0; + VkResult res = vkCreatePipelineCache(device_, &pc, nullptr, &cache); + assert(VK_SUCCESS == res); + return cache; +} + +bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule) { + VkShaderModuleCreateInfo sm; + sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + sm.pNext = nullptr; + sm.pCode = spirv.data(); + sm.codeSize = spirv.size() * sizeof(uint32_t); + sm.flags = 0; + VkResult result = vkCreateShaderModule(device_, &sm, NULL, shaderModule); + if (result != VK_SUCCESS) { + return false; + } else { + return true; + } +} + +void TransitionImageLayout(VkCommandBuffer cmd, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout) { + VkImageMemoryBarrier image_memory_barrier = {}; + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.pNext = NULL; + image_memory_barrier.srcAccessMask = 0; + image_memory_barrier.dstAccessMask = 0; + image_memory_barrier.oldLayout = old_image_layout; + image_memory_barrier.newLayout = new_image_layout; + image_memory_barrier.image = image; + image_memory_barrier.subresourceRange.aspectMask = aspectMask; + image_memory_barrier.subresourceRange.baseMipLevel = 0; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + if (old_image_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { + image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + } + + if (old_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { + image_memory_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + if (old_image_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) { + image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + } + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + /* Make sure anything that was copying from this image has completed */ + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + /* Make sure any Copy or CPU writes to image are flushed */ + if (old_image_layout != VK_IMAGE_LAYOUT_UNDEFINED) { + image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + } + image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { + image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { + image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; + } + + VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + + vkCmdPipelineBarrier(cmd, src_stages, dest_stages, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); +} + +void init_resources(TBuiltInResource &Resources) { + Resources.maxLights = 32; + Resources.maxClipPlanes = 6; + Resources.maxTextureUnits = 32; + Resources.maxTextureCoords = 32; + Resources.maxVertexAttribs = 64; + Resources.maxVertexUniformComponents = 4096; + Resources.maxVaryingFloats = 64; + Resources.maxVertexTextureImageUnits = 32; + Resources.maxCombinedTextureImageUnits = 80; + Resources.maxTextureImageUnits = 32; + Resources.maxFragmentUniformComponents = 4096; + Resources.maxDrawBuffers = 32; + Resources.maxVertexUniformVectors = 128; + Resources.maxVaryingVectors = 8; + Resources.maxFragmentUniformVectors = 16; + Resources.maxVertexOutputVectors = 16; + Resources.maxFragmentInputVectors = 15; + Resources.minProgramTexelOffset = -8; + Resources.maxProgramTexelOffset = 7; + Resources.maxClipDistances = 8; + Resources.maxComputeWorkGroupCountX = 65535; + Resources.maxComputeWorkGroupCountY = 65535; + Resources.maxComputeWorkGroupCountZ = 65535; + Resources.maxComputeWorkGroupSizeX = 1024; + Resources.maxComputeWorkGroupSizeY = 1024; + Resources.maxComputeWorkGroupSizeZ = 64; + Resources.maxComputeUniformComponents = 1024; + Resources.maxComputeTextureImageUnits = 16; + Resources.maxComputeImageUniforms = 8; + Resources.maxComputeAtomicCounters = 8; + Resources.maxComputeAtomicCounterBuffers = 1; + Resources.maxVaryingComponents = 60; + Resources.maxVertexOutputComponents = 64; + Resources.maxGeometryInputComponents = 64; + Resources.maxGeometryOutputComponents = 128; + Resources.maxFragmentInputComponents = 128; + Resources.maxImageUnits = 8; + Resources.maxCombinedImageUnitsAndFragmentOutputs = 8; + Resources.maxCombinedShaderOutputResources = 8; + Resources.maxImageSamples = 0; + Resources.maxVertexImageUniforms = 0; + Resources.maxTessControlImageUniforms = 0; + Resources.maxTessEvaluationImageUniforms = 0; + Resources.maxGeometryImageUniforms = 0; + Resources.maxFragmentImageUniforms = 8; + Resources.maxCombinedImageUniforms = 8; + Resources.maxGeometryTextureImageUnits = 16; + Resources.maxGeometryOutputVertices = 256; + Resources.maxGeometryTotalOutputComponents = 1024; + Resources.maxGeometryUniformComponents = 1024; + Resources.maxGeometryVaryingComponents = 64; + Resources.maxTessControlInputComponents = 128; + Resources.maxTessControlOutputComponents = 128; + Resources.maxTessControlTextureImageUnits = 16; + Resources.maxTessControlUniformComponents = 1024; + Resources.maxTessControlTotalOutputComponents = 4096; + Resources.maxTessEvaluationInputComponents = 128; + Resources.maxTessEvaluationOutputComponents = 128; + Resources.maxTessEvaluationTextureImageUnits = 16; + Resources.maxTessEvaluationUniformComponents = 1024; + Resources.maxTessPatchComponents = 120; + Resources.maxPatchVertices = 32; + Resources.maxTessGenLevel = 64; + Resources.maxViewports = 16; + Resources.maxVertexAtomicCounters = 0; + Resources.maxTessControlAtomicCounters = 0; + Resources.maxTessEvaluationAtomicCounters = 0; + Resources.maxGeometryAtomicCounters = 0; + Resources.maxFragmentAtomicCounters = 8; + Resources.maxCombinedAtomicCounters = 8; + Resources.maxAtomicCounterBindings = 1; + Resources.maxVertexAtomicCounterBuffers = 0; + Resources.maxTessControlAtomicCounterBuffers = 0; + Resources.maxTessEvaluationAtomicCounterBuffers = 0; + Resources.maxGeometryAtomicCounterBuffers = 0; + Resources.maxFragmentAtomicCounterBuffers = 1; + Resources.maxCombinedAtomicCounterBuffers = 1; + Resources.maxAtomicCounterBufferSize = 16384; + Resources.maxTransformFeedbackBuffers = 4; + Resources.maxTransformFeedbackInterleavedComponents = 64; + Resources.maxCullDistances = 8; + Resources.maxCombinedClipAndCullDistances = 8; + Resources.maxSamples = 4; + Resources.limits.nonInductiveForLoops = 1; + Resources.limits.whileLoops = 1; + Resources.limits.doWhileLoops = 1; + Resources.limits.generalUniformIndexing = 1; + Resources.limits.generalAttributeMatrixVectorIndexing = 1; + Resources.limits.generalVaryingIndexing = 1; + Resources.limits.generalSamplerIndexing = 1; + Resources.limits.generalVariableIndexing = 1; + Resources.limits.generalConstantMatrixVectorIndexing = 1; +} + +EShLanguage FindLanguage(const VkShaderStageFlagBits shader_type) { + switch (shader_type) { + case VK_SHADER_STAGE_VERTEX_BIT: + return EShLangVertex; + + case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: + return EShLangTessControl; + + case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: + return EShLangTessEvaluation; + + case VK_SHADER_STAGE_GEOMETRY_BIT: + return EShLangGeometry; + + case VK_SHADER_STAGE_FRAGMENT_BIT: + return EShLangFragment; + + case VK_SHADER_STAGE_COMPUTE_BIT: + return EShLangCompute; + + default: + return EShLangVertex; + } +} + +// Compile a given string containing GLSL into SPV for use by VK +// Return value of false means an error was encountered. +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, + const char *pshader, + std::vector &spirv, std::string *errorMessage) { + + glslang::TProgram program; + const char *shaderStrings[1]; + TBuiltInResource Resources; + init_resources(Resources); + + // Enable SPIR-V and Vulkan rules when parsing GLSL + EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); + + EShLanguage stage = FindLanguage(shader_type); + glslang::TShader shader(stage); + + shaderStrings[0] = pshader; + shader.setStrings(shaderStrings, 1); + + if (!shader.parse(&Resources, 100, false, messages)) { + puts(shader.getInfoLog()); + puts(shader.getInfoDebugLog()); + if (errorMessage) { + *errorMessage = shader.getInfoLog(); + (*errorMessage) += shader.getInfoDebugLog(); + } + return false; // something didn't work + } + + // Note that program does not take ownership of &shader, so this is fine. + program.addShader(&shader); + + if (!program.link(messages)) { + puts(shader.getInfoLog()); + puts(shader.getInfoDebugLog()); + if (errorMessage) { + *errorMessage = shader.getInfoLog(); + (*errorMessage) += shader.getInfoDebugLog(); + } + return false; + } + + // Can't fail, parsing worked, "linking" worked. + glslang::GlslangToSpv(*program.getIntermediate(stage), spirv); + return true; +} + +void init_glslang() { + glslang::InitializeProcess(); +} + +void finalize_glslang() { + glslang::FinalizeProcess(); +} + +const char *VulkanResultToString(VkResult res) { + switch (res) { + case VK_NOT_READY: return "VK_NOT_READY"; + case VK_TIMEOUT: return "VK_TIMEOUT"; + case VK_EVENT_SET: return "VK_EVENT_SET"; + case VK_EVENT_RESET: return "VK_EVENT_RESET"; + case VK_INCOMPLETE: return "VK_INCOMPLETE"; + case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; + case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; + case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; + case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; + case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; + case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; + case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; + case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; + case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; + case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; + case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; + case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; + case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; + case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; + case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; + case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; + default: + return "Unknown"; + } +} + +void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line) { + const char *error = "(none)"; +} diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h new file mode 100644 index 0000000000..bc3a7d6d1b --- /dev/null +++ b/Common/Vulkan/VulkanContext.h @@ -0,0 +1,346 @@ +#ifndef UTIL_INIT +#define UTIL_INIT + +#ifdef ANDROID +#undef NDEBUG // asserts +#endif +#include +#include +#include +#include + +#include "base/logging.h" + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define VK_USE_PLATFORM_WIN32_KHR +#define NOMINMAX /* Don't let Windows define min() or max() */ +#define APP_NAME_STR_LEN 80 +#include +#elif defined(ANDROID) // _WIN32 +#include +#define VK_USE_PLATFORM_ANDROID_KHR +#else +#define VK_USE_PLATFORM_XCB_KHR +#include +#endif // _WIN32 + +#include "Common/Vulkan/VulkanLoader.h" + +// Amount of time, in nanoseconds, to wait for a command buffer to complete +#define FENCE_TIMEOUT 10000000000 + +#if defined(NDEBUG) && defined(__GNUC__) +#define U_ASSERT_ONLY __attribute__((unused)) +#else +#define U_ASSERT_ONLY +#endif + +enum { + VULKAN_FLAG_VALIDATE = 1, + VULKAN_FLAG_PRESENT_MAILBOX = 2, + VULKAN_FLAG_PRESENT_IMMEDIATE = 4, + VULKAN_FLAG_PRESENT_FIFO_RELAXED = 8, +}; + +// A layer can expose extensions, keep track of those extensions here. +struct layer_properties { + VkLayerProperties properties; + std::vector extensions; +}; + +// This is a bit repetitive... +class VulkanDeleteList { +public: + void QueueDeleteDescriptorPool(VkDescriptorPool pool) { descPools_.push_back(pool); } + void QueueDeleteShaderModule(VkShaderModule module) { modules_.push_back(module); } + void QueueDeleteBuffer(VkBuffer buffer) { buffers_.push_back(buffer); } + void QueueDeleteBufferView(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } + void QueueDeleteImage(VkImage image) { images_.push_back(image); } + void QueueDeleteImageView(VkImageView imageView) { imageViews_.push_back(imageView); } + void QueueDeleteDeviceMemory(VkDeviceMemory deviceMemory) { deviceMemory_.push_back(deviceMemory); } + void QueueDeleteSampler(VkSampler sampler) { samplers_.push_back(sampler); } + void QueueDeletePipelineCache(VkPipelineCache pipelineCache) { pipelineCaches_.push_back(pipelineCache); } + + void Take(VulkanDeleteList &del) { + 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(pipelineCaches_.size() == 0); + 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_); + pipelineCaches_ = std::move(del.pipelineCaches_); + } + + void PerformDeletes(VkDevice device) { + 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 &pcache : pipelineCaches_) { + vkDestroyPipelineCache(device, pcache, nullptr); + } + pipelineCaches_.clear(); + } + +private: + std::vector descPools_; + std::vector modules_; + std::vector buffers_; + std::vector bufferViews_; + std::vector images_; + std::vector imageViews_; + std::vector deviceMemory_; + std::vector samplers_; + std::vector pipelineCaches_; +}; + +// VulkanContext sets up the basics necessary for rendering to a window, including framebuffers etc. +// Optionally, it can create a depth buffer for you as well. +class VulkanContext { +public: + VulkanContext(const char *app_name, int app_ver, uint32_t flags); + ~VulkanContext(); + + VkResult CreateDevice(int physical_device); + + const std::string &InitError() { return init_error_; } + + VkDevice GetDevice() { return device_; } + VkInstance GetInstance() { return instance_; } + + VulkanDeleteList &Delete() { return globalDeleteList_; } + + VkPipelineCache CreatePipelineCache(); + +#ifdef _WIN32 + void InitSurfaceWin32(HINSTANCE conn, HWND wnd); +#elif ANDROID + void InitSurfaceAndroid(ANativeWindow *native_window, int width, int height); +#endif + void InitQueue(); + void InitObjects(bool depthPresent); + void InitSwapchain(VkCommandBuffer cmd); + void InitSurfaceRenderPass(bool include_depth, bool clear); + void InitFramebuffers(bool include_depth); + void InitDepthStencilBuffer(VkCommandBuffer cmd); + void InitCommandPool(); + + void DestroyObjects(); + + void DestroySurfaceRenderPass(); + void DestroyFramebuffers(); + void DestroySwapChain(); + void DestroyDepthStencilBuffer(); + void DestroyCommandPool(); + void DestroyDevice(); + + void WaitUntilQueueIdle(); + + // Utility functions for shorter code + VkFence CreateFence(bool presignalled); + bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule); + + void WaitAndResetFence(VkFence fence); + + int GetWidth() { return width; } + int GetHeight() { return height; } + + VkCommandBuffer GetInitCommandBuffer(); + + // This must only be accessed between BeginSurfaceRenderPass and EndSurfaceRenderPass. + VkCommandBuffer GetSurfaceCommandBuffer() { + return frame_[curFrame_ & 1].cmdBuf; + } + + // The surface render pass is special because it has to acquire the backbuffer, and may thus "block". + // Use the returned command buffer to enqueue commands that render to the backbuffer. + // To render to other buffers first, you can submit additional commandbuffers using QueueBeforeSurfaceRender(cmd). + VkCommandBuffer BeginSurfaceRenderPass(VkClearValue clear_values[2]); + // May eventually need the ability to break and resume the backbuffer render pass in a few rare cases. + void EndSurfaceRenderPass(); + + void QueueBeforeSurfaceRender(VkCommandBuffer cmd); + + bool MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); + + VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata = nullptr); + void DestroyDebugMsgCallback(); + + VkRenderPass GetSurfaceRenderPass() const { + return surface_render_pass_; + } + + VkPhysicalDevice GetPhysicalDevice(int n = 0) const { + return physical_devices_[n]; + } + + VkQueue GetGraphicsQueue() const { + return gfx_queue_; + } + + int GetGraphicsQueueFamilyIndex() const { + return graphics_queue_family_index_; + } + + const VkPhysicalDeviceProperties &GetPhysicalDeviceProperties() { + return gpu_props; + } + + VkResult InitGlobalExtensionProperties(); + VkResult InitLayerExtensionProperties(layer_properties &layer_props); + + VkResult InitGlobalLayerProperties(); + + VkResult InitDeviceExtensionProperties(layer_properties &layer_props); + VkResult InitDeviceLayerProperties(); + + const VkPhysicalDeviceFeatures &GetFeaturesAvailable() const { return featuresAvailable_; } + const VkPhysicalDeviceFeatures &GetFeaturesEnabled() const { return featuresEnabled_; } + +private: + VkSemaphore acquireSemaphore; + +#ifdef _WIN32 + HINSTANCE connection; // hInstance - Windows Instance + HWND window; // hWnd - window handle +#elif ANDROID // _WIN32 + ANativeWindow *native_window; +#endif // _WIN32 + + // TODO: Move to frame data + VkCommandPool cmd_pool_; + + VkInstance instance_; + VkDevice device_; + VkQueue gfx_queue_; + + VkSurfaceKHR surface_; + bool prepared; + bool use_staging_buffer_; + + std::string init_error_; + std::vector instance_layer_names; + std::vector instance_extension_names; + std::vector instance_layer_properties; + std::vector instance_extension_properties; + + std::vector device_layer_names; + std::vector device_extension_names; + std::vector device_layer_properties; + std::vector device_extension_properties; + std::vector physical_devices_; + + uint32_t graphics_queue_family_index_; + VkPhysicalDeviceProperties gpu_props; + std::vector queue_props; + VkPhysicalDeviceMemoryProperties memory_properties; + + struct swap_chain_buffer { + VkImage image; + VkImageView view; + }; + + // Swap chain + int width, height; + int flags_; + VkFormat swapchain_format; + std::vector framebuffers_; + uint32_t swapchainImageCount; + VkSwapchainKHR swap_chain_; + std::vector swapChainBuffers; + + // Manages flipping command buffers for the backbuffer render pass. + // It is recommended to do the same for other rendering passes. + struct FrameData { + FrameData() : hasInitCommands(false), cmdInit(nullptr), cmdBuf(nullptr) {} + + VkFence fence; + bool hasInitCommands; + VkCommandBuffer cmdInit; + VkCommandBuffer cmdBuf; + + VulkanDeleteList deleteList; + }; + + FrameData frame_[2]; + int curFrame_; + + // At the end of the frame, this is copied into the frame's delete list, so it can be processed + // the next time the frame comes around again. + VulkanDeleteList globalDeleteList_; + + std::vector msg_callbacks; + + struct { + VkFormat format; + VkImage image; + VkDeviceMemory mem; + VkImageView view; + } depth; + + VkRenderPass surface_render_pass_; + uint32_t current_buffer; + uint32_t queue_count; + + VkPhysicalDeviceFeatures featuresAvailable_; + VkPhysicalDeviceFeatures featuresEnabled_; + + std::vector cmdQueue_; +}; + +// Stand-alone utility functions +void VulkanBeginCommandBuffer(VkCommandBuffer cmd); +void TransitionImageLayout( + VkCommandBuffer cmd, + VkImage image, + VkImageAspectFlags aspectMask, + VkImageLayout old_image_layout, + VkImageLayout new_image_layout); + +// GLSL compiler +void init_glslang(); +void finalize_glslang(); +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv, std::string *errorMessage = nullptr); + +#endif // UTIL_INIT + diff --git a/Common/Vulkan/VulkanImage.cpp b/Common/Vulkan/VulkanImage.cpp new file mode 100644 index 0000000000..01ad9e3db4 --- /dev/null +++ b/Common/Vulkan/VulkanImage.cpp @@ -0,0 +1,356 @@ +#include "Common/Vulkan/VulkanImage.h" + +VkResult VulkanTexture::Create(int w, int h, VkFormat format) { + tex_width = w; + tex_height = h; + format_ = format; + + VkFormatProperties formatProps; + vkGetPhysicalDeviceFormatProperties(vulkan_->GetPhysicalDevice(), format, &formatProps); + + // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. + // Linear tiling is usually only supported for 2D non-array textures. + // needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; + // Always stage. + needStaging = true; + + return VK_SUCCESS; +} + +void VulkanTexture::CreateMappableImage() { + // If we already have a mappableImage, forget it. + if (mappableImage) { + vulkan_->Delete().QueueDeleteImage(mappableImage); + mappableImage = VK_NULL_HANDLE; + } + if (mappableMemory) { + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + mappableMemory = VK_NULL_HANDLE; + } + + bool U_ASSERT_ONLY pass; + + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.tiling = VK_IMAGE_TILING_LINEAR; + image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + + // Create a mappable image. It will be the texture if linear images are ok to be textures + // or it will be the staging image if they are not. + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &mappableImage); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), mappableImage, &mem_reqs); + assert(res == VK_SUCCESS); + + mem_alloc.allocationSize = mem_reqs.size; + + // Find the memory type that is host mappable. + pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mappableMemory); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), mappableImage, mappableMemory, 0); + assert(res == VK_SUCCESS); +} + +uint8_t *VulkanTexture::Lock(int level, int *rowPitch) { + CreateMappableImage(); + + VkImageSubresource subres = {}; + subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subres.mipLevel = 0; + subres.arrayLayer = 0; + + VkSubresourceLayout layout; + void *data; + + // Get the subresource layout so we know what the row pitch is + vkGetImageSubresourceLayout(vulkan_->GetDevice(), mappableImage, &subres, &layout); + VkResult res = vkMapMemory(vulkan_->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); + assert(res == VK_SUCCESS); + + *rowPitch = (int)layout.rowPitch; + return (uint8_t *)data; +} + +void VulkanTexture::Unlock() { + vkUnmapMemory(vulkan_->GetDevice(), mappableMemory); + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + + // if we already have an image, queue it for destruction and forget it. + Wipe(); + if (!needStaging) { + // If we can use the linear tiled image as a texture, just do it + image = mappableImage; + mem = mappableMemory; + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + // Make sure we don't accidentally delete the main image. + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; + } else { + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + // The mappable image cannot be our texture, so create an optimally tiled image and blit to it + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + // Find memory type - don't specify any mapping requirements + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); + assert(res == VK_SUCCESS); + + // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL + TransitionImageLayout(cmd, mappableImage, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + VkImageCopy copy_region; + copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.srcSubresource.mipLevel = 0; + copy_region.srcSubresource.baseArrayLayer = 0; + copy_region.srcSubresource.layerCount = 1; + copy_region.srcOffset.x = 0; + copy_region.srcOffset.y = 0; + copy_region.srcOffset.z = 0; + copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.dstSubresource.mipLevel = 0; + copy_region.dstSubresource.baseArrayLayer = 0; + copy_region.dstSubresource.layerCount = 1; + copy_region.dstOffset.x = 0; + copy_region.dstOffset.y = 0; + copy_region.dstOffset.z = 0; + copy_region.extent.width = tex_width; + copy_region.extent.height = tex_height; + copy_region.extent.depth = 1; + + // Put the copy command into the command buffer + vkCmdCopyImage(cmd, + mappableImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, ©_region); + + assert(res == VK_SUCCESS); + + // Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + + // Then drop the temporary mappable image - although should not be necessary... + vulkan_->Delete().QueueDeleteImage(mappableImage); + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; + } + + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format_; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.image = image; + VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::Wipe() { + if (image) { + vulkan_->Delete().QueueDeleteImage(image); + image = VK_NULL_HANDLE; + } + if (view) { + vulkan_->Delete().QueueDeleteImageView(view); + view = VK_NULL_HANDLE; + } + if (mem) { + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + mem = VK_NULL_HANDLE; + } +} + +void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format, VkImageUsageFlags usage) { + Wipe(); + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + + tex_width = w; + tex_height = h; + numMips_ = numMips; + format_ = format; + + VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = numMips; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.flags = 0; + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); + VkMemoryAllocateInfo mem_alloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + // Find memory type - don't specify any mapping requirements + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); + assert(res == VK_SUCCESS); + + // Since we're going to blit to the target, set its layout to TRANSFER_DST + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + // Create the view while we're at it. + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format_; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = numMips; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.image = image; + res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, uint32_t offset, size_t rowLength) { + VkBufferImageCopy copy_region = {}; + copy_region.bufferOffset = offset; + copy_region.bufferRowLength = (uint32_t)rowLength; + copy_region.bufferImageHeight = 0; // 2D + copy_region.imageExtent.width = mipWidth; + copy_region.imageExtent.height = mipHeight; + copy_region.imageExtent.depth = 1; + copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.imageSubresource.mipLevel = mip; + copy_region.imageSubresource.baseArrayLayer = 0; + copy_region.imageSubresource.layerCount = 1; + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + vkCmdCopyBufferToImage(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); +} + +void VulkanTexture::EndCreate() { + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); +} + +void VulkanTexture::Destroy() { + if (view) { + vulkan_->Delete().QueueDeleteImageView(view); + } + if (image) { + vulkan_->Delete().QueueDeleteImage(image); + if (mappableImage == image) { + mappableImage = VK_NULL_HANDLE; + } + } + if (mem) { + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + if (mappableMemory == mem) { + mappableMemory = VK_NULL_HANDLE; + } + } + + view = VK_NULL_HANDLE; + image = VK_NULL_HANDLE; + mem = VK_NULL_HANDLE; +} diff --git a/Common/Vulkan/VulkanImage.h b/Common/Vulkan/VulkanImage.h new file mode 100644 index 0000000000..fe2dbe6dbd --- /dev/null +++ b/Common/Vulkan/VulkanImage.h @@ -0,0 +1,50 @@ +#pragma once + +#include "Common/Vulkan/VulkanContext.h" + +// Wrapper around what you need to use a texture. +// Not very optimal - if you have many small textures you should use other strategies. +class VulkanTexture { +public: + VulkanTexture(VulkanContext *vulkan) + : vulkan_(vulkan), image(VK_NULL_HANDLE), mem(VK_NULL_HANDLE), view(VK_NULL_HANDLE), + tex_width(0), tex_height(0), numMips_(1), format_(VK_FORMAT_UNDEFINED), + mappableImage(VK_NULL_HANDLE), mappableMemory(VK_NULL_HANDLE), needStaging(false) { + memset(&mem_reqs, 0, sizeof(mem_reqs)); + } + ~VulkanTexture() { + Destroy(); + } + + // Simple usage - no cleverness, no mipmaps. + // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. + // Can later Lock and Unlock again. This cannot change the format. Create cannot + // be called a second time without recreating the texture object until Destroy has + // been called. + VkResult Create(int w, int h, VkFormat format); + uint8_t *Lock(int level, int *rowPitch); + void Unlock(); + + // Fast uploads from buffer. Mipmaps supported. Usage must at least include VK_IMAGE_USAGE_TRANSFER_DST_BIT in order to use UploadMip. + void CreateDirect(int w, int h, int numMips, VkFormat format, VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, uint32_t offset, size_t rowLength); // rowLength is in pixels + void EndCreate(); + int GetNumMips() const { return numMips_; } + void Destroy(); + + VkImageView GetImageView() const { return view; } + +private: + void CreateMappableImage(); + void Wipe(); + VulkanContext *vulkan_; + VkImage image; + VkDeviceMemory mem; + VkImageView view; + int32_t tex_width, tex_height, numMips_; + VkFormat format_; + VkImage mappableImage; + VkDeviceMemory mappableMemory; + VkMemoryRequirements mem_reqs; + bool needStaging; +}; diff --git a/Common/Vulkan/VulkanLoader.cpp b/Common/Vulkan/VulkanLoader.cpp new file mode 100644 index 0000000000..559a7bec88 --- /dev/null +++ b/Common/Vulkan/VulkanLoader.cpp @@ -0,0 +1,403 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "Common/Vulkan/VulkanLoader.h" +#include "base/logging.h" + +#ifndef _WIN32 +#include +#endif + + +PFN_vkCreateInstance vkCreateInstance; +PFN_vkDestroyInstance vkDestroyInstance; +PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; +PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; +PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; +PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; +PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; +PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; +PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; +PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; +PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +PFN_vkCreateDevice vkCreateDevice; +PFN_vkDestroyDevice vkDestroyDevice; +PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; +PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; +PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; +PFN_vkGetDeviceQueue vkGetDeviceQueue; +PFN_vkQueueSubmit vkQueueSubmit; +PFN_vkQueueWaitIdle vkQueueWaitIdle; +PFN_vkDeviceWaitIdle vkDeviceWaitIdle; +PFN_vkAllocateMemory vkAllocateMemory; +PFN_vkFreeMemory vkFreeMemory; +PFN_vkMapMemory vkMapMemory; +PFN_vkUnmapMemory vkUnmapMemory; +PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; +PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; +PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; +PFN_vkBindBufferMemory vkBindBufferMemory; +PFN_vkBindImageMemory vkBindImageMemory; +PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; +PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; +PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; +PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; +PFN_vkQueueBindSparse vkQueueBindSparse; +PFN_vkCreateFence vkCreateFence; +PFN_vkDestroyFence vkDestroyFence; +PFN_vkResetFences vkResetFences; +PFN_vkGetFenceStatus vkGetFenceStatus; +PFN_vkWaitForFences vkWaitForFences; +PFN_vkCreateSemaphore vkCreateSemaphore; +PFN_vkDestroySemaphore vkDestroySemaphore; +PFN_vkCreateEvent vkCreateEvent; +PFN_vkDestroyEvent vkDestroyEvent; +PFN_vkGetEventStatus vkGetEventStatus; +PFN_vkSetEvent vkSetEvent; +PFN_vkResetEvent vkResetEvent; +PFN_vkCreateQueryPool vkCreateQueryPool; +PFN_vkDestroyQueryPool vkDestroyQueryPool; +PFN_vkGetQueryPoolResults vkGetQueryPoolResults; +PFN_vkCreateBuffer vkCreateBuffer; +PFN_vkDestroyBuffer vkDestroyBuffer; +PFN_vkCreateBufferView vkCreateBufferView; +PFN_vkDestroyBufferView vkDestroyBufferView; +PFN_vkCreateImage vkCreateImage; +PFN_vkDestroyImage vkDestroyImage; +PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; +PFN_vkCreateImageView vkCreateImageView; +PFN_vkDestroyImageView vkDestroyImageView; +PFN_vkCreateShaderModule vkCreateShaderModule; +PFN_vkDestroyShaderModule vkDestroyShaderModule; +PFN_vkCreatePipelineCache vkCreatePipelineCache; +PFN_vkDestroyPipelineCache vkDestroyPipelineCache; +PFN_vkGetPipelineCacheData vkGetPipelineCacheData; +PFN_vkMergePipelineCaches vkMergePipelineCaches; +PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; +PFN_vkCreateComputePipelines vkCreateComputePipelines; +PFN_vkDestroyPipeline vkDestroyPipeline; +PFN_vkCreatePipelineLayout vkCreatePipelineLayout; +PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; +PFN_vkCreateSampler vkCreateSampler; +PFN_vkDestroySampler vkDestroySampler; +PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; +PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; +PFN_vkCreateDescriptorPool vkCreateDescriptorPool; +PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; +PFN_vkResetDescriptorPool vkResetDescriptorPool; +PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; +PFN_vkFreeDescriptorSets vkFreeDescriptorSets; +PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; +PFN_vkCreateFramebuffer vkCreateFramebuffer; +PFN_vkDestroyFramebuffer vkDestroyFramebuffer; +PFN_vkCreateRenderPass vkCreateRenderPass; +PFN_vkDestroyRenderPass vkDestroyRenderPass; +PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; +PFN_vkCreateCommandPool vkCreateCommandPool; +PFN_vkDestroyCommandPool vkDestroyCommandPool; +PFN_vkResetCommandPool vkResetCommandPool; +PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; +PFN_vkFreeCommandBuffers vkFreeCommandBuffers; +PFN_vkBeginCommandBuffer vkBeginCommandBuffer; +PFN_vkEndCommandBuffer vkEndCommandBuffer; +PFN_vkResetCommandBuffer vkResetCommandBuffer; +PFN_vkCmdBindPipeline vkCmdBindPipeline; +PFN_vkCmdSetViewport vkCmdSetViewport; +PFN_vkCmdSetScissor vkCmdSetScissor; +PFN_vkCmdSetLineWidth vkCmdSetLineWidth; +PFN_vkCmdSetDepthBias vkCmdSetDepthBias; +PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; +PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; +PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; +PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; +PFN_vkCmdSetStencilReference vkCmdSetStencilReference; +PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; +PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; +PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; +PFN_vkCmdDraw vkCmdDraw; +PFN_vkCmdDrawIndexed vkCmdDrawIndexed; +PFN_vkCmdDrawIndirect vkCmdDrawIndirect; +PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; +PFN_vkCmdDispatch vkCmdDispatch; +PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; +PFN_vkCmdCopyBuffer vkCmdCopyBuffer; +PFN_vkCmdCopyImage vkCmdCopyImage; +PFN_vkCmdBlitImage vkCmdBlitImage; +PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; +PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; +PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; +PFN_vkCmdFillBuffer vkCmdFillBuffer; +PFN_vkCmdClearColorImage vkCmdClearColorImage; +PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; +PFN_vkCmdClearAttachments vkCmdClearAttachments; +PFN_vkCmdResolveImage vkCmdResolveImage; +PFN_vkCmdSetEvent vkCmdSetEvent; +PFN_vkCmdResetEvent vkCmdResetEvent; +PFN_vkCmdWaitEvents vkCmdWaitEvents; +PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; +PFN_vkCmdBeginQuery vkCmdBeginQuery; +PFN_vkCmdEndQuery vkCmdEndQuery; +PFN_vkCmdResetQueryPool vkCmdResetQueryPool; +PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; +PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; +PFN_vkCmdPushConstants vkCmdPushConstants; +PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; +PFN_vkCmdNextSubpass vkCmdNextSubpass; +PFN_vkCmdEndRenderPass vkCmdEndRenderPass; +PFN_vkCmdExecuteCommands vkCmdExecuteCommands; + +#ifdef ANDROID +PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; +#elif defined(_WIN32) +PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; +#endif + +PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; + +// WSI extension. +PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; +PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; +PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; +PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; +PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; +PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; +PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; +PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; +PFN_vkQueuePresentKHR vkQueuePresentKHR; + +// And the DEBUG_REPORT extension. +PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; +PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; + +#ifdef _WIN32 +static HINSTANCE vulkanLibrary; +#define dlsym(x, y) GetProcAddress(x, y) +#else +static void *vulkanLibrary; +#endif + +#define LOAD_INSTANCE_FUNC(instance, x) x = (PFN_ ## x)vkGetInstanceProcAddr(instance, #x); if (!x) {ILOG("Missing (instance): %s", #x);} +#define LOAD_DEVICE_FUNC(instance, x) x = (PFN_ ## x)vkGetDeviceProcAddr(instance, #x); if (!x) {ILOG("Missing (device): %s", #x);} +#define LOAD_GLOBAL_FUNC(x) x = (PFN_ ## x)dlsym(vulkanLibrary, #x); if (!x) {ILOG("Missing (global): %s", #x);} + + +bool VulkanLoad() { +#ifndef _WIN32 + vulkanLibrary = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); +#else + // LoadLibrary etc + vulkanLibrary = LoadLibrary(L"vulkan-1.dll"); +#endif + if (!vulkanLibrary) { + return false; + } + + LOAD_GLOBAL_FUNC(vkCreateInstance); + LOAD_GLOBAL_FUNC(vkGetInstanceProcAddr); + LOAD_GLOBAL_FUNC(vkGetDeviceProcAddr); + + LOAD_GLOBAL_FUNC(vkEnumerateInstanceExtensionProperties); + LOAD_GLOBAL_FUNC(vkEnumerateInstanceLayerProperties); + + WLOG("Vulkan base functions loaded."); + return true; +} + +void VulkanLoadInstanceFunctions(VkInstance instance) { + // OK, let's use the above functions to get the rest. + LOAD_INSTANCE_FUNC(instance, vkDestroyInstance); + LOAD_INSTANCE_FUNC(instance, vkEnumeratePhysicalDevices); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceFeatures); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceImageFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceQueueFamilyProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceMemoryProperties); + LOAD_INSTANCE_FUNC(instance, vkCreateDevice); + LOAD_INSTANCE_FUNC(instance, vkDestroyDevice); + LOAD_INSTANCE_FUNC(instance, vkEnumerateDeviceExtensionProperties); + LOAD_INSTANCE_FUNC(instance, vkEnumerateDeviceLayerProperties); + LOAD_INSTANCE_FUNC(instance, vkGetDeviceQueue); + LOAD_INSTANCE_FUNC(instance, vkQueueSubmit); + LOAD_INSTANCE_FUNC(instance, vkQueueWaitIdle); + LOAD_INSTANCE_FUNC(instance, vkDeviceWaitIdle); + LOAD_INSTANCE_FUNC(instance, vkAllocateMemory); + LOAD_INSTANCE_FUNC(instance, vkFreeMemory); + LOAD_INSTANCE_FUNC(instance, vkMapMemory); + LOAD_INSTANCE_FUNC(instance, vkUnmapMemory); + LOAD_INSTANCE_FUNC(instance, vkFlushMappedMemoryRanges); + LOAD_INSTANCE_FUNC(instance, vkInvalidateMappedMemoryRanges); + LOAD_INSTANCE_FUNC(instance, vkGetDeviceMemoryCommitment); + LOAD_INSTANCE_FUNC(instance, vkBindBufferMemory); + LOAD_INSTANCE_FUNC(instance, vkBindImageMemory); + LOAD_INSTANCE_FUNC(instance, vkGetBufferMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetImageMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetImageSparseMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSparseImageFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkQueueBindSparse); + LOAD_INSTANCE_FUNC(instance, vkCreateFence); + LOAD_INSTANCE_FUNC(instance, vkDestroyFence); + LOAD_INSTANCE_FUNC(instance, vkResetFences); + LOAD_INSTANCE_FUNC(instance, vkGetFenceStatus); + LOAD_INSTANCE_FUNC(instance, vkWaitForFences); + LOAD_INSTANCE_FUNC(instance, vkCreateSemaphore); + LOAD_INSTANCE_FUNC(instance, vkDestroySemaphore); + LOAD_INSTANCE_FUNC(instance, vkCreateEvent); + LOAD_INSTANCE_FUNC(instance, vkDestroyEvent); + LOAD_INSTANCE_FUNC(instance, vkGetEventStatus); + LOAD_INSTANCE_FUNC(instance, vkSetEvent); + LOAD_INSTANCE_FUNC(instance, vkResetEvent); + LOAD_INSTANCE_FUNC(instance, vkCreateQueryPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyQueryPool); + LOAD_INSTANCE_FUNC(instance, vkGetQueryPoolResults); + LOAD_INSTANCE_FUNC(instance, vkCreateBuffer); + LOAD_INSTANCE_FUNC(instance, vkDestroyBuffer); + LOAD_INSTANCE_FUNC(instance, vkCreateBufferView); + LOAD_INSTANCE_FUNC(instance, vkDestroyBufferView); + LOAD_INSTANCE_FUNC(instance, vkCreateImage); + LOAD_INSTANCE_FUNC(instance, vkDestroyImage); + LOAD_INSTANCE_FUNC(instance, vkGetImageSubresourceLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateImageView); + LOAD_INSTANCE_FUNC(instance, vkDestroyImageView); + LOAD_INSTANCE_FUNC(instance, vkCreateShaderModule); + LOAD_INSTANCE_FUNC(instance, vkDestroyShaderModule); + LOAD_INSTANCE_FUNC(instance, vkCreatePipelineCache); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipelineCache); + LOAD_INSTANCE_FUNC(instance, vkGetPipelineCacheData); + LOAD_INSTANCE_FUNC(instance, vkMergePipelineCaches); + LOAD_INSTANCE_FUNC(instance, vkCreateGraphicsPipelines); + LOAD_INSTANCE_FUNC(instance, vkCreateComputePipelines); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipeline); + LOAD_INSTANCE_FUNC(instance, vkCreatePipelineLayout); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipelineLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateSampler); + LOAD_INSTANCE_FUNC(instance, vkDestroySampler); + LOAD_INSTANCE_FUNC(instance, vkCreateDescriptorSetLayout); + LOAD_INSTANCE_FUNC(instance, vkDestroyDescriptorSetLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkResetDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkAllocateDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkFreeDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkUpdateDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkCreateFramebuffer); + LOAD_INSTANCE_FUNC(instance, vkDestroyFramebuffer); + LOAD_INSTANCE_FUNC(instance, vkCreateRenderPass); + LOAD_INSTANCE_FUNC(instance, vkDestroyRenderPass); + LOAD_INSTANCE_FUNC(instance, vkGetRenderAreaGranularity); + LOAD_INSTANCE_FUNC(instance, vkCreateCommandPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyCommandPool); + LOAD_INSTANCE_FUNC(instance, vkResetCommandPool); + LOAD_INSTANCE_FUNC(instance, vkAllocateCommandBuffers); + LOAD_INSTANCE_FUNC(instance, vkFreeCommandBuffers); + LOAD_INSTANCE_FUNC(instance, vkBeginCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkEndCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkResetCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdBindPipeline); + LOAD_INSTANCE_FUNC(instance, vkCmdSetViewport); + LOAD_INSTANCE_FUNC(instance, vkCmdSetScissor); + LOAD_INSTANCE_FUNC(instance, vkCmdSetLineWidth); + LOAD_INSTANCE_FUNC(instance, vkCmdSetDepthBias); + LOAD_INSTANCE_FUNC(instance, vkCmdSetBlendConstants); + LOAD_INSTANCE_FUNC(instance, vkCmdSetDepthBounds); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilCompareMask); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilWriteMask); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilReference); + LOAD_INSTANCE_FUNC(instance, vkCmdBindDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkCmdBindIndexBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdBindVertexBuffers); + LOAD_INSTANCE_FUNC(instance, vkCmdDraw); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndexed); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndexedIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdDispatch); + LOAD_INSTANCE_FUNC(instance, vkCmdDispatchIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyImage); + LOAD_INSTANCE_FUNC(instance, vkCmdBlitImage); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyBufferToImage); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyImageToBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdUpdateBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdFillBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdClearColorImage); + LOAD_INSTANCE_FUNC(instance, vkCmdClearDepthStencilImage); + LOAD_INSTANCE_FUNC(instance, vkCmdClearAttachments); + LOAD_INSTANCE_FUNC(instance, vkCmdResolveImage); + LOAD_INSTANCE_FUNC(instance, vkCmdSetEvent); + LOAD_INSTANCE_FUNC(instance, vkCmdResetEvent); + LOAD_INSTANCE_FUNC(instance, vkCmdWaitEvents); + LOAD_INSTANCE_FUNC(instance, vkCmdPipelineBarrier); + LOAD_INSTANCE_FUNC(instance, vkCmdBeginQuery); + LOAD_INSTANCE_FUNC(instance, vkCmdEndQuery); + LOAD_INSTANCE_FUNC(instance, vkCmdResetQueryPool); + LOAD_INSTANCE_FUNC(instance, vkCmdWriteTimestamp); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyQueryPoolResults); + LOAD_INSTANCE_FUNC(instance, vkCmdPushConstants); + LOAD_INSTANCE_FUNC(instance, vkCmdBeginRenderPass); + LOAD_INSTANCE_FUNC(instance, vkCmdNextSubpass); + LOAD_INSTANCE_FUNC(instance, vkCmdEndRenderPass); + LOAD_INSTANCE_FUNC(instance, vkCmdExecuteCommands); + + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceSupportKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceCapabilitiesKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceFormatsKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfacePresentModesKHR); + + LOAD_INSTANCE_FUNC(instance, vkCreateSwapchainKHR); + LOAD_INSTANCE_FUNC(instance, vkDestroySwapchainKHR); + LOAD_INSTANCE_FUNC(instance, vkGetSwapchainImagesKHR); + LOAD_INSTANCE_FUNC(instance, vkAcquireNextImageKHR); + LOAD_INSTANCE_FUNC(instance, vkQueuePresentKHR); + +#ifdef _WIN32 + LOAD_INSTANCE_FUNC(instance, vkCreateWin32SurfaceKHR); +#elif defined(ANDROID) + LOAD_INSTANCE_FUNC(instance, vkCreateAndroidSurfaceKHR); +#endif + + LOAD_INSTANCE_FUNC(instance, vkDestroySurfaceKHR); + + LOAD_INSTANCE_FUNC(instance, vkCreateDebugReportCallbackEXT); + LOAD_INSTANCE_FUNC(instance, vkDestroyDebugReportCallbackEXT); + WLOG("Vulkan instance functions loaded."); +} + +// On some implementations, loading functions (that have Device as their first parameter) via vkGetDeviceProcAddr may +// increase performance - but then these function pointers will only work on that specific device. Thus, this loader is not very +// good for multi-device. +void VulkanLoadDeviceFunctions(VkDevice device) { + WLOG("Vulkan device functions loaded."); + // TODO: Move more functions VulkanLoadInstanceFunctions to here. + LOAD_DEVICE_FUNC(device, vkCreateSwapchainKHR); + LOAD_DEVICE_FUNC(device, vkDestroySwapchainKHR); + LOAD_DEVICE_FUNC(device, vkGetSwapchainImagesKHR); + LOAD_DEVICE_FUNC(device, vkAcquireNextImageKHR); + LOAD_DEVICE_FUNC(device, vkQueuePresentKHR); +} + +void VulkanFree() { +#ifdef _WIN32 + if (vulkanLibrary) { + FreeLibrary(vulkanLibrary); + } +#else + if (vulkanLibrary) { + dlclose(vulkanLibrary); + } +#endif +} diff --git a/Common/Vulkan/VulkanLoader.h b/Common/Vulkan/VulkanLoader.h new file mode 100644 index 0000000000..5c36804596 --- /dev/null +++ b/Common/Vulkan/VulkanLoader.h @@ -0,0 +1,198 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#ifdef ANDROID +#define VK_USE_PLATFORM_ANDROID_KHR +#elif defined(_WIN32) +#define VK_USE_PLATFORM_WIN32_KHR +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#endif + +#define VK_NO_PROTOTYPES + +#include "ext/vulkan/vulkan.h" + +extern PFN_vkCreateInstance vkCreateInstance; +extern PFN_vkDestroyInstance vkDestroyInstance; +extern PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; +extern PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; +extern PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; +extern PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; +extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; +extern PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; +extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; +extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; +extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +extern PFN_vkCreateDevice vkCreateDevice; +extern PFN_vkDestroyDevice vkDestroyDevice; +extern PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +extern PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; +extern PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; +extern PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; +extern PFN_vkGetDeviceQueue vkGetDeviceQueue; +extern PFN_vkQueueSubmit vkQueueSubmit; +extern PFN_vkQueueWaitIdle vkQueueWaitIdle; +extern PFN_vkDeviceWaitIdle vkDeviceWaitIdle; +extern PFN_vkAllocateMemory vkAllocateMemory; +extern PFN_vkFreeMemory vkFreeMemory; +extern PFN_vkMapMemory vkMapMemory; +extern PFN_vkUnmapMemory vkUnmapMemory; +extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; +extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; +extern PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; +extern PFN_vkBindBufferMemory vkBindBufferMemory; +extern PFN_vkBindImageMemory vkBindImageMemory; +extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; +extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; +extern PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; +extern PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; +extern PFN_vkQueueBindSparse vkQueueBindSparse; +extern PFN_vkCreateFence vkCreateFence; +extern PFN_vkDestroyFence vkDestroyFence; +extern PFN_vkResetFences vkResetFences; +extern PFN_vkGetFenceStatus vkGetFenceStatus; +extern PFN_vkWaitForFences vkWaitForFences; +extern PFN_vkCreateSemaphore vkCreateSemaphore; +extern PFN_vkDestroySemaphore vkDestroySemaphore; +extern PFN_vkCreateEvent vkCreateEvent; +extern PFN_vkDestroyEvent vkDestroyEvent; +extern PFN_vkGetEventStatus vkGetEventStatus; +extern PFN_vkSetEvent vkSetEvent; +extern PFN_vkResetEvent vkResetEvent; +extern PFN_vkCreateQueryPool vkCreateQueryPool; +extern PFN_vkDestroyQueryPool vkDestroyQueryPool; +extern PFN_vkGetQueryPoolResults vkGetQueryPoolResults; +extern PFN_vkCreateBuffer vkCreateBuffer; +extern PFN_vkDestroyBuffer vkDestroyBuffer; +extern PFN_vkCreateBufferView vkCreateBufferView; +extern PFN_vkDestroyBufferView vkDestroyBufferView; +extern PFN_vkCreateImage vkCreateImage; +extern PFN_vkDestroyImage vkDestroyImage; +extern PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; +extern PFN_vkCreateImageView vkCreateImageView; +extern PFN_vkDestroyImageView vkDestroyImageView; +extern PFN_vkCreateShaderModule vkCreateShaderModule; +extern PFN_vkDestroyShaderModule vkDestroyShaderModule; +extern PFN_vkCreatePipelineCache vkCreatePipelineCache; +extern PFN_vkDestroyPipelineCache vkDestroyPipelineCache; +extern PFN_vkGetPipelineCacheData vkGetPipelineCacheData; +extern PFN_vkMergePipelineCaches vkMergePipelineCaches; +extern PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; +extern PFN_vkCreateComputePipelines vkCreateComputePipelines; +extern PFN_vkDestroyPipeline vkDestroyPipeline; +extern PFN_vkCreatePipelineLayout vkCreatePipelineLayout; +extern PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; +extern PFN_vkCreateSampler vkCreateSampler; +extern PFN_vkDestroySampler vkDestroySampler; +extern PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; +extern PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; +extern PFN_vkCreateDescriptorPool vkCreateDescriptorPool; +extern PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; +extern PFN_vkResetDescriptorPool vkResetDescriptorPool; +extern PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; +extern PFN_vkFreeDescriptorSets vkFreeDescriptorSets; +extern PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; +extern PFN_vkCreateFramebuffer vkCreateFramebuffer; +extern PFN_vkDestroyFramebuffer vkDestroyFramebuffer; +extern PFN_vkCreateRenderPass vkCreateRenderPass; +extern PFN_vkDestroyRenderPass vkDestroyRenderPass; +extern PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; +extern PFN_vkCreateCommandPool vkCreateCommandPool; +extern PFN_vkDestroyCommandPool vkDestroyCommandPool; +extern PFN_vkResetCommandPool vkResetCommandPool; +extern PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; +extern PFN_vkFreeCommandBuffers vkFreeCommandBuffers; +extern PFN_vkBeginCommandBuffer vkBeginCommandBuffer; +extern PFN_vkEndCommandBuffer vkEndCommandBuffer; +extern PFN_vkResetCommandBuffer vkResetCommandBuffer; +extern PFN_vkCmdBindPipeline vkCmdBindPipeline; +extern PFN_vkCmdSetViewport vkCmdSetViewport; +extern PFN_vkCmdSetScissor vkCmdSetScissor; +extern PFN_vkCmdSetLineWidth vkCmdSetLineWidth; +extern PFN_vkCmdSetDepthBias vkCmdSetDepthBias; +extern PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; +extern PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; +extern PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; +extern PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; +extern PFN_vkCmdSetStencilReference vkCmdSetStencilReference; +extern PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; +extern PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; +extern PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; +extern PFN_vkCmdDraw vkCmdDraw; +extern PFN_vkCmdDrawIndexed vkCmdDrawIndexed; +extern PFN_vkCmdDrawIndirect vkCmdDrawIndirect; +extern PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; +extern PFN_vkCmdDispatch vkCmdDispatch; +extern PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; +extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; +extern PFN_vkCmdCopyImage vkCmdCopyImage; +extern PFN_vkCmdBlitImage vkCmdBlitImage; +extern PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; +extern PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; +extern PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; +extern PFN_vkCmdFillBuffer vkCmdFillBuffer; +extern PFN_vkCmdClearColorImage vkCmdClearColorImage; +extern PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; +extern PFN_vkCmdClearAttachments vkCmdClearAttachments; +extern PFN_vkCmdResolveImage vkCmdResolveImage; +extern PFN_vkCmdSetEvent vkCmdSetEvent; +extern PFN_vkCmdResetEvent vkCmdResetEvent; +extern PFN_vkCmdWaitEvents vkCmdWaitEvents; +extern PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; +extern PFN_vkCmdBeginQuery vkCmdBeginQuery; +extern PFN_vkCmdEndQuery vkCmdEndQuery; +extern PFN_vkCmdResetQueryPool vkCmdResetQueryPool; +extern PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; +extern PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; +extern PFN_vkCmdPushConstants vkCmdPushConstants; +extern PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; +extern PFN_vkCmdNextSubpass vkCmdNextSubpass; +extern PFN_vkCmdEndRenderPass vkCmdEndRenderPass; +extern PFN_vkCmdExecuteCommands vkCmdExecuteCommands; + +#ifdef ANDROID +extern PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; +#elif defined(_WIN32) +extern PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; +#endif + +extern PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; + +// Simple loader for the WSI extension. +extern PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; +extern PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; +extern PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; +extern PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; + +extern PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; +extern PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; +extern PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; +extern PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; +extern PFN_vkQueuePresentKHR vkQueuePresentKHR; + +// And the DEBUG_REPORT extension. +extern PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; +extern PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; + +bool VulkanLoad(); +void VulkanLoadInstanceFunctions(VkInstance instance); +void VulkanLoadDeviceFunctions(VkDevice device); +void VulkanFree(); + diff --git a/Common/Vulkan/VulkanMemory.cpp b/Common/Vulkan/VulkanMemory.cpp new file mode 100644 index 0000000000..2daf1d5bfb --- /dev/null +++ b/Common/Vulkan/VulkanMemory.cpp @@ -0,0 +1,48 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +// Additionally, Common/Vulkan/* , including this file, are also licensed +// under the public domain. + +#include "Common/Vulkan/VulkanMemory.h" + +VulkanPushBuffer::VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(0) { + VkDevice device = vulkan->GetDevice(); + + VkBufferCreateInfo b = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; + b.size = size; + b.flags = 0; + b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + b.queueFamilyIndexCount = 0; + b.pQueueFamilyIndices = nullptr; + VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); + assert(VK_SUCCESS == res); + + // Okay, that's the buffer. Now let's allocate some memory for it. + VkMemoryAllocateInfo alloc = {}; + alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc.pNext = nullptr; + + vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &alloc.memoryTypeIndex); + alloc.allocationSize = size; + + res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); + assert(VK_SUCCESS == res); + res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); + assert(VK_SUCCESS == res); +} diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h new file mode 100644 index 0000000000..8ea4cb08db --- /dev/null +++ b/Common/Vulkan/VulkanMemory.h @@ -0,0 +1,102 @@ +#pragma once + +#include "Common/Vulkan/VulkanContext.h" + +// VulkanMemory +// +// Vulkan memory management utils. + +// VulkanPushBuffer +// Simple incrementing allocator. +// Use these to push vertex, index and uniform data. Generally you'll have two of these +// and alternate on each frame. Make sure not to reset until the fence from the last time you used it +// has completed. +// +// TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. +// TODO: Make this auto-grow and shrink. Need to be careful about returning and using the new +// buffer handle on overflow. +class VulkanPushBuffer { +public: + VulkanPushBuffer(VulkanContext *vulkan, size_t size); + + ~VulkanPushBuffer() { + assert(buffer_ == VK_NULL_HANDLE); + assert(deviceMemory_ == VK_NULL_HANDLE); + } + + void Destroy(VulkanContext *vulkan) { + vulkan->Delete().QueueDeleteBuffer(buffer_); + vulkan->Delete().QueueDeleteDeviceMemory(deviceMemory_); + buffer_ = VK_NULL_HANDLE; + deviceMemory_ = VK_NULL_HANDLE; + } + + void Reset() { offset_ = 0; } + + void Begin(VkDevice device) { + offset_ = 0; + VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); + assert(VK_SUCCESS == res); + } + + void End(VkDevice device) { + /* + VkMappedMemoryRange range = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE }; + range.offset = 0; + range.size = offset_; + range.memory = deviceMemory_; + vkFlushMappedMemoryRanges(device, 1, &range); + */ + vkUnmapMemory(device, deviceMemory_); + writePtr_ = nullptr; + } + + // When using the returned memory, make sure to bind the returned vkbuf. + // This will later allow for handling overflow correctly. + size_t Allocate(size_t numBytes, VkBuffer *vkbuf) { + size_t out = offset_; + offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + + if (offset_ >= size_) { + // TODO: Allocate a second buffer, then combine them on the next frame. +#ifdef _WIN32 + DebugBreak(); +#endif + } + *vkbuf = buffer_; + return out; + } + + // TODO: Add alignment support? + // Returns the offset that should be used when binding this buffer to get this data. + size_t Push(const void *data, size_t size, VkBuffer *vkbuf) { + size_t off = Allocate(size, vkbuf); + memcpy(writePtr_ + off, data, size); + return off; + } + + uint32_t PushAligned(const void *data, size_t size, int align, VkBuffer *vkbuf) { + offset_ = (offset_ + align - 1) & ~(align - 1); + size_t off = Allocate(size, vkbuf); + memcpy(writePtr_ + off, data, size); + return (uint32_t)off; + } + + size_t GetOffset() const { + return offset_; + } + + // "Zero-copy" variant - you can write the data directly as you compute it. + void *Push(size_t size, uint32_t *bindOffset, VkBuffer *vkbuf) { + size_t off = Allocate(size, vkbuf); + *bindOffset = (uint32_t)off; + return writePtr_ + off; + } + +private: + VkDeviceMemory deviceMemory_; + VkBuffer buffer_; + size_t offset_; + size_t size_; + uint8_t *writePtr_; +}; diff --git a/Core/Config.cpp b/Core/Config.cpp index dc656c2d90..b96a23b950 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -454,11 +454,11 @@ static ConfigSetting graphicsSettings[] = { #endif ReportedConfigSetting("ForceMaxEmulatedFPS", &g_Config.iForceMaxEmulatedFPS, 60, true, true), - // TODO: Hm, on fast mobile GPUs we should definitely default to at least 4... + // TODO: Hm, on fast mobile GPUs we should definitely default to at least 4 (setting = 2)... #ifdef MOBILE_DEVICE ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 0, true, true), #else - ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 8, true, true), + ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 4, true, true), #endif ReportedConfigSetting("VertexCache", &g_Config.bVertexCache, true, true, true), ReportedConfigSetting("TextureBackoffCache", &g_Config.bTextureBackoffCache, false, true, true), @@ -862,6 +862,7 @@ void Config::Load(const char *iniFileName, const char *controllerIniFilename) { vPinnedPaths.push_back(it->second); } + // This caps the exponent 4 (so 16x.) if (iAnisotropyLevel > 4) { iAnisotropyLevel = 4; } diff --git a/Core/Config.h b/Core/Config.h index df58435160..8618adaa46 100644 --- a/Core/Config.h +++ b/Core/Config.h @@ -50,10 +50,14 @@ enum BufferFilter { enum class GPUBackend { OPENGL = 0, DIRECT3D9 = 1, + DIRECT3D11 = 2, + VULKAN = 3, }; enum { GPU_BACKEND_OPENGL = (int)GPUBackend::OPENGL, GPU_BACKEND_DIRECT3D9 = (int)GPUBackend::DIRECT3D9, + GPU_BACKEND_DIRECT3D11 = (int)GPUBackend::DIRECT3D11, + GPU_BACKEND_VULKAN = (int)GPUBackend::VULKAN, }; enum AudioBackendType { diff --git a/Core/Core.cpp b/Core/Core.cpp index f588b8c38d..508c69ce0d 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -34,6 +34,7 @@ #ifdef _WIN32 #include "Windows/GPU/WindowsGLContext.h" #include "Windows/GPU/D3D9Context.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "Windows/InputDevice.h" #endif diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index 09b1d79cfc..514cf98e74 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -45,7 +45,6 @@ StaticLibrary false - false Unicode v140_xp @@ -158,6 +157,7 @@ USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;USE_FFMPEG;WIN32;_ARCH_64=1;_M_X64=1;_LIB;NDEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions) false MultiThreaded + true true @@ -737,4 +737,4 @@ - \ No newline at end of file + diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 0b60f84189..e19984a171 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -31,19 +31,23 @@ enum GPUCore { GPU_GLES, GPU_SOFTWARE, GPU_DIRECTX9, + GPU_DIRECTX11, + GPU_VULKAN, }; class FileLoader; class GraphicsContext; +class Thin3DContext; // PSP_CoreParameter() struct CoreParameter { - CoreParameter() : collectEmuLog(0), unthrottle(false), fpsLimit(0), updateRecent(true), freezeNext(false), frozen(false), mountIsoLoader(nullptr) {} + CoreParameter() : thin3d(nullptr), collectEmuLog(0), unthrottle(false), fpsLimit(0), updateRecent(true), freezeNext(false), frozen(false), mountIsoLoader(nullptr) {} CPUCore cpuCore; GPUCore gpuCore; GraphicsContext *graphicsContext; // TODO: Find a better place. + Thin3DContext *thin3d; bool enableSound; // there aren't multiple sound cores. std::string fileToStart; diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index 878303a2f0..b1fdb606bf 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -439,7 +439,8 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { "Texture invalidations: %i\n" "Vertex shaders loaded: %i\n" "Fragment shaders loaded: %i\n" - "Combined shaders loaded: %i\n", + "Combined shaders loaded: %i\n" + "Pushbuffer space used: UBO %d, Vtx %d, Idx %d\n", gpuStats.numVBlanks, gpuStats.msProcessingDisplayLists * 1000.0f, kernelStats.msInSyscalls * 1000.0f, @@ -463,7 +464,10 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { gpuStats.numTextureInvalidations, gpuStats.numVertexShaders, gpuStats.numFragmentShaders, - gpuStats.numShaders + gpuStats.numShaders, + gpuStats.pushUBOSpaceUsed, + gpuStats.pushVertexSpaceUsed, + gpuStats.pushIndexSpaceUsed ); stats[bufsize - 1] = '\0'; gpuStats.ResetFrame(); diff --git a/Core/System.cpp b/Core/System.cpp index 0df10e3d91..d1613cc617 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -386,7 +386,12 @@ bool PSP_InitStart(const CoreParameter &coreParam, std::string *error_string) { #else INFO_LOG(BOOT, "PPSSPP %s", PPSSPP_GIT_VERSION); #endif + + GraphicsContext *temp = coreParameter.graphicsContext; coreParameter = coreParam; + if (coreParameter.graphicsContext == nullptr) { + coreParameter.graphicsContext = temp; + } coreParameter.errorString = ""; pspIsIniting = true; @@ -420,7 +425,7 @@ bool PSP_InitUpdate(std::string *error_string) { bool success = coreParameter.fileToStart != ""; *error_string = coreParameter.errorString; if (success) { - success = GPU_Init(coreParameter.graphicsContext); + success = GPU_Init(coreParameter.graphicsContext, coreParameter.thin3d); if (!success) { PSP_Shutdown(); *error_string = "Unable to initialize rendering engine."; diff --git a/Core/System.h b/Core/System.h index 7749d893bc..4ff1767d87 100644 --- a/Core/System.h +++ b/Core/System.h @@ -68,6 +68,8 @@ void PSP_BeginHostFrame(); void PSP_EndHostFrame(); void PSP_RunLoopUntil(u64 globalticks); void PSP_RunLoopFor(int cycles); +void PSP_BeginFrame(); +void PSP_EndFrame(); void Audio_Init(); diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 721fdf18a3..2a250a21de 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -27,7 +27,7 @@ #define WRITE p+=sprintf // Uses integer instructions available since OpenGL 3.0. Suitable for ES 3.0 as well. -void GenerateDepalShader300(char *buffer, GEBufferFormat pixelFormat) { +void GenerateDepalShader300(char *buffer, GEBufferFormat pixelFormat, ShaderLanguage language) { char *p = buffer; if (gl_extensions.IsGLES) { WRITE(p, "#version 300 es\n"); @@ -250,7 +250,8 @@ void GenerateDepalShader(char *buffer, GEBufferFormat pixelFormat, ShaderLanguag GenerateDepalShaderFloat(buffer, pixelFormat, language); break; case GLSL_300: - GenerateDepalShader300(buffer, pixelFormat); + case GLSL_VULKAN: + GenerateDepalShader300(buffer, pixelFormat, language); break; case HLSL_DX9: GenerateDepalShaderFloat(buffer, pixelFormat, language); diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 57a87c889c..c49a65cdbf 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -22,6 +22,7 @@ enum ShaderLanguage { GLSL_140, GLSL_300, + GLSL_VULKAN, HLSL_DX9, }; diff --git a/GPU/Common/FramebufferCommon.h b/GPU/Common/FramebufferCommon.h index e236a64f6d..4456e3461c 100644 --- a/GPU/Common/FramebufferCommon.h +++ b/GPU/Common/FramebufferCommon.h @@ -51,6 +51,8 @@ namespace DX9 { struct FBO_DX9; } +class VulkanFBO; + struct VirtualFramebuffer { int last_frame_used; int last_frame_attached; @@ -85,11 +87,13 @@ struct VirtualFramebuffer { int lastFrameNewSize; GEBufferFormat format; // virtual, right now they are all RGBA8888 + // TODO: Handle fbo and colorDepth better. u8 colorDepth; union { FBO *fbo; DX9::FBO_DX9 *fbo_dx9; + VulkanFBO *fbo_vk; }; u16 drawnWidth; diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index 88d45eb6b1..0762ddd4f0 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -544,6 +544,7 @@ float FromScaledDepth(float z) { void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out) { bool throughmode = gstate.isModeThrough(); out.dirtyProj = false; + out.dirtyDepth = false; float renderWidthFactor, renderHeightFactor; float renderX = 0.0f, renderY = 0.0f; @@ -640,31 +641,33 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float hScale = 1.0f; float yOffset = 0.0f; - // If we're within the bounds, we want clipping the viewport way. So leave it be. - if (left < 0.0f || right > renderWidth) { - float overageLeft = std::max(-left, 0.0f); - float overageRight = std::max(right - renderWidth, 0.0f); - // Our center drifted by the difference in overages. - float drift = overageRight - overageLeft; + if (!gstate_c.Supports(GPU_SUPPORTS_LARGE_VIEWPORTS)) { + // If we're within the bounds, we want clipping the viewport way. So leave it be. + if (left < 0.0f || right > renderWidth) { + float overageLeft = std::max(-left, 0.0f); + float overageRight = std::max(right - renderWidth, 0.0f); + // Our center drifted by the difference in overages. + float drift = overageRight - overageLeft; - left += overageLeft; - right -= overageRight; + left += overageLeft; + right -= overageRight; - wScale = vpWidth / (right - left); - xOffset = drift / (right - left); - } + wScale = vpWidth / (right - left); + xOffset = drift / (right - left); + } - if (top < 0.0f || bottom > renderHeight) { - float overageTop = std::max(-top, 0.0f); - float overageBottom = std::max(bottom - renderHeight, 0.0f); - // Our center drifted by the difference in overages. - float drift = overageBottom - overageTop; + if (top < 0.0f || bottom > renderHeight) { + float overageTop = std::max(-top, 0.0f); + float overageBottom = std::max(bottom - renderHeight, 0.0f); + // Our center drifted by the difference in overages. + float drift = overageBottom - overageTop; - top += overageTop; - bottom -= overageBottom; + top += overageTop; + bottom -= overageBottom; - hScale = vpHeight / (bottom - top); - yOffset = drift / (bottom - top); + hScale = vpHeight / (bottom - top); + yOffset = drift / (bottom - top); + } } out.viewportX = left + displayOffsetX; diff --git a/GPU/Common/ShaderCommon.h b/GPU/Common/ShaderCommon.h index ef2a05c26b..8d23dfd9a0 100644 --- a/GPU/Common/ShaderCommon.h +++ b/GPU/Common/ShaderCommon.h @@ -22,6 +22,7 @@ enum DebugShaderType { SHADER_TYPE_FRAGMENT = 1, SHADER_TYPE_GEOMETRY = 2, SHADER_TYPE_VERTEXLOADER = 3, // Not really a shader, but might as well re-use this mechanism + SHADER_TYPE_PIPELINE = 4, // Vulkan and DX12 combines a bunch of state into pipeline objects. Might as well make them inspectable. }; enum DebugShaderStringType { diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index 1bf7cb7a1a..98d55089bf 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -122,7 +122,7 @@ void ComputeVertexShaderID(ShaderID *id_out, u32 vertType, bool useHWTransform) if (doTextureProjection && gstate.getUVProjMode() == GE_PROJMAP_UV) { id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, (vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT); // two bits } else { - id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, 3); + id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, 3); // float - no scaling } } diff --git a/GPU/Common/SoftwareTransformCommon.cpp b/GPU/Common/SoftwareTransformCommon.cpp index 00a05dc4a0..669e4924d2 100644 --- a/GPU/Common/SoftwareTransformCommon.cpp +++ b/GPU/Common/SoftwareTransformCommon.cpp @@ -129,8 +129,14 @@ static bool IsReallyAClear(const TransformedVertex *transformed, int numVerts) { } void SoftwareTransform( - int prim, u8 *decoded, int vertexCount, u32 vertType, u16 *&inds, int indexType, - const DecVtxFormat &decVtxFormat, int &maxIndex, FramebufferManagerCommon *fbman, TextureCacheCommon *texCache, TransformedVertex *transformed, TransformedVertex *transformedExpanded, TransformedVertex *&drawBuffer, int &numTrans, bool &drawIndexed, SoftwareTransformResult *result, float ySign) { + int prim, int vertexCount, u32 vertType, u16 *&inds, int indexType, + const DecVtxFormat &decVtxFormat, int &maxIndex, TransformedVertex *&drawBuffer, int &numTrans, bool &drawIndexed, const SoftwareTransformParams *params, SoftwareTransformResult *result) { + u8 *decoded = params->decoded; + FramebufferManagerCommon *fbman = params->fbman; + TextureCacheCommon *texCache = params->texCache; + TransformedVertex *transformed = params->transformed; + TransformedVertex *transformedExpanded = params->transformedExpanded; + float ySign = 1.0f; bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0; bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled(); @@ -406,11 +412,16 @@ void SoftwareTransform( // Experiment: Disable on PowerVR (see issue #6290) // TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not. if (maxIndex > 1 && gstate.isModeClear() && prim == GE_PRIM_RECTANGLES && IsReallyAClear(transformed, maxIndex) && gl_extensions.gpuVendor != GPU_VENDOR_POWERVR) { // && g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) { - result->color = transformed[1].color0_32; - // Need to rescale from a [0, 1] float. This is the final transformed value. - result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f)); - result->action = SW_CLEAR; - return; + // If alpha is not allowed to be separate, it must match for both depth/stencil and color. Vulkan requires this. + bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask(); + bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask(); + if (params->allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil)) { + result->color = transformed[1].color0_32; + // Need to rescale from a [0, 1] float. This is the final transformed value. + result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f)); + result->action = SW_CLEAR; + return; + } } // This means we're using a framebuffer (and one that isn't big enough.) diff --git a/GPU/Common/SoftwareTransformCommon.h b/GPU/Common/SoftwareTransformCommon.h index 581bfbfbd5..9ae3bd2697 100644 --- a/GPU/Common/SoftwareTransformCommon.h +++ b/GPU/Common/SoftwareTransformCommon.h @@ -38,5 +38,14 @@ struct SoftwareTransformResult { u8 stencilValue; }; -void SoftwareTransform(int prim, u8 *decoded, int vertexCount, u32 vertexType, u16 *&inds, int indexType, const DecVtxFormat &decVtxFormat, int &maxIndex, FramebufferManagerCommon *fbman, TextureCacheCommon *texCache, TransformedVertex *transformed, TransformedVertex *transformedExpanded, TransformedVertex *&drawBuffer, - int &numTrans, bool &drawIndexed, SoftwareTransformResult *result, float ySign); +struct SoftwareTransformParams { + u8 *decoded; + TransformedVertex *transformed; + TransformedVertex *transformedExpanded; + FramebufferManagerCommon *fbman; + TextureCacheCommon *texCache; + bool allowSeparateAlphaClear; +}; + +void SoftwareTransform(int prim, int vertexCount, u32 vertexType, u16 *&inds, int indexType, const DecVtxFormat &decVtxFormat, int &maxIndex, TransformedVertex *&drawBuffer, + int &numTrans, bool &drawIndexed, const SoftwareTransformParams *params, SoftwareTransformResult *result); diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 95ff12aa60..9b24211d9e 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -39,6 +39,8 @@ enum FramebufferNotification { struct VirtualFramebuffer; +class CachedTextureVulkan; + class TextureCacheCommon { public: TextureCacheCommon(); @@ -96,6 +98,7 @@ public: union { u32 textureName; void *texturePtr; + CachedTextureVulkan *vkTex; }; int invalidHint; u32 fullhash; @@ -104,7 +107,7 @@ public: u16 maxSeenV; // Cache the current filter settings so we can avoid setting it again. - // (OpenGL madness where filter settings are attached to each texture). + // (OpenGL madness where filter settings are attached to each texture. Unused in Vulkan). u8 magFilt; u8 minFilt; bool sClamp; diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index 101e3295b0..9a3ec013b3 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -1118,7 +1118,7 @@ int VertexDecoder::ToString(char *output) const { if (tc) output += sprintf(output, "T: %s ", tcnames[tc]); if (weighttype) - output += sprintf(output, "W: %s (%ix)", weightnames[weighttype], nweights); + output += sprintf(output, "W: %s (%ix) ", weightnames[weighttype], nweights); if (idx) output += sprintf(output, "I: %s ", idxnames[idx]); if (morphcount > 1) diff --git a/GPU/Common/VertexDecoderCommon.h b/GPU/Common/VertexDecoderCommon.h index 69dbe4da53..14ed122bae 100644 --- a/GPU/Common/VertexDecoderCommon.h +++ b/GPU/Common/VertexDecoderCommon.h @@ -106,8 +106,7 @@ inline int RoundUp4(int x) { } // Reads decoded vertex formats in a convenient way. For software transform and debugging. -class VertexReader -{ +class VertexReader { public: VertexReader(u8 *base, const DecVtxFormat &decFmt, int vtype) : base_(base), data_(base), decFmt_(decFmt), vtype_(vtype) {} diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index a21f0a703e..7481c508d8 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -480,6 +480,24 @@ void DIRECTX9_GPU::CheckGPUFeatures() { features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; features |= GPU_PREFER_CPU_DOWNLOAD; features |= GPU_SUPPORTS_ACCURATE_DEPTH; + features |= GPU_SUPPORTS_UNPACK_SUBIMAGE; + + D3DCAPS9 caps; + ZeroMemory(&caps, sizeof(caps)); + HRESULT result = 0; + if (pD3DdeviceEx) { + result = pD3DdeviceEx->GetDeviceCaps(&caps); + } else { + result = pD3Ddevice->GetDeviceCaps(&caps); + } + if (FAILED(result)) { + WARN_LOG_REPORT(G3D, "Direct3D9: Failed to get the device caps!"); + } else { + if ((caps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) != 0 && caps.MaxAnisotropy > 1) + features |= GPU_SUPPORTS_ANISOTROPY; + if ((caps.TextureCaps & (D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_POW2)) == 0) + features |= GPU_SUPPORTS_OES_TEXTURE_NPOT; + } if (!g_Config.bHighQualityDepth) { features |= GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT; diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index c8f2d67084..e772734e6d 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -603,7 +603,7 @@ void TextureCacheDX9::UpdateSamplingParams(TexCacheEntry &entry, bool force) { D3DTEXTUREFILTERTYPE mipf = (D3DTEXTUREFILTERTYPE)MipFilt[minFilt]; D3DTEXTUREFILTERTYPE magf = (D3DTEXTUREFILTERTYPE)MagFilt[magFilt]; - if (g_Config.iAnisotropyLevel > 0 && minf == D3DTEXF_LINEAR) { + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0 && minf == D3DTEXF_LINEAR) { minf = D3DTEXF_ANISOTROPIC; } @@ -653,8 +653,11 @@ void TextureCacheDX9::StartFrame() { Decimate(); } - DWORD anisotropyLevel = (DWORD)g_Config.iAnisotropyLevel > maxAnisotropyLevel ? maxAnisotropyLevel : g_Config.iAnisotropyLevel; - pD3Ddevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, anisotropyLevel); + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY)) { + DWORD aniso = 1 << g_Config.iAnisotropyLevel; + DWORD anisotropyLevel = aniso > maxAnisotropyLevel ? maxAnisotropyLevel : aniso; + pD3Ddevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, anisotropyLevel); + } } @@ -1639,6 +1642,7 @@ TextureCacheDX9::TexCacheEntry::Status TextureCacheDX9::CheckAlpha(const u32 *pi return (TexCacheEntry::Status)res; } +// TODO: xoffset and yoffset are unused - bug? static inline void copyTexture(int xoffset, int yoffset, int w, int h, int pitch, int srcfmt, int fmt, void * pSrc, void * pDst) { int y; switch(fmt) { diff --git a/GPU/Directx9/TransformPipelineDX9.cpp b/GPU/Directx9/TransformPipelineDX9.cpp index 19f894c7b8..5e9f9d6596 100644 --- a/GPU/Directx9/TransformPipelineDX9.cpp +++ b/GPU/Directx9/TransformPipelineDX9.cpp @@ -828,11 +828,20 @@ rotateVBO: SoftwareTransformResult result; memset(&result, 0, sizeof(result)); + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = true; + int maxIndex = indexGen.MaxIndex(); SoftwareTransform( - prim, decoded, indexGen.VertexCount(), + prim, indexGen.VertexCount(), dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), - maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); ApplyDrawStateLate(); vshader = shaderManager_->ApplyShader(prim, lastVType_); diff --git a/GPU/Directx9/VertexShaderGeneratorDX9.cpp b/GPU/Directx9/VertexShaderGeneratorDX9.cpp index d464e59ab1..905c84722c 100644 --- a/GPU/Directx9/VertexShaderGeneratorDX9.cpp +++ b/GPU/Directx9/VertexShaderGeneratorDX9.cpp @@ -102,7 +102,6 @@ void GenerateVertexShaderDX9(const ShaderID &id, char *buffer) { if (enableBones) { numBoneWeights = 1 + id.Bits(VS_BIT_BONES, 3); } - int texFmtScale = id.Bits(VS_BIT_TEXCOORD_FMTSCALE, 2); WRITE(p, "#pragma warning( disable : 3571 )\n"); diff --git a/GPU/GLES/Framebuffer.cpp b/GPU/GLES/Framebuffer.cpp index 6ef3bf0ffe..b33e886bb1 100644 --- a/GPU/GLES/Framebuffer.cpp +++ b/GPU/GLES/Framebuffer.cpp @@ -1987,7 +1987,7 @@ bool FramebufferManager::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferF return true; } - buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, false, true); + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, !useBufferedRendering_, true); if (vfb->fbo) fbo_bind_for_read(vfb->fbo); if (gl_extensions.GLES3 || !gl_extensions.IsGLES) diff --git a/GPU/GLES/GLES_GPU.cpp b/GPU/GLES/GLES_GPU.cpp index 9efdeb0b8d..c6ee431456 100644 --- a/GPU/GLES/GLES_GPU.cpp +++ b/GPU/GLES/GLES_GPU.cpp @@ -565,6 +565,8 @@ void GLES_GPU::CheckGPUFeatures() { if (gl_extensions.GLES3 || !gl_extensions.IsGLES) features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; + features |= GPU_SUPPORTS_ANISOTROPY; + // If we already have a 16-bit depth buffer, we don't need to round. if (fbo_standard_z_depth() > 16) { if (!g_Config.bHighQualityDepth && (features & GPU_SUPPORTS_ACCURATE_DEPTH) != 0) { diff --git a/GPU/GLES/StateMapping.cpp b/GPU/GLES/StateMapping.cpp index e693bd3768..1993d88d60 100644 --- a/GPU/GLES/StateMapping.cpp +++ b/GPU/GLES/StateMapping.cpp @@ -152,7 +152,7 @@ inline void TransformDrawEngine::ResetShaderBlending() { } void TransformDrawEngine::ApplyDrawState(int prim) { - // TODO: All this setup is soon so expensive that we'll need dirty flags, or simply do it in the command writes where we detect dirty by xoring. Silly to do all this work on every drawcall. + // TODO: All this setup is so expensive that we'll need dirty flags, or simply do it in the command writes where we detect dirty by xoring. Silly to do all this work on every drawcall. if (gstate_c.textureChanged != TEXCHANGE_UNCHANGED && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { textureCache_->SetTexture(); diff --git a/GPU/GLES/TextureCache.cpp b/GPU/GLES/TextureCache.cpp index c799e02c85..5c096af52d 100644 --- a/GPU/GLES/TextureCache.cpp +++ b/GPU/GLES/TextureCache.cpp @@ -1485,9 +1485,11 @@ void TextureCache::SetTexture(bool force) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); } - int aniso = 1 << g_Config.iAnisotropyLevel; - float anisotropyLevel = (float) aniso > maxAnisotropyLevel ? maxAnisotropyLevel : (float) aniso; - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropyLevel); + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY)) { + int aniso = 1 << g_Config.iAnisotropyLevel; + float anisotropyLevel = (float) aniso > maxAnisotropyLevel ? maxAnisotropyLevel : (float) aniso; + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropyLevel); + } gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; diff --git a/GPU/GLES/TransformPipeline.cpp b/GPU/GLES/TransformPipeline.cpp index b23d5239bc..edd8a8657a 100644 --- a/GPU/GLES/TransformPipeline.cpp +++ b/GPU/GLES/TransformPipeline.cpp @@ -890,11 +890,21 @@ rotateVBO: SoftwareTransformResult result; memset(&result, 0, sizeof(result)); + // TODO: Keep this static? Faster than repopulating? + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = true; + int maxIndex = indexGen.MaxIndex(); SoftwareTransform( - prim, decoded, indexGen.VertexCount(), + prim, indexGen.VertexCount(), dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), - maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0); + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); ApplyDrawStateLate(); LinkedShader *program = shaderManager_->ApplyFragmentShader(vsid, vshader, lastVType_, prim); diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 915d953bfb..f5bec931d5 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -15,11 +15,15 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include "Common/GraphicsContext.h" #include "Core/Core.h" #include "GPU/GPU.h" #include "GPU/GPUInterface.h" #include "GPU/GLES/GLES_GPU.h" +#ifndef NO_VULKAN +#include "GPU/Vulkan/GPU_Vulkan.h" +#endif #include "GPU/Null/NullGpu.h" #include "GPU/Software/SoftGpu.h" @@ -41,7 +45,8 @@ static void SetGPU(T *obj) { #ifdef USE_CRT_DBG #undef new #endif -bool GPU_Init(GraphicsContext *ctx) { + +bool GPU_Init(GraphicsContext *ctx, Thin3DContext *thin3d) { switch (PSP_CoreParameter().gpuCore) { case GPU_NULL: SetGPU(new NullGPU()); @@ -50,13 +55,20 @@ bool GPU_Init(GraphicsContext *ctx) { SetGPU(new GLES_GPU(ctx)); break; case GPU_SOFTWARE: - SetGPU(new SoftGPU(ctx)); + SetGPU(new SoftGPU(ctx, thin3d)); break; case GPU_DIRECTX9: #if defined(_WIN32) SetGPU(new DIRECTX9_GPU(ctx)); #endif break; + case GPU_DIRECTX11: + return nullptr; +#ifndef NO_VULKAN + case GPU_VULKAN: + SetGPU(new GPU_Vulkan(ctx)); + break; +#endif } return gpu != NULL; diff --git a/GPU/GPU.h b/GPU/GPU.h index d036d3ebea..6989ba4d18 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -89,6 +89,9 @@ struct GPUStatistics { int vertexGPUCycles; int otherGPUCycles; int gpuCommandsAtCallLevel[4]; + int pushUBOSpaceUsed; + int pushVertexSpaceUsed; + int pushIndexSpaceUsed; // Total statistics, updated by the GPU core in UpdateStats int numVBlanks; @@ -104,5 +107,7 @@ extern GPUStatistics gpuStats; extern GPUInterface *gpu; extern GPUDebugInterface *gpuDebug; -bool GPU_Init(GraphicsContext *ctx); +class Thin3DContext; + +bool GPU_Init(GraphicsContext *ctx, Thin3DContext *thin3d); void GPU_Shutdown(); diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index f089cec7f4..cfb441cc35 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -45,7 +45,6 @@ StaticLibrary false - false Unicode v140_xp @@ -84,7 +83,7 @@ Level3 - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; _CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_32=1;_M_IX86=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions) StreamingSIMDExtensions2 Fast @@ -106,7 +105,7 @@ Level3 - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; NotSet Fast false @@ -132,7 +131,7 @@ MaxSpeed true true - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; false StreamingSIMDExtensions2 Fast @@ -158,7 +157,7 @@ MaxSpeed true true - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; false NotSet Fast @@ -168,6 +167,7 @@ false USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;_M_X64=1;_LIB;NDEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions) MultiThreaded + true true @@ -244,6 +244,18 @@ + + + + + + + + + + + + @@ -322,6 +334,18 @@ + + + + + + + + + + + + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index d4bfb7b987..7558d33b67 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -22,6 +22,9 @@ {0cbddc00-4aa3-41d0-bed2-a454d37f838e} + + {3c621896-140c-4c8b-8e4d-a478bfdeca8a} + @@ -201,6 +204,42 @@ Common + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + @@ -386,5 +425,39 @@ Common + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + \ No newline at end of file diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 59671d1dd4..5d4c3f006e 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -456,6 +456,9 @@ enum { GPU_SUPPORTS_BLEND_MINMAX = FLAG_BIT(4), GPU_SUPPORTS_LOGIC_OP = FLAG_BIT(5), GPU_USE_DEPTH_RANGE_HACK = FLAG_BIT(6), + GPU_SUPPORTS_WIDE_LINES = FLAG_BIT(7), + GPU_SUPPORTS_ANISOTROPY = FLAG_BIT(8), + GPU_SUPPORTS_LARGE_VIEWPORTS = FLAG_BIT(16), GPU_SUPPORTS_ACCURATE_DEPTH = FLAG_BIT(17), GPU_SUPPORTS_VAO = FLAG_BIT(18), GPU_SUPPORTS_ANY_COPY_IMAGE = FLAG_BIT(19), diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index d14d7872e3..c9e44c2cbe 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -42,18 +42,14 @@ FormatBuffer fb; FormatBuffer depthbuf; u32 clut[4096]; -static Thin3DContext *thin3d = nullptr; -static Thin3DTexture *fbTex = nullptr; static Thin3DVertexFormat *vformat = nullptr; static Thin3DDepthStencilState *depth = nullptr; static Thin3DBuffer *vdata = nullptr; static Thin3DBuffer *idata = nullptr; -static std::vector fbTexBuffer; -SoftGPU::SoftGPU(GraphicsContext *gfxCtx) - : gfxCtx_(gfxCtx) +SoftGPU::SoftGPU(GraphicsContext *gfxCtx, Thin3DContext *_thin3D) + : gfxCtx_(gfxCtx), thin3d(_thin3D) { - thin3d = gfxCtx_->CreateThin3DContext(); fbTex = thin3d->CreateTexture(LINEAR2D, RGBA8888, 480, 272, 1, 1); std::vector components; @@ -87,8 +83,6 @@ SoftGPU::~SoftGPU() { vformat = nullptr; fbTex->Release(); fbTex = nullptr; - thin3d->Release(); - thin3d = nullptr; } void SoftGPU::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { diff --git a/GPU/Software/SoftGpu.h b/GPU/Software/SoftGpu.h index 423b4f22d3..481fd4ae6b 100644 --- a/GPU/Software/SoftGpu.h +++ b/GPU/Software/SoftGpu.h @@ -45,10 +45,12 @@ typedef struct { } FormatBuffer; class ShaderManager; +class Thin3DContext; +class Thin3DTexture; class SoftGPU : public GPUCommon { public: - SoftGPU(GraphicsContext *gfxCtx); + SoftGPU(GraphicsContext *gfxCtx, Thin3DContext *_thin3D); ~SoftGPU(); void InitClear() override {} void ExecuteOp(u32 op, u32 diff) override; @@ -102,4 +104,7 @@ private: GEBufferFormat displayFormat_; GraphicsContext *gfxCtx_; + Thin3DTexture *fbTex; + Thin3DContext *thin3d; + std::vector fbTexBuffer; }; diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.cpp b/GPU/Vulkan/DepalettizeShaderVulkan.cpp new file mode 100644 index 0000000000..2de073cabe --- /dev/null +++ b/GPU/Vulkan/DepalettizeShaderVulkan.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2014- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY{} without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + + +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" + +DepalShaderCacheVulkan::DepalShaderCacheVulkan() { + +} + +DepalShaderCacheVulkan::~DepalShaderCacheVulkan() { + +} + +DepalShaderVulkan *DepalShaderCacheVulkan::GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) { + return nullptr; +} + +VulkanTexture *DepalShaderCacheVulkan::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { + return nullptr; +} + +void DepalShaderCacheVulkan::Clear() {} + +void DepalShaderCacheVulkan::Decimate() {} + +u32 DepalShaderCacheVulkan::GenerateShaderID(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) { + return 0; +} + +bool DepalShaderCacheVulkan::CreateVertexShader() { + return false; +} diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.h b/GPU/Vulkan/DepalettizeShaderVulkan.h new file mode 100644 index 0000000000..63faa1c8b6 --- /dev/null +++ b/GPU/Vulkan/DepalettizeShaderVulkan.h @@ -0,0 +1,64 @@ +// Copyright (c) 2014- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "Common/CommonTypes.h" +#include "GPU/ge_constants.h" + +class DepalShaderVulkan { +public: + /* + GLuint program; + GLuint fragShader; + GLint a_position; + GLint a_texcoord0; + */ +}; + +class DepalTextureVulkan { +public: + int texture; + int lastFrame; +}; + +class VulkanTexture; + +// Caches both shaders and palette textures. +// Could even avoid bothering with palette texture and just use uniform data... +class DepalShaderCacheVulkan { +public: + DepalShaderCacheVulkan(); + ~DepalShaderCacheVulkan(); + + // This also uploads the palette and binds the correct texture. + DepalShaderVulkan *GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); + VulkanTexture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); + void Clear(); + void Decimate(); + +private: + u32 GenerateShaderID(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); + bool CreateVertexShader(); + + // GLuint vertexShader_; + std::map cache_; + std::map texCache_; +}; + diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp new file mode 100644 index 0000000000..173bbfc38b --- /dev/null +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -0,0 +1,813 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include + +#include "base/logging.h" +#include "base/timeutil.h" +#include "math/dataconv.h" + +#include "Common/MemoryUtil.h" +#include "Core/MemMap.h" +#include "Core/Host.h" +#include "Core/System.h" +#include "Core/Reporting.h" +#include "Core/Config.h" +#include "Core/CoreTiming.h" + +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" + +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanMemory.h" + +#include "GPU/Common/TextureDecoder.h" +#include "GPU/Common/SplineCommon.h" +#include "GPU/Common/TransformCommon.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/SoftwareTransformCommon.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/GPU_Vulkan.h" + +enum { + DRAW_BINDING_TEXTURE = 0, + DRAW_BINDING_2ND_TEXTURE = 1, + DRAW_BINDING_DYNUBO_BASE = 2, + DRAW_BINDING_DYNUBO_LIGHT = 3, + DRAW_BINDING_DYNUBO_BONE = 4, +}; + +enum { + TRANSFORMED_VERTEX_BUFFER_SIZE = VERTEX_BUFFER_MAX * sizeof(TransformedVertex) +}; + +DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) + : + vulkan_(vulkan), + prevPrim_(GE_PRIM_INVALID), + lastVTypeID_(-1), + pipelineManager_(nullptr), + textureCache_(nullptr), + framebufferManager_(nullptr), + numDrawCalls(0), + vertexCountInDrawCalls(0), + fboTexNeedBind_(false), + fboTexBound_(false), + curFrame_(0) { + + memset(&decOptions_, 0, sizeof(decOptions_)); + decOptions_.expandAllUVtoFloat = false; // this may be a good idea though. + decOptions_.expandAllWeightsToFloat = false; + decOptions_.expand8BitNormalsToFloat = false; + + // Allocate nicely aligned memory. Maybe graphics drivers will + // appreciate it. + // All this is a LOT of memory, need to see if we can cut down somehow. + decoded = (u8 *)AllocateMemoryPages(DECODED_VERTEX_BUFFER_SIZE); + decIndex = (u16 *)AllocateMemoryPages(DECODED_INDEX_BUFFER_SIZE); + splineBuffer = (u8 *)AllocateMemoryPages(SPLINE_BUFFER_SIZE); + transformed = (TransformedVertex *)AllocateMemoryPages(TRANSFORMED_VERTEX_BUFFER_SIZE); + transformedExpanded = (TransformedVertex *)AllocateMemoryPages(3 * TRANSFORMED_VERTEX_BUFFER_SIZE); + + indexGen.Setup(decIndex); + + // All resources we need for PSP drawing. Usually only bindings 0 and 2-4 are populated. + VkDescriptorSetLayoutBinding bindings[5]; + bindings[0].descriptorCount = 1; + bindings[0].pImmutableSamplers = nullptr; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[0].binding = DRAW_BINDING_TEXTURE; + bindings[1].descriptorCount = 1; + bindings[1].pImmutableSamplers = nullptr; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[1].binding = DRAW_BINDING_2ND_TEXTURE; + bindings[2].descriptorCount = 1; + bindings[2].pImmutableSamplers = nullptr; + bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[2].stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[2].binding = DRAW_BINDING_DYNUBO_BASE; + bindings[3].descriptorCount = 1; + bindings[3].pImmutableSamplers = nullptr; + bindings[3].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[3].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[3].binding = DRAW_BINDING_DYNUBO_LIGHT; + bindings[4].descriptorCount = 1; + bindings[4].pImmutableSamplers = nullptr; + bindings[4].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[4].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[4].binding = DRAW_BINDING_DYNUBO_BONE; + + VkDevice device = vulkan_->GetDevice(); + + VkDescriptorSetLayoutCreateInfo dsl; + dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + dsl.pNext = nullptr; + dsl.bindingCount = 5; + dsl.pBindings = bindings; + VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); + assert(VK_SUCCESS == res); + + VkDescriptorPoolSize dpTypes[2]; + dpTypes[0].descriptorCount = 2048; + dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[1].descriptorCount = 200; + dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + VkDescriptorPoolCreateInfo dp; + dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + dp.pNext = nullptr; + dp.flags = 0; // Don't want to mess around with individually freeing these, let's go fixed each frame and zap the whole array. Might try the dynamic approach later. + dp.maxSets = 1000; + dp.pPoolSizes = dpTypes; + dp.poolSizeCount = ARRAY_SIZE(dpTypes); + + // We are going to use one-shot descriptors in the initial implementation. Might look into caching them + // if creating and updating them turns out to be expensive. + for (int i = 0; i < 2; i++) { + VkResult res = vkCreateDescriptorPool(vulkan_->GetDevice(), &dp, nullptr, &frame_[i].descPool); + assert(VK_SUCCESS == res); + frame_[i].pushUBO = new VulkanPushBuffer(vulkan_, 16 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushVertex = new VulkanPushBuffer(vulkan_, 8 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushIndex = new VulkanPushBuffer(vulkan_, 2 * 1024 * 1024); // TODO: Do something more dynamic + } + + VkPipelineLayoutCreateInfo pl; + pl.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pl.pNext = nullptr; + pl.pPushConstantRanges = nullptr; + pl.pushConstantRangeCount = 0; + pl.setLayoutCount = 1; + pl.pSetLayouts = &descriptorSetLayout_; + pl.flags = 0; + res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); + assert(VK_SUCCESS == res); + + VkSamplerCreateInfo samp = {}; + samp.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samp.pNext = nullptr; + 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.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + samp.flags = 0; + samp.magFilter = VK_FILTER_LINEAR; + samp.minFilter = VK_FILTER_LINEAR; + res = vkCreateSampler(device, &samp, nullptr, &depalSampler_); + assert(VK_SUCCESS == res); +} + +DrawEngineVulkan::~DrawEngineVulkan() { + FreeMemoryPages(decoded, DECODED_VERTEX_BUFFER_SIZE); + FreeMemoryPages(decIndex, DECODED_INDEX_BUFFER_SIZE); + FreeMemoryPages(splineBuffer, SPLINE_BUFFER_SIZE); + FreeMemoryPages(transformed, TRANSFORMED_VERTEX_BUFFER_SIZE); + FreeMemoryPages(transformedExpanded, 3 * TRANSFORMED_VERTEX_BUFFER_SIZE); + + for (int i = 0; i < 2; i++) { + vulkan_->Delete().QueueDeleteDescriptorPool(frame_[i].descPool); + frame_[i].pushUBO->Destroy(vulkan_); + frame_[i].pushVertex->Destroy(vulkan_); + frame_[i].pushIndex->Destroy(vulkan_); + delete frame_[i].pushUBO; + delete frame_[i].pushVertex; + delete frame_[i].pushIndex; + } + vulkan_->Delete().QueueDeleteSampler(depalSampler_); +} + +void DrawEngineVulkan::BeginFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); + frame->descSets.clear(); + + // First reset all buffers, then begin. This is so that Reset can free memory and Begin can allocate it, + // if growing the buffer is needed. Doing it this way will reduce fragmentation if more than one buffer + // needs to grow in the same frame. The state where many buffers are reset can also be used to + // defragment memory. + frame->pushUBO->Reset(); + frame->pushVertex->Reset(); + frame->pushIndex->Reset(); + + frame->pushUBO->Begin(vulkan_->GetDevice()); + frame->pushVertex->Begin(vulkan_->GetDevice()); + frame->pushIndex->Begin(vulkan_->GetDevice()); + + DirtyAllUBOs(); +} + +void DrawEngineVulkan::EndFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + gpuStats.pushUBOSpaceUsed = (int)frame->pushUBO->GetOffset(); + gpuStats.pushVertexSpaceUsed = (int)frame->pushVertex->GetOffset(); + gpuStats.pushIndexSpaceUsed = (int)frame->pushIndex->GetOffset(); + frame->pushUBO->End(vulkan_->GetDevice()); + frame->pushVertex->End(vulkan_->GetDevice()); + frame->pushIndex->End(vulkan_->GetDevice()); + curFrame_++; +} + +VertexDecoder *DrawEngineVulkan::GetVertexDecoder(u32 vtype) { + auto iter = decoderMap_.find(vtype); + if (iter != decoderMap_.end()) + return iter->second; + VertexDecoder *dec = new VertexDecoder(); + dec->SetVertexType(vtype, decOptions_, decJitCache_); + decoderMap_[vtype] = dec; + return dec; +} + +void DrawEngineVulkan::SetupVertexDecoder(u32 vertType) { + SetupVertexDecoderInternal(vertType); +} + +inline void DrawEngineVulkan::SetupVertexDecoderInternal(u32 vertType) { + // As the decoder depends on the UVGenMode when we use UV prescale, we simply mash it + // into the top of the verttype where there are unused bits. + const u32 vertTypeID = (vertType & 0xFFFFFF) | (gstate.getUVGenMode() << 24); + + // If vtype has changed, setup the vertex decoder. + if (vertTypeID != lastVTypeID_) { + dec_ = GetVertexDecoder(vertTypeID); + lastVTypeID_ = vertTypeID; + } +} + +void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead) { + if (!indexGen.PrimCompatible(prevPrim_, prim) || numDrawCalls >= MAX_DEFERRED_DRAW_CALLS || vertexCountInDrawCalls + vertexCount > VERTEX_BUFFER_MAX) + Flush(cmd_); + + // TODO: Is this the right thing to do? + if (prim == GE_PRIM_KEEP_PREVIOUS) { + prim = prevPrim_ != GE_PRIM_INVALID ? prevPrim_ : GE_PRIM_POINTS; + } else { + prevPrim_ = prim; + } + + SetupVertexDecoderInternal(vertType); + + *bytesRead = vertexCount * dec_->VertexSize(); + if ((vertexCount < 2 && prim > 0) || (vertexCount < 3 && prim > 2 && prim != GE_PRIM_RECTANGLES)) + return; + + DeferredDrawCall &dc = drawCalls[numDrawCalls]; + dc.verts = verts; + dc.inds = inds; + dc.vertType = vertType; + dc.indexType = (vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT; + dc.prim = prim; + dc.vertexCount = vertexCount; + + if (inds) { + GetIndexBounds(inds, vertexCount, vertType, &dc.indexLowerBound, &dc.indexUpperBound); + } else { + dc.indexLowerBound = 0; + dc.indexUpperBound = vertexCount - 1; + } + + numDrawCalls++; + vertexCountInDrawCalls += vertexCount; + + if (prim == GE_PRIM_RECTANGLES && (gstate.getTextureAddress(0) & 0x3FFFFFFF) == (gstate.getFrameBufAddress() & 0x3FFFFFFF)) { + // Rendertarget == texture? + if (!g_Config.bDisableSlowFramebufEffects) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + Flush(cmd_); + } + } +} + +void DrawEngineVulkan::DecodeVerts(VulkanPushBuffer *push, uint32_t *bindOffset, VkBuffer *vkbuf) { + int decodedVerts = 0; + + u8 *dest = decoded; + + // Figure out how much pushbuffer space we need to allocate. + if (push) { + int vertsToDecode = 0; + for (int i = 0; i < numDrawCalls; i++) { + const DeferredDrawCall &dc = drawCalls[i]; + if (dc.indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { + vertsToDecode += dc.indexUpperBound - dc.indexLowerBound + 1; + } else { + vertsToDecode += dc.vertexCount; + } + } + dest = (u8 *)push->Push(vertsToDecode * dec_->GetDecVtxFmt().stride, bindOffset, vkbuf); + } + + for (int i = 0; i < numDrawCalls; i++) { + const DeferredDrawCall &dc = drawCalls[i]; + + indexGen.SetIndex(decodedVerts); + int indexLowerBound = dc.indexLowerBound, indexUpperBound = dc.indexUpperBound; + + void *inds = dc.inds; + if (dc.indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { + // Decode the verts and apply morphing. Simple. + dec_->DecodeVerts(dest + decodedVerts * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts += indexUpperBound - indexLowerBound + 1; + indexGen.AddPrim(dc.prim, dc.vertexCount); + } else { + // It's fairly common that games issue long sequences of PRIM calls, with differing + // inds pointer but the same base vertex pointer. We'd like to reuse vertices between + // these as much as possible, so we make sure here to combine as many as possible + // into one nice big drawcall, sharing data. + + // 1. Look ahead to find the max index, only looking as "matching" drawcalls. + // Expand the lower and upper bounds as we go. + int lastMatch = i; + const int total = numDrawCalls; + for (int j = i + 1; j < total; ++j) { + if (drawCalls[j].verts != dc.verts) + break; + + indexLowerBound = std::min(indexLowerBound, (int)drawCalls[j].indexLowerBound); + indexUpperBound = std::max(indexUpperBound, (int)drawCalls[j].indexUpperBound); + lastMatch = j; + } + + // 2. Loop through the drawcalls, translating indices as we go. + switch (dc.indexType) { + case GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u8 *)drawCalls[j].inds, indexLowerBound); + } + break; + case GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u16 *)drawCalls[j].inds, indexLowerBound); + } + break; + } + + const int vertexCount = indexUpperBound - indexLowerBound + 1; + + // This check is a workaround for Pangya Fantasy Golf, which sends bogus index data when switching items in "My Room" sometimes. + if (decodedVerts + vertexCount > VERTEX_BUFFER_MAX) { + return; + } + + // 3. Decode that range of vertex data. + dec_->DecodeVerts(dest + decodedVerts * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts += vertexCount; + + // 4. Advance indexgen vertex counter. + indexGen.Advance(vertexCount); + i = lastMatch; + } + } + // Sanity check + if (indexGen.Prim() < 0) { + ERROR_LOG_REPORT(G3D, "DecodeVerts: Failed to deduce prim: %i", indexGen.Prim()); + // Force to points (0) + indexGen.AddPrim(GE_PRIM_POINTS, 0); + } +} + +inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { + // Switch to u32 units. + const u32 *p = (const u32 *)ptr; + sz >>= 2; + + if (sz > 100) { + size_t step = sz / 4; + u32 hash = 0; + for (size_t i = 0; i < sz; i += step) { + hash += DoReliableHash32(p + i, 100, 0x3A44B9C4); + } + return hash; + } else { + return p[0] + p[sz - 1]; + } +} + +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone) { + DescriptorSetKey key; + key.imageView_ = imageView; + key.sampler_ = sampler; + key.secondaryImageView_ = VK_NULL_HANDLE; + key.base_ = base; + key.light_ = light; + key.bone_ = bone; + assert(base != VK_NULL_HANDLE); + assert(light != VK_NULL_HANDLE); + assert(bone != VK_NULL_HANDLE); + + FrameData *frame = &frame_[curFrame_ & 1]; + auto iter = frame->descSets.find(key); + if (iter != frame->descSets.end()) { + return iter->second; + } + + // Didn't find one in the frame descriptor set cache, let's make a new one. + // We wipe the cache on every frame. + + VkDescriptorSet desc; + VkDescriptorSetAllocateInfo descAlloc; + VkDescriptorImageInfo tex; + descAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + descAlloc.pNext = nullptr; + descAlloc.pSetLayouts = &descriptorSetLayout_; + descAlloc.descriptorPool = frame->descPool; + descAlloc.descriptorSetCount = 1; + VkResult result = vkAllocateDescriptorSets(vulkan_->GetDevice(), &descAlloc, &desc); + assert(result == VK_SUCCESS); + + // We just don't write to the slots we don't care about. + VkWriteDescriptorSet writes[4]; + memset(writes, 0, sizeof(writes)); + // Main texture + int n = 0; + if (imageView) { + // TODO: Also support LAYOUT_GENERAL to be able to texture from framebuffers without transitioning them? + tex.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + tex.imageView = imageView; + tex.sampler = sampler; + writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[n].pNext = nullptr; + writes[n].dstBinding = DRAW_BINDING_TEXTURE; + writes[n].pImageInfo = &tex; + writes[n].descriptorCount = 1; + writes[n].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + writes[n].dstSet = desc; + n++; + } + + // Skipping 2nd texture for now. + // Uniform buffer objects + VkDescriptorBufferInfo buf[3]; + int count = 0; + buf[count].buffer = base; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_FS_Base); + count++; + buf[count].buffer = light; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_Lights); + count++; + buf[count].buffer = bone; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_Bones); + count++; + for (int i = 0; i < count; i++) { + writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[n].pNext = nullptr; + writes[n].dstBinding = DRAW_BINDING_DYNUBO_BASE + i; + writes[n].dstArrayElement = 0; + writes[n].pBufferInfo = &buf[i]; + writes[n].dstSet = desc; + writes[n].descriptorCount = 1; + writes[n].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + n++; + } + + vkUpdateDescriptorSets(vulkan_->GetDevice(), n, writes, 0, nullptr); + + frame->descSets[key] = desc; + return desc; +} + +void DrawEngineVulkan::DirtyAllUBOs() { + baseUBOOffset = 0; + lightUBOOffset = 0; + boneUBOOffset = 0; + baseBuf = VK_NULL_HANDLE; + lightBuf = VK_NULL_HANDLE; + boneBuf = VK_NULL_HANDLE; + dirtyUniforms_ = DIRTY_BASE_UNIFORMS | DIRTY_LIGHT_UNIFORMS | DIRTY_BONE_UNIFORMS; +} + +// The inline wrapper in the header checks for numDrawCalls == 0d +void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { + gpuStats.numFlushes++; + + FrameData *frame = &frame_[curFrame_ & 1]; + + // Note than when we implement overflow in pushbuffer, we need to make sure to overflow here, not between + // the three ubo pushes. The reason is that the three UBOs must be in the same buffer as that's how we + // designed the descriptor set. + + VkImageView imageView = VK_NULL_HANDLE; + VkSampler sampler = VK_NULL_HANDLE; + + // TODO: The descriptor set seems to be unbinding the texture when not specified. Cache it or the imageView instead? + // TODO: Add this back when fixed: gstate_c.textureChanged != TEXCHANGE_UNCHANGED && + if (!gstate.isModeClear() && gstate.isTextureMapEnabled()) { + textureCache_->SetTexture(frame->pushUBO); + gstate_c.textureChanged = TEXCHANGE_UNCHANGED; + if (gstate_c.needShaderTexClamp) { + // We will rarely need to set this, so let's do it every time on use rather than in runloop. + // Most of the time non-framebuffer textures will be used which can be clamped themselves. + shaderManager_->DirtyUniform(DIRTY_TEXCLAMP); + } + textureCache_->ApplyTexture(imageView, sampler); + } + + GEPrimitiveType prim = prevPrim_; + + bool useHWTransform = CanUseHardwareTransform(prim); + + VulkanVertexShader *vshader = nullptr; + VulkanFragmentShader *fshader = nullptr; + + uint32_t ibOffset = 0; + uint32_t vbOffset = 0; + + if (useHWTransform) { + // We don't detect clears in this path, so here we can switch framebuffers if necessary. + + int vertexCount = 0; + int maxIndex = 0; + bool useElements = true; + + // Decode directly into the pushbuffer + VkBuffer vbuf; + DecodeVerts(frame->pushVertex, &vbOffset, &vbuf); + gpuStats.numUncachedVertsDrawn += indexGen.VertexCount(); + useElements = !indexGen.SeenOnlyPurePrims(); + vertexCount = indexGen.VertexCount(); + maxIndex = indexGen.MaxIndex(); + if (!useElements && indexGen.PureCount()) { + vertexCount = indexGen.PureCount(); + } + prim = indexGen.Prim(); + + bool hasColor = (lastVTypeID_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + if (gstate.isModeThrough()) { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); + } else { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); + } + + VulkanPipelineRasterStateKey pipelineKey; + VulkanDynamicState dynState; + ConvertStateToVulkanKey(*framebufferManager_, shaderManager_, prim, pipelineKey, dynState); + // TODO: Dirty-flag these. + vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); + vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); + vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); + vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); + float bc[4]; + Uint8x4ToFloat4(bc, dynState.blendColor); + vkCmdSetBlendConstants(cmd_, bc); + + dirtyUniforms_ |= shaderManager_->UpdateUniforms(); + + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, true); + if (!pipeline) { + // Already logged, let's bail out. + return; + } + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + + if ((dirtyUniforms_ & DIRTY_BASE_UNIFORMS) || baseBuf == VK_NULL_HANDLE) { + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &baseBuf); + dirtyUniforms_ &= ~DIRTY_BASE_UNIFORMS; + } + if ((dirtyUniforms_ & DIRTY_LIGHT_UNIFORMS) || lightBuf == VK_NULL_HANDLE) { + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO, &lightBuf); + dirtyUniforms_ &= ~DIRTY_LIGHT_UNIFORMS; + } + if ((dirtyUniforms_ & DIRTY_BONE_UNIFORMS) || boneBuf == VK_NULL_HANDLE) { + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO, &boneBuf); + dirtyUniforms_ &= ~DIRTY_BONE_UNIFORMS; + } + + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, baseBuf, lightBuf, boneBuf); + + const uint32_t dynamicUBOOffsets[3] = { + baseUBOOffset, lightUBOOffset, boneUBOOffset, + }; + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); + + int stride = dec_->GetDecVtxFmt().stride; + + VkDeviceSize offsets[1] = { vbOffset }; + if (useElements) { + VkBuffer ibuf; + ibOffset = (uint32_t)frame->pushIndex->Push(decIndex, 2 * indexGen.VertexCount(), &ibuf); + // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); + vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, 0, 0); + } else { + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); + vkCmdDraw(cmd_, vertexCount, 1, 0, 0); + } + } else { + // Decode to "decoded" + DecodeVerts(nullptr, nullptr, nullptr); + bool hasColor = (lastVTypeID_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + if (gstate.isModeThrough()) { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); + } else { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); + } + + gpuStats.numUncachedVertsDrawn += indexGen.VertexCount(); + prim = indexGen.Prim(); + // Undo the strip optimization, not supported by the SW code yet. + if (prim == GE_PRIM_TRIANGLE_STRIP) + prim = GE_PRIM_TRIANGLES; + VERBOSE_LOG(G3D, "Flush prim %i SW! %i verts in one go", prim, indexGen.VertexCount()); + + int numTrans = 0; + bool drawIndexed = false; + u16 *inds = decIndex; + TransformedVertex *drawBuffer = NULL; + SoftwareTransformResult result; + memset(&result, 0, sizeof(result)); + + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = false; + + int maxIndex = indexGen.MaxIndex(); + SoftwareTransform( + prim, indexGen.VertexCount(), + dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); + + // Only here, where we know whether to clear or to draw primitives, should we actually set the current framebuffer! Because that gives use the opportunity + // to use a "pre-clear" render pass, for high efficiency on tilers. + + if (result.action == SW_DRAW_PRIMITIVES) { + VulkanPipelineRasterStateKey pipelineKey; + VulkanDynamicState dynState; + ConvertStateToVulkanKey(*framebufferManager_, shaderManager_, prim, pipelineKey, dynState); + // TODO: Dirty-flag these. + vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); + vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); + if (dynState.useStencil) { + vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); + vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); + } + if (result.setStencil) { + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, result.stencilValue); + } else if (dynState.useStencil) { + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); + } + + float bc[4]; + Uint8x4ToFloat4(bc, dynState.blendColor); + vkCmdSetBlendConstants(cmd_, bc); + dirtyUniforms_ |= shaderManager_->UpdateUniforms(); + + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, false); + if (!pipeline) { + // Already logged, let's bail out. + return; + } + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + + if ((dirtyUniforms_ & DIRTY_BASE_UNIFORMS) || baseBuf == VK_NULL_HANDLE) { + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &baseBuf); + dirtyUniforms_ &= ~DIRTY_BASE_UNIFORMS; + } + // Even if the first draw is through-mode, make sure we at least have one copy of these uniforms buffered + if ((dirtyUniforms_ & DIRTY_LIGHT_UNIFORMS) || lightBuf == VK_NULL_HANDLE) { + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO, &lightBuf); + dirtyUniforms_ &= ~DIRTY_LIGHT_UNIFORMS; + } + if ((dirtyUniforms_ & DIRTY_BONE_UNIFORMS) || boneBuf == VK_NULL_HANDLE) { + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO, &boneBuf); + dirtyUniforms_ &= ~DIRTY_BONE_UNIFORMS; + } + + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, baseBuf, lightBuf, boneBuf); + const uint32_t dynamicUBOOffsets[3] = { + baseUBOOffset, lightUBOOffset, boneUBOOffset, + }; + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); + + if (drawIndexed) { + VkBuffer vbuf, ibuf; + vbOffset = (uint32_t)frame->pushVertex->Push(drawBuffer, maxIndex * sizeof(TransformedVertex), &vbuf); + ibOffset = (uint32_t)frame->pushIndex->Push(inds, sizeof(short) * numTrans, &ibuf); + VkDeviceSize offsets[1] = { vbOffset }; + // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); + vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); + } else { + VkBuffer vbuf; + vbOffset = (uint32_t)frame->pushVertex->Push(drawBuffer, numTrans * sizeof(TransformedVertex), &vbuf); + VkDeviceSize offsets[1] = { vbOffset }; + // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); + vkCmdDraw(cmd_, numTrans, 1, 0, 0); + } + } else if (result.action == SW_CLEAR) { + // Note: we won't get here if the clear is alpha but not color, or color but not alpha. + // A rectangle will be used instead. + // TODO: If this is the first clear in a frame, translate to a cleared attachment load instead. + + int mask = gstate.isClearModeColorMask() ? 1 : 0; + if (gstate.isClearModeAlphaMask()) mask |= 2; + if (gstate.isClearModeDepthMask()) mask |= 4; + + VkClearValue colorValue, depthValue; + colorValue.color.float32[0] = (result.color & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[1] = ((result.color >> 8) & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[2] = ((result.color >> 16) & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[3] = ((result.color >> 24) & 0xFF) * (1.0f / 255.0f); + depthValue.depthStencil.depth = result.depth; + depthValue.depthStencil.stencil = (result.color >> 24) & 0xFF; + + VkClearRect rect; + rect.baseArrayLayer = 0; + rect.layerCount = 1; + rect.rect.offset.x = 0; + rect.rect.offset.y = 0; + rect.rect.extent.width = gstate_c.curRTRenderWidth; + rect.rect.extent.height = gstate_c.curRTRenderHeight; + + int count = 0; + VkClearAttachment attach[2]; + if (mask & 3) { + attach[count].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + attach[count].clearValue = colorValue; + attach[count].colorAttachment = 0; + count++; + } + if (mask & 4) { + attach[count].aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + attach[count].clearValue = depthValue; + attach[count].colorAttachment = 0; + } + vkCmdClearAttachments(cmd_, count, attach, 1, &rect); + + if (mask & 1) { + framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); + } + if (mask & 4) { + framebufferManager_->SetDepthUpdated(); + } + } + } + + gpuStats.numDrawCalls += numDrawCalls; + gpuStats.numVertsSubmitted += vertexCountInDrawCalls; + + indexGen.Reset(); + numDrawCalls = 0; + vertexCountInDrawCalls = 0; + prevPrim_ = GE_PRIM_INVALID; + gstate_c.vertexFullAlpha = true; + framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); + + // Now seems as good a time as any to reset the min/max coords, which we may examine later. + gstate_c.vertBounds.minU = 512; + gstate_c.vertBounds.minV = 512; + gstate_c.vertBounds.maxU = 0; + gstate_c.vertBounds.maxV = 0; + + host->GPUNotifyDraw(); +} + +void DrawEngineVulkan::Resized() { + decJitCache_->Clear(); + lastVTypeID_ = -1; + dec_ = NULL; + // TODO: We must also wipe pipelines. + for (auto iter = decoderMap_.begin(); iter != decoderMap_.end(); iter++) { + delete iter->second; + } + decoderMap_.clear(); +} + +bool DrawEngineVulkan::IsCodePtrVertexDecoder(const u8 *ptr) const { + return decJitCache_->IsInSpace(ptr); +} diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h new file mode 100644 index 0000000000..afe1a8d606 --- /dev/null +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -0,0 +1,240 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +// The Descriptor Set used for the majority of PSP rendering looks like this: +// +// * binding 0: Texture/Sampler (the PSP texture) +// * binding 1: Secondary texture sampler for shader blending or depal palettes +// * binding 2: Base Uniform Buffer (includes fragment state) +// * binding 3: Light uniform buffer +// * binding 4: Bone uniform buffer +// +// All shaders conform to this layout, so they are all compatible with the same descriptor set. +// The format of the various uniform buffers may vary though - vertex shaders that don't skin +// won't get any bone data, etc. + +#include +#include + +#include "GPU/Vulkan/VulkanUtil.h" + +#include "GPU/GPUState.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Common/IndexGenerator.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Common/GPUStateUtils.h" + +struct DecVtxFormat; +struct UVScale; + +class ShaderManagerVulkan; +class PipelineManagerVulkan; +class TextureCacheVulkan; +class FramebufferManagerVulkan; +class CachedTextureVulkan; + +// Avoiding the full include of TextureDecoder.h. +#if (defined(_M_SSE) && defined(_M_X64)) || defined(ARM64) +typedef u64 ReliableHashType; +#else +typedef u32 ReliableHashType; +#endif + +class VulkanContext; +class VulkanPushBuffer; + +// Handles transform, lighting and drawing. +class DrawEngineVulkan : public DrawEngineCommon { +public: + DrawEngineVulkan(VulkanContext *vulkan); + virtual ~DrawEngineVulkan(); + + void SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead); + + void SetShaderManager(ShaderManagerVulkan *shaderManager) { + shaderManager_ = shaderManager; + } + void SetPipelineManager(PipelineManagerVulkan *pipelineManager) { + pipelineManager_ = pipelineManager; + } + void SetTextureCache(TextureCacheVulkan *textureCache) { + textureCache_ = textureCache; + } + void SetFramebufferManager(FramebufferManagerVulkan *fbManager) { + framebufferManager_ = fbManager; + } + + void Resized(); // TODO: Call + + void SetupVertexDecoder(u32 vertType); + void SetupVertexDecoderInternal(u32 vertType); + + // This requires a SetupVertexDecoder call first. + int EstimatePerVertexCost() { + // TODO: This is transform cost, also account for rasterization cost somehow... although it probably + // runs in parallel with transform. + + // Also, this is all pure guesswork. If we can find a way to do measurements, that would be great. + + // GTA wants a low value to run smooth, GoW wants a high value (otherwise it thinks things + // went too fast and starts doing all the work over again). + + int cost = 20; + if (gstate.isLightingEnabled()) { + cost += 10; + + for (int i = 0; i < 4; i++) { + if (gstate.isLightChanEnabled(i)) + cost += 10; + } + } + + if (gstate.getUVGenMode() != GE_TEXMAP_TEXTURE_COORDS) { + cost += 20; + } + if (dec_ && dec_->morphcount > 1) { + cost += 5 * dec_->morphcount; + } + + return cost; + } + + // So that this can be inlined + void Flush(VkCommandBuffer cmd) { + if (!numDrawCalls) + return; + DoFlush(cmd); + } + + bool IsCodePtrVertexDecoder(const u8 *ptr) const; + + void DispatchFlush() override { Flush(cmd_); } + void DispatchSubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead) override { + SubmitPrim(verts, inds, prim, vertexCount, vertType, bytesRead); + } + + void SetCmdBuffer(VkCommandBuffer cmd) { + cmd_ = cmd; + } + + VkPipelineLayout GetPipelineLayout() const { + return pipelineLayout_; + } + + void BeginFrame(); + void EndFrame(); + + void DirtyAllUBOs(); + +private: + void DecodeVerts(VulkanPushBuffer *push, uint32_t *bindOffset, VkBuffer *vkbuf); + void DoFlush(VkCommandBuffer cmd); + + VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone); + + VertexDecoder *GetVertexDecoder(u32 vtype); + + VulkanContext *vulkan_; + + // We use a single descriptor set layout for all PSP draws. + VkDescriptorSetLayout descriptorSetLayout_; + VkPipelineLayout pipelineLayout_; + + struct DescriptorSetKey { + VkImageView imageView_; + VkImageView secondaryImageView_; + VkSampler sampler_; + VkBuffer base_, light_, bone_; // All three UBO slots will be set to this. This will usually be identical + // for all draws in a frame, except when the buffer has to grow. + + bool operator < (const DescriptorSetKey &other) const { + if (imageView_ < other.imageView_) return true; else if (imageView_ > other.imageView_) return false; + if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; + if (secondaryImageView_ < other.secondaryImageView_) return true; else if (secondaryImageView_ > other.secondaryImageView_) return false; + if (base_ < other.base_) return true; else if (base_ > other.base_) return false; + if (light_ < other.light_) return true; else if (light_ > other.light_) return false; + if (bone_ < other.bone_) return true; else if (bone_ > other.bone_) return false; + return false; + } + }; + + // We alternate between these. + struct FrameData { + VkDescriptorPool descPool; + VulkanPushBuffer *pushUBO; + VulkanPushBuffer *pushVertex; + VulkanPushBuffer *pushIndex; + // We do rolling allocation and reset instead of caching across frames. That we might do later. + std::map descSets; + }; + + int curFrame_; + FrameData frame_[2]; + + // Defer all vertex decoding to a "Flush" (except when software skinning) + struct DeferredDrawCall { + void *verts; + void *inds; + u32 vertType; + u8 indexType; + s8 prim; + u32 vertexCount; + u16 indexLowerBound; + u16 indexUpperBound; + }; + + // This is always set to the current main command buffer of the VulkanContext. + // In the future, we may support flushing mid-frame and more fine grained command buffer usage, + // but for now, let's just submit a whole frame at a time. This is not compatible with some games + // that do mid frame read-backs. + VkCommandBuffer cmd_; + + // Vertex collector state + IndexGenerator indexGen; + GEPrimitiveType prevPrim_; + + u32 lastVTypeID_; + + TransformedVertex *transformed; + TransformedVertex *transformedExpanded; + + // Other + ShaderManagerVulkan *shaderManager_; + PipelineManagerVulkan *pipelineManager_; + TextureCacheVulkan *textureCache_; + FramebufferManagerVulkan *framebufferManager_; + + VkSampler depalSampler_; + + enum { MAX_DEFERRED_DRAW_CALLS = 128 }; + + uint32_t dirtyUniforms_; + uint32_t baseUBOOffset; + uint32_t lightUBOOffset; + uint32_t boneUBOOffset; + VkBuffer baseBuf, lightBuf, boneBuf; + + DeferredDrawCall drawCalls[MAX_DEFERRED_DRAW_CALLS]; + int numDrawCalls; + int vertexCountInDrawCalls; + + bool fboTexNeedBind_; + bool fboTexBound_; +}; diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp new file mode 100644 index 0000000000..05d479e6c8 --- /dev/null +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -0,0 +1,478 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#if !defined(USING_GLES2) +// SDL 1.2 on Apple does not have support for OpenGL 3 and hence needs +// special treatment in the shader generator. +#if defined(__APPLE__) +#define FORCE_OPENGL_2_0 +#endif +#endif + +#include +#include + +#include "Common/StringUtils.h" +#include "base/logging.h" +#include "gfx_es2/gpu_features.h" +#include "Core/Reporting.h" +#include "Core/Config.h" +#include "GPU/Common/GPUStateUtils.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" + +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" + +static const char *vulkan_glsl_preamble = + "#version 400\n" + "#extension GL_ARB_separate_shader_objects : enable\n" + "#extension GL_ARB_shading_language_420pack : enable\n\n"; + +#define WRITE p+=sprintf + +// Missing: Z depth range +bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { + char *p = buffer; + + const char *lastFragData = nullptr; + + WRITE(p, "%s", vulkan_glsl_preamble); + + bool lmode = id.Bit(FS_BIT_LMODE); + bool doTexture = id.Bit(FS_BIT_DO_TEXTURE); + bool enableFog = id.Bit(FS_BIT_ENABLE_FOG); + bool enableAlphaTest = id.Bit(FS_BIT_ALPHA_TEST); + + bool alphaTestAgainstZero = id.Bit(FS_BIT_ALPHA_AGAINST_ZERO); + bool enableColorTest = id.Bit(FS_BIT_COLOR_TEST); + bool colorTestAgainstZero = id.Bit(FS_BIT_COLOR_AGAINST_ZERO); + bool enableColorDoubling = id.Bit(FS_BIT_COLOR_DOUBLE); + bool doTextureProjection = id.Bit(FS_BIT_DO_TEXTURE_PROJ); + bool doTextureAlpha = id.Bit(FS_BIT_TEXALPHA); + bool doFlatShading = id.Bit(FS_BIT_FLATSHADE); + + GEComparison alphaTestFunc = (GEComparison)id.Bits(FS_BIT_ALPHA_TEST_FUNC, 3); + GEComparison colorTestFunc = (GEComparison)id.Bits(FS_BIT_COLOR_TEST_FUNC, 2); + bool needShaderTexClamp = id.Bit(FS_BIT_SHADER_TEX_CLAMP); + + GETexFunc texFunc = (GETexFunc)id.Bits(FS_BIT_TEXFUNC, 3); + bool textureAtOffset = id.Bit(FS_BIT_TEXTURE_AT_OFFSET); + + ReplaceBlendType replaceBlend = static_cast(id.Bits(FS_BIT_REPLACE_BLEND, 3)); + ReplaceAlphaType stencilToAlpha = static_cast(id.Bits(FS_BIT_STENCIL_TO_ALPHA, 2)); + + GEBlendSrcFactor replaceBlendFuncA = (GEBlendSrcFactor)id.Bits(FS_BIT_BLENDFUNC_A, 4); + GEBlendDstFactor replaceBlendFuncB = (GEBlendDstFactor)id.Bits(FS_BIT_BLENDFUNC_B, 4); + GEBlendMode replaceBlendEq = (GEBlendMode)id.Bits(FS_BIT_BLENDEQ, 3); + StencilValueType replaceAlphaWithStencilType = (StencilValueType)id.Bits(FS_BIT_REPLACE_ALPHA_WITH_STENCIL_TYPE, 4); + + bool isModeClear = id.Bit(FS_BIT_CLEARMODE); + + const char *shading = doFlatShading ? "flat" : ""; + + WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseUBO {\n%s} base;\n", ub_baseStr); + if (doTexture) { + WRITE(p, "layout (binding = 0) uniform sampler2D tex;\n"); + } + + if (!isModeClear && replaceBlend > REPLACE_BLEND_STANDARD) { + if (replaceBlend == REPLACE_BLEND_COPY_FBO) { + WRITE(p, "layout (binding = 1) uniform sampler2D fbotex;\n"); + } + } + + WRITE(p, "layout (location = 1) %s in vec4 v_color0;\n", shading); + if (lmode) + WRITE(p, "layout (location = 2) %s in vec3 v_color1;\n", shading); + if (enableFog) { + WRITE(p, "layout (location = 3) in float v_fogdepth;\n"); + } + if (doTexture) { + if (doTextureProjection) + WRITE(p, "layout (location = 0) in vec3 v_texcoord;\n"); + else + WRITE(p, "layout (location = 0) in vec2 v_texcoord;\n"); + } + + if (enableAlphaTest && !alphaTestAgainstZero) { + WRITE(p, "int roundAndScaleTo255i(in float x) { return int(floor(x * 255.0 + 0.5)); }\n"); + } + if (enableColorTest && !colorTestAgainstZero) { + WRITE(p, "ivec3 roundAndScaleTo255iv(in vec3 x) { return ivec3(floor(x * 255.0 + 0.5)); }\n"); + } + + WRITE(p, "layout (location = 0, index = 0) out vec4 fragColor0;\n"); + if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) { + WRITE(p, "layout (location = 0, index = 1) out vec4 fragColor1;\n"); + } + + // PowerVR needs a custom modulo function. For some reason, this has far higher precision than the builtin one. + if ((gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) && needShaderTexClamp) { + WRITE(p, "float mymod(float a, float b) { return a - b * floor(a / b); }\n"); + } + + WRITE(p, "void main() {\n"); + if (isModeClear) { + // Clear mode does not allow any fancy shading. + WRITE(p, " vec4 v = v_color0;\n"); + } else { + const char *secondary = ""; + // Secondary color for specular on top of texture + if (lmode) { + WRITE(p, " vec4 s = vec4(v_color1, 0.0);\n"); + secondary = " + s"; + } else { + secondary = ""; + } + + if (doTexture) { + const char *texcoord = "v_texcoord"; + // TODO: Not sure the right way to do this for projection. + // This path destroys resolution on older PowerVR no matter what I do, so we disable it on SGX 540 and lesser, and live with the consequences. + if (needShaderTexClamp && !(gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_TERRIBLE)) { + // We may be clamping inside a larger surface (tex = 64x64, buffer=480x272). + // We may also be wrapping in such a surface, or either one in a too-small surface. + // Obviously, clamping to a smaller surface won't work. But better to clamp to something. + std::string ucoord = "v_texcoord.x"; + std::string vcoord = "v_texcoord.y"; + if (doTextureProjection) { + ucoord = "(v_texcoord.x / v_texcoord.z)"; + vcoord = "(v_texcoord.y / v_texcoord.z)"; + } + + std::string modulo = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? "mymod" : "mod"; + + if (id.Bit(FS_BIT_CLAMP_S)) { + ucoord = "clamp(" + ucoord + ", base.texclamp.z, base.texclamp.x - base.texclamp.z)"; + } else { + ucoord = modulo + "(" + ucoord + ", base.texclamp.x)"; + } + if (id.Bit(FS_BIT_CLAMP_T)) { + vcoord = "clamp(" + vcoord + ", base.texclamp.w, base.texclamp.y - base.texclamp.w)"; + } else { + vcoord = modulo + "(" + vcoord + ", base.texclamp.y)"; + } + if (textureAtOffset) { + ucoord = "(" + ucoord + " + base.texclampoff.x)"; + vcoord = "(" + vcoord + " + base.texclampoff.y)"; + } + + WRITE(p, " vec2 fixedcoord = vec2(%s, %s);\n", ucoord.c_str(), vcoord.c_str()); + texcoord = "fixedcoord"; + // We already projected it. + doTextureProjection = false; + } + + if (doTextureProjection) { + WRITE(p, " vec4 t = textureProj(tex, %s);\n", texcoord); + } else { + WRITE(p, " vec4 t = texture(tex, %s);\n", texcoord); + } + WRITE(p, " vec4 p = v_color0;\n"); + + if (doTextureAlpha) { // texfmt == RGBA + switch (texFunc) { + case GE_TEXFUNC_MODULATE: + WRITE(p, " vec4 v = p * t%s;\n", secondary); + break; + + case GE_TEXFUNC_DECAL: + WRITE(p, " vec4 v = vec4(mix(p.rgb, t.rgb, t.a), p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_BLEND: + WRITE(p, " vec4 v = vec4(mix(p.rgb, base.texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_REPLACE: + WRITE(p, " vec4 v = t%s;\n", secondary); + break; + + case GE_TEXFUNC_ADD: + case GE_TEXFUNC_UNKNOWN1: + case GE_TEXFUNC_UNKNOWN2: + case GE_TEXFUNC_UNKNOWN3: + WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a * t.a)%s;\n", secondary); + break; + default: + WRITE(p, " vec4 v = p;\n"); break; + } + } else { // texfmt == RGB + switch (texFunc) { + case GE_TEXFUNC_MODULATE: + WRITE(p, " vec4 v = vec4(t.rgb * p.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_DECAL: + WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_BLEND: + WRITE(p, " vec4 v = vec4(mix(p.rgb, base.texenv.rgb, t.rgb), p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_REPLACE: + WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_ADD: + case GE_TEXFUNC_UNKNOWN1: + case GE_TEXFUNC_UNKNOWN2: + case GE_TEXFUNC_UNKNOWN3: + WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a)%s;\n", secondary); break; + default: + WRITE(p, " vec4 v = p;\n"); break; + } + } + } else { + // No texture mapping + WRITE(p, " vec4 v = v_color0 %s;\n", secondary); + } + + // Texture access is at half texels [0.5/256, 255.5/256], but colors are normalized [0, 255]. + // So we have to scale to account for the difference. + std::string alphaTestXCoord = "0"; + + if (enableAlphaTest) { + if (alphaTestAgainstZero) { + // When testing against 0 (extremely common), we can avoid some math. + // 0.002 is approximately half of 1.0 / 255.0. + if (alphaTestFunc == GE_COMP_NOTEQUAL || alphaTestFunc == GE_COMP_GREATER) { + WRITE(p, " if (v.a < 0.002) discard;\n"); + } else if (alphaTestFunc != GE_COMP_NEVER) { + // Anything else is a test for == 0. Happens sometimes, actually... + WRITE(p, " if (v.a > 0.002) discard;\n"); + } else { + // NEVER has been logged as used by games, although it makes little sense - statically failing. + // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. + WRITE(p, " discard;\n"); + } + } else { + const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; + if (alphaTestFuncs[alphaTestFunc][0] != '#') { + WRITE(p, " if ((roundAndScaleTo255i(v.a) & base.alphacolormask.a) %s base.alphacolorref.a) discard;\n", alphaTestFuncs[alphaTestFunc]); + } else { + // This means NEVER. See above. + WRITE(p, " discard;\n"); + } + } + } + + if (enableColorTest) { + if (colorTestAgainstZero) { + // When testing against 0 (common), we can avoid some math. + // 0.002 is approximately half of 1.0 / 255.0. + if (colorTestFunc == GE_COMP_NOTEQUAL) { + WRITE(p, " if (v.r < 0.002 && v.g < 0.002 && v.b < 0.002) discard;\n"); + } else if (colorTestFunc != GE_COMP_NEVER) { + // Anything else is a test for == 0. + WRITE(p, " if (v.r > 0.002 || v.g > 0.002 || v.b > 0.002) discard;\n"); + } else { + // NEVER has been logged as used by games, although it makes little sense - statically failing. + // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. + WRITE(p, " discard;\n"); + } + } else { + const char *colorTestFuncs[] = { "#", "#", " != ", " == " }; + if (colorTestFuncs[colorTestFunc][0] != '#') { + WRITE(p, " ivec3 v_scaled = roundAndScaleTo255iv(v.rgb);\n"); + WRITE(p, " if ((v_scaled & base.alphacolormask.rgb) %s (base.alphacolorref.rgb & base.alphacolormask.rgb)) discard;\n", colorTestFuncs[colorTestFunc]); + } else { + WRITE(p, " discard;\n"); + } + } + } + + // Color doubling happens after the color test. + if (enableColorDoubling && replaceBlend == REPLACE_BLEND_2X_SRC) { + WRITE(p, " v.rgb = v.rgb * 4.0;\n"); + } else if (enableColorDoubling || replaceBlend == REPLACE_BLEND_2X_SRC) { + WRITE(p, " v.rgb = v.rgb * 2.0;\n"); + } + + if (enableFog) { + WRITE(p, " float fogCoef = clamp(v_fogdepth, 0.0, 1.0);\n"); + WRITE(p, " v = mix(vec4(base.fogcolor, v.a), v, fogCoef);\n"); + // WRITE(p, " v.x = v_depth;\n"); + } + + if (replaceBlend == REPLACE_BLEND_PRE_SRC || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA) { + const char *srcFactor = "ERROR"; + switch (replaceBlendFuncA) { + case GE_SRCBLEND_DSTCOLOR: srcFactor = "ERROR"; break; + case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "ERROR"; break; + case GE_SRCBLEND_SRCALPHA: srcFactor = "vec3(v.a)"; break; + case GE_SRCBLEND_INVSRCALPHA: srcFactor = "vec3(1.0 - v.a)"; break; + case GE_SRCBLEND_DSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_INVDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "vec3(v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_FIXA: srcFactor = "base.blendFixA"; break; + } + + WRITE(p, " v.rgb = v.rgb * %s;\n", srcFactor); + } + + if (replaceBlend == REPLACE_BLEND_COPY_FBO) { + WRITE(p, " lowp vec4 destColor = texelFetch(fbotex, ivec2(gl_FragCoord.x, gl_FragCoord.y), 0);\n"); + + const char *srcFactor = "vec3(1.0)"; + const char *dstFactor = "vec3(0.0)"; + + switch (replaceBlendFuncA) { + case GE_SRCBLEND_DSTCOLOR: srcFactor = "destColor.rgb"; break; + case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "(vec3(1.0) - destColor.rgb)"; break; + case GE_SRCBLEND_SRCALPHA: srcFactor = "vec3(v.a)"; break; + case GE_SRCBLEND_INVSRCALPHA: srcFactor = "vec3(1.0 - v.a)"; break; + case GE_SRCBLEND_DSTALPHA: srcFactor = "vec3(destColor.a)"; break; + case GE_SRCBLEND_INVDSTALPHA: srcFactor = "vec3(1.0 - destColor.a)"; break; + case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "vec3(v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "vec3(destColor.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "vec3(1.0 - destColor.a * 2.0)"; break; + case GE_SRCBLEND_FIXA: srcFactor = "base.blendFixA"; break; + } + switch (replaceBlendFuncB) { + case GE_DSTBLEND_SRCCOLOR: dstFactor = "v.rgb"; break; + case GE_DSTBLEND_INVSRCCOLOR: dstFactor = "(vec3(1.0) - v.rgb)"; break; + case GE_DSTBLEND_SRCALPHA: dstFactor = "vec3(v.a)"; break; + case GE_DSTBLEND_INVSRCALPHA: dstFactor = "vec3(1.0 - v.a)"; break; + case GE_DSTBLEND_DSTALPHA: dstFactor = "vec3(destColor.a)"; break; + case GE_DSTBLEND_INVDSTALPHA: dstFactor = "vec3(1.0 - destColor.a)"; break; + case GE_DSTBLEND_DOUBLESRCALPHA: dstFactor = "vec3(v.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEINVSRCALPHA: dstFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEDSTALPHA: dstFactor = "vec3(destColor.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEINVDSTALPHA: dstFactor = "vec3(1.0 - destColor.a * 2.0)"; break; + case GE_DSTBLEND_FIXB: dstFactor = "base.blendFixB"; break; + } + + switch (replaceBlendEq) { + case GE_BLENDMODE_MUL_AND_ADD: + WRITE(p, " v.rgb = v.rgb * %s + destColor.rgb * %s;\n", srcFactor, dstFactor); + break; + case GE_BLENDMODE_MUL_AND_SUBTRACT: + WRITE(p, " v.rgb = v.rgb * %s - destColor.rgb * %s;\n", srcFactor, dstFactor); + break; + case GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE: + WRITE(p, " v.rgb = destColor.rgb * %s - v.rgb * %s;\n", dstFactor, srcFactor); + break; + case GE_BLENDMODE_MIN: + WRITE(p, " v.rgb = min(v.rgb, destColor.rgb);\n"); + break; + case GE_BLENDMODE_MAX: + WRITE(p, " v.rgb = max(v.rgb, destColor.rgb);\n"); + break; + case GE_BLENDMODE_ABSDIFF: + WRITE(p, " v.rgb = abs(v.rgb - destColor.rgb);\n"); + break; + } + } + + if (replaceBlend == REPLACE_BLEND_2X_ALPHA || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA) { + WRITE(p, " v.a = v.a * 2.0;\n"); + } + } + + std::string replacedAlpha = "0.0"; + char replacedAlphaTemp[64] = ""; + if (stencilToAlpha != REPLACE_ALPHA_NO) { + switch (replaceAlphaWithStencilType) { + case STENCIL_VALUE_UNIFORM: + replacedAlpha = "base.fogcoef_stencilreplace.z"; + break; + + case STENCIL_VALUE_ZERO: + replacedAlpha = "0.0"; + break; + + case STENCIL_VALUE_ONE: + case STENCIL_VALUE_INVERT: + // In invert, we subtract by one, but we want to output one here. + replacedAlpha = "1.0"; + break; + + case STENCIL_VALUE_INCR_4: + case STENCIL_VALUE_DECR_4: + // We're adding/subtracting, just by the smallest value in 4-bit. + snprintf(replacedAlphaTemp, sizeof(replacedAlphaTemp), "%f", 1.0 / 15.0); + replacedAlpha = replacedAlphaTemp; + break; + + case STENCIL_VALUE_INCR_8: + case STENCIL_VALUE_DECR_8: + // We're adding/subtracting, just by the smallest value in 8-bit. + snprintf(replacedAlphaTemp, sizeof(replacedAlphaTemp), "%f", 1.0 / 255.0); + replacedAlpha = replacedAlphaTemp; + break; + + case STENCIL_VALUE_KEEP: + // Do nothing. We'll mask out the alpha using color mask. + break; + } + } + + switch (stencilToAlpha) { + case REPLACE_ALPHA_DUALSOURCE: + WRITE(p, " fragColor0 = vec4(v.rgb, %s);\n", replacedAlpha.c_str()); + WRITE(p, " fragColor1 = vec4(0.0, 0.0, 0.0, v.a);\n"); + break; + + case REPLACE_ALPHA_YES: + WRITE(p, " fragColor0 = vec4(v.rgb, %s);\n", replacedAlpha.c_str()); + break; + + case REPLACE_ALPHA_NO: + WRITE(p, " fragColor0 = v;\n"); + break; + + default: + ERROR_LOG(G3D, "Bad stencil-to-alpha type, corrupt ID?"); + return false; + } + + LogicOpReplaceType replaceLogicOpType = (LogicOpReplaceType)id.Bits(FS_BIT_REPLACE_LOGIC_OP_TYPE, 2); + switch (replaceLogicOpType) { + case LOGICOPTYPE_ONE: + WRITE(p, " fragColor0.rgb = vec3(1.0, 1.0, 1.0);\n"); + break; + case LOGICOPTYPE_INVERT: + WRITE(p, " fragColor0.rgb = vec3(1.0, 1.0, 1.0) - fragColor0.rgb;\n"); + break; + case LOGICOPTYPE_NORMAL: + break; + + default: + ERROR_LOG(G3D, "Bad logic op type, corrupt ID?"); + return false; + } + + if (gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { + WRITE(p, " highp float z = gl_FragCoord.z;\n"); + WRITE(p, " z = (1.0/65535.0) * floor(z * 65535.0);\n"); + WRITE(p, " gl_FragDepth = z;\n"); + } + + WRITE(p, "}\n"); + + return true; +} \ No newline at end of file diff --git a/headless/WindowsHeadlessHostDx9.h b/GPU/Vulkan/FragmentShaderGeneratorVulkan.h similarity index 62% rename from headless/WindowsHeadlessHostDx9.h rename to GPU/Vulkan/FragmentShaderGeneratorVulkan.h index 29966ec756..666daea965 100644 --- a/headless/WindowsHeadlessHostDx9.h +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.h @@ -1,3 +1,4 @@ +#pragma once // Copyright (c) 2012- PPSSPP Project. // This program is free software: you can redistribute it and/or modify @@ -17,23 +18,8 @@ #pragma once -#include "StubHost.h" -#include "WindowsHeadlessHost.h" +#include "Globals.h" -#undef HEADLESSHOST_CLASS -#define HEADLESSHOST_CLASS WindowsHeadlessHost +struct ShaderID; -#include "Common/CommonWindows.h" - -// TODO: Get rid of this junk -class WindowsHeadlessHostDx9 : public WindowsHeadlessHost -{ -public: - bool InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) override; - void ShutdownGraphics() override; - - void SwapBuffers() override; - -private: - bool ResizeGL() override; -}; \ No newline at end of file +bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer); diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp new file mode 100644 index 0000000000..74c1c94ec0 --- /dev/null +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -0,0 +1,1945 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include + +#include "profiler/profiler.h" + +#include "base/timeutil.h" +#include "math/lin/matrix4x4.h" + +#include "Common/Vulkan/VulkanContext.h" +#include "Common/ColorConv.h" +#include "Core/Host.h" +#include "Core/MemMap.h" +#include "Core/Config.h" +#include "Core/System.h" +#include "Core/Reporting.h" +#include "Core/HLE/sceDisplay.h" +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" + +#include "GPU/Common/PostShader.h" +#include "GPU/Common/TextureDecoder.h" +#include "GPU/Common/FramebufferCommon.h" +#include "GPU/Debugger/Stepping.h" + +#include "GPU/GPUInterface.h" +#include "GPU/GPUState.h" +#include "Common/Vulkan/VulkanImage.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/VulkanUtil.h" + +#include "UI/OnScreenDisplay.h" + +extern int g_iNumVideos; + + +static const char tex_fs[] = +"layout (binding = 0) uniform sampler2D sampler0;\n" +"layout (location = 0) in vec2 v_texcoord0;\n" +"void main() {\n" +" gl_FragColor = texture2D(sampler0, v_texcoord0);\n" +"}\n"; + +static const char basic_vs[] = +"layout (location = 0) in vec4 a_position;\n" +"layout (location = 1) in attribute vec2 a_texcoord0;\n" +"layout (location = 0) out vec2 v_texcoord0;\n" +"void main() {\n" +" v_texcoord0 = a_texcoord0;\n" +" gl_Position = a_position;\n" +"}\n"; + +void ConvertFromRGBA8888_Vulkan(u8 *dst, const u8 *src, u32 dstStride, u32 srcStride, u32 width, u32 height, GEBufferFormat format); + +void FramebufferManagerVulkan::ClearBuffer(bool keepState) { + // keepState is irrelevant. + if (!currentRenderVfb_) { + return; + } + VkClearAttachment clear[2]; + memset(clear, 0, sizeof(clear)); + clear[0].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + clear[1].aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + VkClearRect rc; + rc.baseArrayLayer = 0; + rc.layerCount = 1; + rc.rect.offset.x = 0; + rc.rect.offset.y = 0; + rc.rect.extent.width = currentRenderVfb_->bufferWidth; + rc.rect.extent.height = currentRenderVfb_->bufferHeight; + vkCmdClearAttachments(curCmd_, 2, clear, 1, &rc); +} + +void FramebufferManagerVulkan::DisableState() { +} + +void FramebufferManagerVulkan::SetNumExtraFBOs(int num) { + /* + for (size_t i = 0; i < extraFBOs_.size(); i++) { + fbo_destroy(extraFBOs_[i]); + } + extraFBOs_.clear(); + for (int i = 0; i < num; i++) { + // No depth/stencil for post processing + FBO *fbo_vk = fbo_create(renderWidth_, renderHeight_, 1, false, FBO_8888); + extraFBOs_.push_back(fbo_vk); + + // The new FBO is still bound after creation, but let's bind it anyway. + fbo_bind_as_render_target(fbo_vk); + ClearBuffer(); + } + + currentRenderVfb_ = 0; + fbo_unbind(); + */ +} + +void FramebufferManagerVulkan::CompileDraw2DProgram() { + /* + if (!draw2dprogram_) { + std::string errorString; + draw2dprogram_ = glsl_create_source(basic_vs, tex_fs, &errorString); + if (!draw2dprogram_) { + ERROR_LOG_REPORT(G3D, "Failed to compile draw2dprogram! This shouldn't happen.\n%s", errorString.c_str()); + } else { + glsl_bind(draw2dprogram_); + glUniform1i(draw2dprogram_->sampler0, 0); + } + + plainColorProgram_ = glsl_create_source(color_vs, color_fs, &errorString); + if (!plainColorProgram_) { + ERROR_LOG_REPORT(G3D, "Failed to compile plainColorProgram! This shouldn't happen.\n%s", errorString.c_str()); + } else { + glsl_bind(plainColorProgram_); + plainColorLoc_ = glsl_uniform_loc(plainColorProgram_, "u_color"); + } + + SetNumExtraFBOs(0); + const ShaderInfo *shaderInfo = 0; + if (g_Config.sPostShaderName != "Off") { + shaderInfo = GetPostShaderInfo(g_Config.sPostShaderName); + } + + if (shaderInfo) { + postShaderAtOutputResolution_ = shaderInfo->outputResolution; + postShaderProgram_ = glsl_create(shaderInfo->vertexShaderFile.c_str(), shaderInfo->fragmentShaderFile.c_str(), &errorString); + if (!postShaderProgram_) { + // DO NOT turn this into a report, as it will pollute our logs with all kinds of + // user shader experiments. + ERROR_LOG(G3D, "Failed to build post-processing program from %s and %s!\n%s", shaderInfo->vertexShaderFile.c_str(), shaderInfo->fragmentShaderFile.c_str(), errorString.c_str()); + // let's show the first line of the error string as an OSM. + std::set blacklistedLines; + // These aren't useful to show, skip to the first interesting line. + blacklistedLines.insert("Fragment shader failed to compile with the following errors:"); + blacklistedLines.insert("Vertex shader failed to compile with the following errors:"); + blacklistedLines.insert("Compile failed."); + blacklistedLines.insert(""); + + std::string firstLine; + size_t start = 0; + for (size_t i = 0; i < errorString.size(); i++) { + if (errorString[i] == '\n') { + firstLine = errorString.substr(start, i - start); + if (blacklistedLines.find(firstLine) == blacklistedLines.end()) { + break; + } + start = i + 1; + firstLine.clear(); + } + } + if (!firstLine.empty()) { + osm.Show("Post-shader error: " + firstLine + "...", 10.0f, 0xFF3090FF); + } else { + osm.Show("Post-shader error, see log for details", 10.0f, 0xFF3090FF); + } + usePostShader_ = false; + } else { + glsl_bind(postShaderProgram_); + glUniform1i(postShaderProgram_->sampler0, 0); + SetNumExtraFBOs(1); + deltaLoc_ = glsl_uniform_loc(postShaderProgram_, "u_texelDelta"); + pixelDeltaLoc_ = glsl_uniform_loc(postShaderProgram_, "u_pixelDelta"); + timeLoc_ = glsl_uniform_loc(postShaderProgram_, "u_time"); + usePostShader_ = true; + } + } else { + postShaderProgram_ = nullptr; + usePostShader_ = false; + } + + glsl_unbind(); + } + */ +} + +void FramebufferManagerVulkan::UpdatePostShaderUniforms(int bufferWidth, int bufferHeight, int renderWidth, int renderHeight) { + float u_delta = 1.0f / renderWidth; + float v_delta = 1.0f / renderHeight; + float u_pixel_delta = u_delta; + float v_pixel_delta = v_delta; + if (postShaderAtOutputResolution_) { + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, ROTATION_LOCKED_HORIZONTAL); + u_pixel_delta = (1.0f / w) * (480.0f / bufferWidth); + v_pixel_delta = (1.0f / h) * (272.0f / bufferHeight); + } + + postUniforms_.texelDelta[0] = u_delta; + postUniforms_.texelDelta[1] = v_delta; + postUniforms_.pixelDelta[0] = u_pixel_delta; + postUniforms_.pixelDelta[1] = v_pixel_delta; + int flipCount = __DisplayGetFlipCount(); + int vCount = __DisplayGetVCount(); + float time[4] = { time_now(), (vCount % 60) * 1.0f / 60.0f, (float)vCount, (float)(flipCount % 60) }; + memcpy(postUniforms_.time, time, 4 * sizeof(float)); +} + +void FramebufferManagerVulkan::DestroyDraw2DProgram() { + /* + if (draw2dprogram_) { + glsl_destroy(draw2dprogram_); + draw2dprogram_ = nullptr; + } + if (postShaderProgram_) { + glsl_destroy(postShaderProgram_); + postShaderProgram_ = nullptr; + } + */ +} + +FramebufferManagerVulkan::FramebufferManagerVulkan(VulkanContext *vulkan) : + vulkan_(vulkan), + drawPixelsTex_(0), + drawPixelsTexFormat_(GE_FORMAT_INVALID), + convBuf_(nullptr), + textureCache_(nullptr), + shaderManager_(nullptr), + resized_(false), + pixelBufObj_(nullptr), + currentPBO_(0) { +} + +FramebufferManagerVulkan::~FramebufferManagerVulkan() { + /* + if (drawPixelsTex_) + glDeleteTextures(1, &drawPixelsTex_); + DestroyDraw2DProgram(); + if (stencilUploadProgram_) { + glsl_destroy(stencilUploadProgram_); + } + SetNumExtraFBOs(0); + + for (auto it = tempFBOs_.begin(), end = tempFBOs_.end(); it != end; ++it) { + fbo_destroy(it->second.fbo_vk); + } + + delete[] pixelBufObj_; + delete[] convBuf_; + */ +} + +void FramebufferManagerVulkan::Init() { + FramebufferManagerCommon::Init(); + // Workaround for upscaling shaders where we force x1 resolution without saving it + resized_ = true; + CompileDraw2DProgram(); +} + +void FramebufferManagerVulkan::MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) { + /* + if (drawPixelsTex_ && (drawPixelsTexFormat_ != srcPixelFormat || drawPixelsTexW_ != width || drawPixelsTexH_ != height)) { + glDeleteTextures(1, &drawPixelsTex_); + drawPixelsTex_ = 0; + } + + if (!drawPixelsTex_) { + drawPixelsTex_ = textureCache_->AllocTextureName(); + drawPixelsTexW_ = width; + drawPixelsTexH_ = height; + + // Initialize backbuffer texture for DrawPixels + glBindTexture(GL_TEXTURE_2D, drawPixelsTex_); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + drawPixelsTexFormat_ = srcPixelFormat; + } else { + glBindTexture(GL_TEXTURE_2D, drawPixelsTex_); + } + + // TODO: We can just change the texture format and flip some bits around instead of this. + // Could share code with the texture cache perhaps. + bool useConvBuf = false; + if (srcPixelFormat != GE_FORMAT_8888 || srcStride != width) { + useConvBuf = true; + u32 neededSize = width * height * 4; + if (!convBuf_ || convBufSize_ < neededSize) { + delete[] convBuf_; + convBuf_ = new u8[neededSize]; + convBufSize_ = neededSize; + } + for (int y = 0; y < height; y++) { + switch (srcPixelFormat) { + case GE_FORMAT_565: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA565ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_5551: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA5551ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_4444: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA4444ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_8888: + { + const u8 *src = srcPixels + srcStride * 4 * y; + u8 *dst = convBuf_ + 4 * width * y; + memcpy(dst, src, 4 * width); + } + break; + + case GE_FORMAT_INVALID: + _dbg_assert_msg_(G3D, false, "Invalid pixelFormat passed to DrawPixels()."); + break; + } + } + } + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, useConvBuf ? convBuf_ : srcPixels); + */ +} + +void FramebufferManagerVulkan::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) { + /* + float v0 = 0.0f, v1 = 1.0f; + if (useBufferedRendering_ && vfb && vfb->fbo_vk) { + fbo_bind_as_render_target(vfb->fbo_vk); + glViewport(0, 0, vfb->renderWidth, vfb->renderHeight); + } else { + // We are drawing to the back buffer so need to flip. + v0 = 1.0f; + v1 = 0.0f; + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, ROTATION_LOCKED_HORIZONTAL); + glViewport(x, y, w, h); + } + + MakePixelTexture(srcPixels, srcPixelFormat, srcStride, width, height); + + DrawActiveTexture(0, dstX, dstY, width, height, vfb->bufferWidth, vfb->bufferHeight, 0.0f, v0, 1.0f, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + textureCache_->ForgetLastTexture(); + */ +} + +void FramebufferManagerVulkan::DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) { + /* + MakePixelTexture(srcPixels, srcPixelFormat, srcStride, 512, 272); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, g_Config.iTexFiltering == TEX_FILTER_NEAREST ? GL_NEAREST : GL_LINEAR); + + struct CardboardSettings cardboardSettings; + GetCardboardSettings(&cardboardSettings); + + // This might draw directly at the backbuffer (if so, applyPostShader is set) so if there's a post shader, we need to apply it here. + // Should try to unify this path with the regular path somehow, but this simple solution works for most of the post shaders + // (it always runs at output resolution so FXAA may look odd). + float x, y, w, h; + int uvRotation = (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, uvRotation); + if (applyPostShader) { + // Make sure we've compiled the shader. + if (!postShaderProgram_) { + CompileDraw2DProgram(); + } + // Might've changed if the shader was just changed to Off. + if (usePostShader_) { + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(480, 272, renderWidth_, renderHeight_); + } + } + float u0 = 0.0f, u1 = 480.0f / 512.0f; + float v0 = 0.0f, v1 = 1.0f; + + // We are drawing directly to the back buffer. + std::swap(v0, v1); + + if (cardboardSettings.enabled) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, uvRotation); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + } + */ +} + +// x, y, w, h are relative coordinates against destW/destH, which is not very intuitive. +void FramebufferManagerVulkan::DrawActiveTexture(VulkanTexture *texture, float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, VkPipeline pipeline, int uvRotation) { + /* + float texCoords[8] = { + u0,v0, + u1,v0, + u1,v1, + u0,v1, + }; + + static const GLubyte indices[4] = { 0,1,3,2 }; + + if (uvRotation != ROTATION_LOCKED_HORIZONTAL) { + float temp[8]; + int rotation = 0; + switch (uvRotation) { + case ROTATION_LOCKED_HORIZONTAL180: rotation = 4; break; + case ROTATION_LOCKED_VERTICAL: rotation = 2; break; + case ROTATION_LOCKED_VERTICAL180: rotation = 6; break; + } + for (int i = 0; i < 8; i++) { + temp[i] = texCoords[(i + rotation) & 7]; + } + memcpy(texCoords, temp, sizeof(temp)); + } + + if (texture) { + // Previously had NVDrawTexture fallback here but wasn't worth it. + glBindTexture(GL_TEXTURE_2D, texture); + } + + float pos[12] = { + x,y,0, + x + w,y,0, + x + w,y + h,0, + x,y + h,0 + }; + + float invDestW = 1.0f / (destW * 0.5f); + float invDestH = 1.0f / (destH * 0.5f); + for (int i = 0; i < 4; i++) { + pos[i * 3] = pos[i * 3] * invDestW - 1.0f; + pos[i * 3 + 1] = pos[i * 3 + 1] * invDestH - 1.0f; + } + + if (!program) { + if (!draw2dprogram_) { + CompileDraw2DProgram(); + } + + program = draw2dprogram_; + } + + // Upscaling postshaders doesn't look well with linear + if (postShaderIsUpscalingFilter_) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, g_Config.iBufFilter == SCALE_NEAREST ? GL_NEAREST : GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, g_Config.iBufFilter == SCALE_NEAREST ? GL_NEAREST : GL_LINEAR); + } + + if (program != postShaderProgram_) { + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(program); + } + + glEnableVertexAttribArray(program->a_position); + glEnableVertexAttribArray(program->a_texcoord0); + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + transformDraw_->BindBuffer(pos, sizeof(pos), texCoords, sizeof(texCoords)); + transformDraw_->BindElementBuffer(indices, sizeof(indices)); + glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, 12, 0); + glVertexAttribPointer(program->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, (void *)sizeof(pos)); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, 0); + } else { + glstate.arrayBuffer.unbind(); + glstate.elementArrayBuffer.unbind(); + glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, 12, pos); + glVertexAttribPointer(program->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, texCoords); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, indices); + } + glDisableVertexAttribArray(program->a_position); + glDisableVertexAttribArray(program->a_texcoord0); + + glsl_unbind(); + */ +} + +void FramebufferManagerVulkan::DestroyFramebuf(VirtualFramebuffer *v) { + textureCache_->NotifyFramebuffer(v->fb_address, v, NOTIFY_FB_DESTROYED); + if (v->fbo_vk) { + delete v->fbo_vk; + v->fbo_vk = 0; + } + + // Wipe some pointers + if (currentRenderVfb_ == v) + currentRenderVfb_ = 0; + if (displayFramebuf_ == v) + displayFramebuf_ = 0; + if (prevDisplayFramebuf_ == v) + prevDisplayFramebuf_ = 0; + if (prevPrevDisplayFramebuf_ == v) + prevPrevDisplayFramebuf_ = 0; + + delete v; +} + +void FramebufferManagerVulkan::RebindFramebuffer() { + /* + if (currentRenderVfb_ && currentRenderVfb_->fbo_vk) { + ImagcurrentRenderVfb_->fbo_vk->GetColorImageView(); + } else { + fbo_unbind(); + } + if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) + glstate.viewport.restore(); + */ +} + +void FramebufferManagerVulkan::ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force) { + VirtualFramebuffer old = *vfb; + + if (force) { + vfb->bufferWidth = w; + vfb->bufferHeight = h; + } else { + if (vfb->bufferWidth >= w && vfb->bufferHeight >= h) { + return; + } + + // In case it gets thin and wide, don't resize down either side. + vfb->bufferWidth = std::max(vfb->bufferWidth, w); + vfb->bufferHeight = std::max(vfb->bufferHeight, h); + } + + SetRenderSize(vfb); + + bool trueColor = g_Config.bTrueColor; + if (hackForce04154000Download_ && vfb->fb_address == 0x00154000) { + trueColor = true; + } + + if (trueColor) { + vfb->colorDepth = VK_FBO_8888; + } else { + switch (vfb->format) { + case GE_FORMAT_4444: + vfb->colorDepth = VK_FBO_4444; + break; + case GE_FORMAT_5551: + vfb->colorDepth = VK_FBO_5551; + break; + case GE_FORMAT_565: + vfb->colorDepth = VK_FBO_565; + break; + case GE_FORMAT_8888: + default: + vfb->colorDepth = VK_FBO_8888; + break; + } + } + + textureCache_->ForgetLastTexture(); + + if (!useBufferedRendering_) { + if (vfb->fbo_vk) { + delete vfb->fbo_vk; + vfb->fbo_vk = 0; + } + return; + } + + vfb->fbo_vk = new VulkanFBO(); + // bo_create(vfb->renderWidth, vfb->renderHeight, 1, true, (FBOColorDepth)vfb->colorDepth); + if (old.fbo_vk) { + INFO_LOG(SCEGE, "Resizing FBO for %08x : %i x %i x %i", vfb->fb_address, w, h, vfb->format); + if (vfb->fbo_vk) { + /// fbo_bind_as_render_target(vfb->fbo_vk); + ClearBuffer(); + if (!g_Config.bDisableSlowFramebufEffects) { + BlitFramebuffer(vfb, 0, 0, &old, 0, 0, std::min(vfb->bufferWidth, vfb->width), std::min(vfb->height, vfb->bufferHeight), 0); + } + } + delete old.fbo_vk; + if (vfb->fbo_vk) { + // fbo_bind_as_render_target(vfb->fbo_vk); + } + } + + if (!vfb->fbo_vk) { + ERROR_LOG(SCEGE, "Error creating FBO! %i x %i", vfb->renderWidth, vfb->renderHeight); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) { + if (!useBufferedRendering_) { + // Let's ignore rendering to targets that have not (yet) been displayed. + gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB; + } + + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_CREATED); + + // Some AMD drivers crash if we don't clear the buffer first? + /* + glDisable(GL_DITHER); // why? + ClearBuffer(); + */ + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) { + if (ShouldDownloadFramebuffer(vfb) && !vfb->memoryUpdated) { + ReadFramebufferToMemory(vfb, true, 0, 0, vfb->width, vfb->height); + } + textureCache_->ForgetLastTexture(); + + if (useBufferedRendering_) { + if (vfb->fbo_vk) { + // vfb->fbo_vk->GetColorImageView(); + } + } else { + if (vfb->fbo_vk) { + // wtf? This should only happen very briefly when toggling bBufferedRendering + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_DESTROYED); + delete vfb->fbo_vk; + vfb->fbo_vk = nullptr; + } + + // Let's ignore rendering to targets that have not (yet) been displayed. + if (vfb->usageFlags & FB_USAGE_DISPLAYED_FRAMEBUFFER) { + gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB; + } else { + gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB; + } + } + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_UPDATED); + + // Copy depth pixel value from the read framebuffer to the draw framebuffer + if (prevVfb && !g_Config.bDisableSlowFramebufEffects) { + if (!prevVfb->fbo_vk || !vfb->fbo_vk || !useBufferedRendering_ || !prevVfb->depthUpdated || isClearingDepth) { + // If depth wasn't updated, then we're at least "two degrees" away from the data. + // This is an optimization: it probably doesn't need to be copied in this case. + } else { + BlitFramebufferDepth(prevVfb, vfb); + } + } + if (vfb->drawnFormat != vfb->format) { + // TODO: Might ultimately combine this with the resize step in DoSetRenderFrameBuffer(). + ReformatFramebufferFrom(vfb, vfb->drawnFormat); + } + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) { + if (vfbFormatChanged) { + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_UPDATED); + if (vfb->drawnFormat != vfb->format) { + ReformatFramebufferFrom(vfb, vfb->drawnFormat); + } + } + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +bool FramebufferManagerVulkan::NotifyStencilUpload(u32 addr, int size, bool skipZero) { + // In Vulkan we should be able to simply copy the stencil data directly to a stencil buffer without + // messing about with bitplane textures and the like. + return false; +} + + +int FramebufferManagerVulkan::GetLineWidth() { + if (g_Config.iInternalResolution == 0) { + return std::max(1, (int)(renderWidth_ / 480)); + } else { + return g_Config.iInternalResolution; + } +} + +void FramebufferManagerVulkan::ReformatFramebufferFrom(VirtualFramebuffer *vfb, GEBufferFormat old) { + if (!useBufferedRendering_ || !vfb->fbo_vk) { + return; + } + /* + fbo_bind_as_render_target(vfb->fbo); + + // Technically, we should at this point re-interpret the bytes of the old format to the new. + // That might get tricky, and could cause unnecessary slowness in some games. + // For now, we just clear alpha/stencil from 565, which fixes shadow issues in Kingdom Hearts. + // (it uses 565 to write zeros to the buffer, than 4444 to actually render the shadow.) + // + // The best way to do this may ultimately be to create a new FBO (combine with any resize?) + // and blit with a shader to that, then replace the FBO on vfb. Stencil would still be complex + // to exactly reproduce in 4444 and 8888 formats. + + if (old == GE_FORMAT_565) { + glstate.scissorTest.disable(); + glstate.depthWrite.set(GL_FALSE); + glstate.colorMask.set(false, false, false, true); + glstate.stencilFunc.set(GL_ALWAYS, 0, 0); + glstate.stencilMask.set(0xFF); + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClearStencil(0); + glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + } + + RebindFramebuffer(); + */ +} + +void FramebufferManagerVulkan::BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst) { + /* + if (src->z_address == dst->z_address && + src->z_stride != 0 && dst->z_stride != 0 && + src->renderWidth == dst->renderWidth && + src->renderHeight == dst->renderHeight) { + + if (gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT | GPU_SUPPORTS_NV_FRAMEBUFFER_BLIT)) { + // Only use NV if ARB isn't supported. + bool useNV = !gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT); + + // Let's only do this if not clearing depth. + fbo_bind_for_read(src->fbo); + glstate.scissorTest.force(false); + + if (useNV) { +#if defined(USING_GLES2) && defined(ANDROID) // We only support this extension on Android, it's not even available on PC. + glBlitFramebufferNV(0, 0, src->renderWidth, src->renderHeight, 0, 0, dst->renderWidth, dst->renderHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); +#endif // defined(USING_GLES2) && defined(ANDROID) + } else { + glBlitFramebuffer(0, 0, src->renderWidth, src->renderHeight, 0, 0, dst->renderWidth, dst->renderHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + // If we set dst->depthUpdated here, our optimization above would be pointless. + + glstate.scissorTest.restore(); + } + }*/ +} + +VulkanFBO *FramebufferManagerVulkan::GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth) { + u64 key = ((u64)depth << 32) | ((u32)w << 16) | h; + auto it = tempFBOs_.find(key); + if (it != tempFBOs_.end()) { + it->second.last_frame_used = gpuStats.numFlips; + return it->second.fbo_vk; + } + + textureCache_->ForgetLastTexture(); + // FBO *fbo_vk = fbo_create(w, h, 1, false, depth); + VulkanFBO *fbo_vk = new VulkanFBO(); + if (!fbo_vk) + return nullptr; + // fbo_bind_as_render_target(fbo_vk); + // fbo_vk->GetColorImageView() + // ClearBuffer(true); + const TempFBO info = { fbo_vk, gpuStats.numFlips }; + tempFBOs_[key] = info; + return fbo_vk; +} + +void FramebufferManagerVulkan::BindFramebufferColor(int stage, u32 fbRawAddress, VirtualFramebuffer *framebuffer, int flags) { + if (framebuffer == NULL) { + framebuffer = currentRenderVfb_; + } + + /* + if (stage != GL_TEXTURE0) { + glActiveTexture(stage); + } + + if (!framebuffer->fbo_vk || !useBufferedRendering_) { + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE0); + gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE; + return; + } + + // currentRenderVfb_ will always be set when this is called, except from the GE debugger. + // Let's just not bother with the copy in that case. + bool skipCopy = (flags & BINDFBCOLOR_MAY_COPY) == 0; + if (GPUStepping::IsStepping() || g_Config.bDisableSlowFramebufEffects) { + skipCopy = true; + } + if (!skipCopy && currentRenderVfb_ && framebuffer->fb_address == fbRawAddress) { + // TODO: Maybe merge with bvfbs_? Not sure if those could be packing, and they're created at a different size. + fbo_vk *renderCopy = GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, (FBOColorDepth)framebuffer->colorDepth); + if (renderCopy) { + VirtualFramebuffer copyInfo = *framebuffer; + copyInfo.fbo_vk = renderCopy; + + int x = 0; + int y = 0; + int w = framebuffer->drawnWidth; + int h = framebuffer->drawnHeight; + + // If max is not > min, we probably could not detect it. Skip. + // See the vertex decoder, where this is updated. + if ((flags & BINDFBCOLOR_MAY_COPY_WITH_UV) == BINDFBCOLOR_MAY_COPY_WITH_UV && gstate_c.vertBounds.maxU > gstate_c.vertBounds.minU) { + x = gstate_c.vertBounds.minU; + y = gstate_c.vertBounds.minV; + w = gstate_c.vertBounds.maxU - x; + h = gstate_c.vertBounds.maxV - y; + + // If we bound a framebuffer, apply the byte offset as pixels to the copy too. + if (flags & BINDFBCOLOR_APPLY_TEX_OFFSET) { + x += gstate_c.curTextureXOffset; + y += gstate_c.curTextureYOffset; + } + } + + BlitFramebuffer(©Info, x, y, framebuffer, x, y, w, h, 0); + + fbo_bind_color_as_texture(renderCopy, 0); + } else { + fbo_bind_color_as_texture(framebuffer->fbo_vk, 0); + } + } else { + fbo_bind_color_as_texture(framebuffer->fbo_vk, 0); + } + + if (stage != GL_TEXTURE0) { + glActiveTexture(stage); + } + */ +} + +struct CardboardSettings * FramebufferManagerVulkan::GetCardboardSettings(struct CardboardSettings * cardboardSettings) { + if (cardboardSettings) { + // Calculate Cardboard Settings + float cardboardScreenScale = g_Config.iCardboardScreenSize / 100.0f; + float cardboardScreenWidth = pixelWidth_ / 2.0f * cardboardScreenScale; + float cardboardScreenHeight = pixelHeight_ / 2.0f * cardboardScreenScale; + float cardboardMaxXShift = (pixelWidth_ / 2.0f - cardboardScreenWidth) / 2.0f; + float cardboardUserXShift = g_Config.iCardboardXShift / 100.0f * cardboardMaxXShift; + float cardboardLeftEyeX = cardboardMaxXShift + cardboardUserXShift; + float cardboardRightEyeX = pixelWidth_ / 2.0f + cardboardMaxXShift - cardboardUserXShift; + float cardboardMaxYShift = pixelHeight_ / 2.0f - cardboardScreenHeight / 2.0f; + float cardboardUserYShift = g_Config.iCardboardYShift / 100.0f * cardboardMaxYShift; + float cardboardScreenY = cardboardMaxYShift + cardboardUserYShift; + + // Copy current Settings into Structure + cardboardSettings->enabled = g_Config.bEnableCardboard; + cardboardSettings->leftEyeXPosition = cardboardLeftEyeX; + cardboardSettings->rightEyeXPosition = cardboardRightEyeX; + cardboardSettings->screenYPosition = cardboardScreenY; + cardboardSettings->screenWidth = cardboardScreenWidth; + cardboardSettings->screenHeight = cardboardScreenHeight; + } + + return cardboardSettings; +} + +void FramebufferManagerVulkan::CopyDisplayToOutput() { + // This is where we should collect all the renderpasses from this frame, + // sort them in order according to texturing dependencies, and enqueue + // them on the Vulkan context. + + // Then, we will simply perform a blit of the currently displayed framebuffer to the backbuffer. + // If there's no extra graphics to draw like framerate counters or controls, + // then in theory, we can even avoid starting up a render pass at all for the backbuffer (!). not sure if that + // is worth the needed refactoring trouble though. + + // fbo_unbind(); + // glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + + currentRenderVfb_ = 0; + + if (useBufferedRendering_) { + // TODO: Clear here. Although it will be done through the surface pass instead.. + } + + if (displayFramebufPtr_ == 0) { + DEBUG_LOG(SCEGE, "Display disabled, displaying only black"); + // No framebuffer to display! Clear to black. + ClearBuffer(); + return; + } + + u32 offsetX = 0; + u32 offsetY = 0; + + struct CardboardSettings cardboardSettings; + GetCardboardSettings(&cardboardSettings); + + VirtualFramebuffer *vfb = GetVFBAt(displayFramebufPtr_); + if (!vfb) { + // Let's search for a framebuf within this range. + const u32 addr = (displayFramebufPtr_ & 0x03FFFFFF) | 0x04000000; + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *v = vfbs_[i]; + const u32 v_addr = (v->fb_address & 0x03FFFFFF) | 0x04000000; + const u32 v_size = FramebufferByteSize(v); + if (addr >= v_addr && addr < v_addr + v_size) { + const u32 dstBpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride; + const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride; + // We have enough space there for the display, right? + if (v_offsetX + 480 > (u32)v->fb_stride || v->bufferHeight < v_offsetY + 272) { + continue; + } + // Check for the closest one. + if (offsetY == 0 || offsetY > v_offsetY) { + offsetX = v_offsetX; + offsetY = v_offsetY; + vfb = v; + } + } + } + + if (vfb) { + // Okay, we found one above. + INFO_LOG_REPORT_ONCE(displayoffset, HLE, "Rendering from framebuf with offset %08x -> %08x+%dx%d", addr, vfb->fb_address, offsetX, offsetY); + } + } + + if (vfb && vfb->format != displayFormat_) { + if (vfb->last_frame_render + FBO_OLD_AGE < gpuStats.numFlips) { + // The game probably switched formats on us. + vfb->format = displayFormat_; + } else { + vfb = 0; + } + } + + if (!vfb) { + if (Memory::IsValidAddress(displayFramebufPtr_)) { + // The game is displaying something directly from RAM. In GTA, it's decoded video. + + // First check that it's not a known RAM copy of a VRAM framebuffer though, as in MotoGP + for (auto iter = knownFramebufferRAMCopies_.begin(); iter != knownFramebufferRAMCopies_.end(); ++iter) { + if (iter->second == displayFramebufPtr_) { + vfb = GetVFBAt(iter->first); + } + } + + if (!vfb) { + // Just a pointer to plain memory to draw. We should create a framebuffer, then draw to it. + DrawFramebufferToOutput(Memory::GetPointer(displayFramebufPtr_), displayFormat_, displayStride_, true); + return; + } + } else { + DEBUG_LOG(SCEGE, "Found no FBO to display! displayFBPtr = %08x", displayFramebufPtr_); + // No framebuffer to display! Clear to black. + ClearBuffer(); + return; + } + } + + vfb->usageFlags |= FB_USAGE_DISPLAYED_FRAMEBUFFER; + vfb->last_frame_displayed = gpuStats.numFlips; + vfb->dirtyAfterDisplay = false; + vfb->reallyDirtyAfterDisplay = false; + + if (prevDisplayFramebuf_ != displayFramebuf_) { + prevPrevDisplayFramebuf_ = prevDisplayFramebuf_; + } + if (displayFramebuf_ != vfb) { + prevDisplayFramebuf_ = displayFramebuf_; + } + displayFramebuf_ = vfb; + + if (vfb->fbo_vk) { + DEBUG_LOG(SCEGE, "Displaying FBO %08x", vfb->fb_address); + + // We should not be in a renderpass here so can just copy. + + /* + GLuint colorTexture = fbo_get_color_texture(vfb->fbo_vk); + + int uvRotation = (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL; + + // Output coordinates + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, uvRotation); + + // TODO ES3: Use glInvalidateFramebuffer to discard depth/stencil data at the end of frame. + + float u0 = offsetX / (float)vfb->bufferWidth; + float v0 = offsetY / (float)vfb->bufferHeight; + float u1 = (480.0f + offsetX) / (float)vfb->bufferWidth; + float v1 = (272.0f + offsetY) / (float)vfb->bufferHeight; + + if (!usePostShader_) { + // We are doing the DrawActiveTexture call directly to the backbuffer here. Hence, we must + // flip V. + std::swap(v0, v1); + if (cardboardSettings.enabled) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + } else if (usePostShader_ && extraFBOs_.size() == 1 && !postShaderAtOutputResolution_) { + // An additional pass, post-processing shader to the extra FBO. + fbo_bind_as_render_target(extraFBOs_[0]); + int fbo_w, fbo_h; + fbo_get_dimensions(extraFBOs_[0], &fbo_w, &fbo_h); + glstate.viewport.set(0, 0, fbo_w, fbo_h); + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(vfb->bufferWidth, vfb->bufferHeight, renderWidth_, renderHeight_); + DrawActiveTexture(colorTexture, 0, 0, fbo_w, fbo_h, fbo_w, fbo_h, 0.0f, 0.0f, 1.0f, 1.0f, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + + fbo_unbind(); + + // Use the extra FBO, with applied post-processing shader, as a texture. + // fbo_bind_color_as_texture(extraFBOs_[0], 0); + if (extraFBOs_.size() == 0) { + ERROR_LOG(G3D, "WTF?"); + return; + } + colorTexture = fbo_get_color_texture(extraFBOs_[0]); + + // We are doing the DrawActiveTexture call directly to the backbuffer after here. Hence, we must + // flip V. + std::swap(v0, v1); + + if (g_Config.bEnableCardboard) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { + fbo_bind_as_render_target(extraFBOs_[0]); + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(GL_FRAMEBUFFER, 3, attachments); + } + } else { + // We are doing the DrawActiveTexture call directly to the backbuffer here. Hence, we must + // flip V. + std::swap(v0, v1); + + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(vfb->bufferWidth, vfb->bufferHeight, vfb->renderWidth, vfb->renderHeight); + if (g_Config.bEnableCardboard) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, uvRotation); + } + } + + glBindTexture(GL_TEXTURE_2D, 0); + */ + } +} + +void FramebufferManagerVulkan::ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) { + PROFILE_THIS_SCOPE("gpu-readback"); + if (sync) { + // flush async just in case when we go for synchronous update + // Doesn't actually pack when sent a null argument. + PackFramebufferAsync_(nullptr); + } + + if (vfb) { + // We'll pseudo-blit framebuffers here to get a resized version of vfb. + VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb); + OptimizeDownloadRange(vfb, x, y, w, h); + BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0); + + // PackFramebufferSync_() - Synchronous pixel data transfer using glReadPixels + // PackFramebufferAsync_() - Asynchronous pixel data transfer using glReadPixels with PBOs + + // TODO: Can we fall back to sync without these? + if (!sync) { + PackFramebufferAsync_(nvfb); + } else { + PackFramebufferSync_(nvfb, x, y, w, h); + } + + textureCache_->ForgetLastTexture(); + RebindFramebuffer(); + } +} + +void FramebufferManagerVulkan::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { + PROFILE_THIS_SCOPE("gpu-readback"); + // Flush async just in case. + PackFramebufferAsync_(nullptr); + + VirtualFramebuffer *vfb = GetVFBAt(fb_address); + if (vfb && vfb->fb_stride != 0) { + const u32 bpp = vfb->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + int x = 0; + int y = 0; + int pixels = loadBytes / bpp; + // The height will be 1 for each stride or part thereof. + int w = std::min(pixels % vfb->fb_stride, (int)vfb->width); + int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height); + + // No need to download if we already have it. + if (!vfb->memoryUpdated && vfb->clutUpdatedBytes < loadBytes) { + // We intentionally don't call OptimizeDownloadRange() here - we don't want to over download. + // CLUT framebuffers are often incorrectly estimated in size. + if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) { + vfb->memoryUpdated = true; + } + vfb->clutUpdatedBytes = loadBytes; + + // We'll pseudo-blit framebuffers here to get a resized version of vfb. + VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb); + BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0); + + PackFramebufferSync_(nvfb, x, y, w, h); + + textureCache_->ForgetLastTexture(); + RebindFramebuffer(); + } + } +} + +bool FramebufferManagerVulkan::CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + // When updating VRAM, it need to be exact format. + if (!gstate_c.Supports(GPU_PREFER_CPU_DOWNLOAD)) { + switch (nvfb->format) { + case GE_FORMAT_4444: + nvfb->colorDepth = VK_FBO_4444; + break; + case GE_FORMAT_5551: + nvfb->colorDepth = VK_FBO_5551; + break; + case GE_FORMAT_565: + nvfb->colorDepth = VK_FBO_565; + break; + case GE_FORMAT_8888: + default: + nvfb->colorDepth = VK_FBO_8888; + break; + } + } + + /* + nvfb->fbo = fbo_create(nvfb->width, nvfb->height, 1, false, (FBOColorDepth)nvfb->colorDepth); + if (!(nvfb->fbo)) { + ERROR_LOG(SCEGE, "Error creating FBO! %i x %i", nvfb->renderWidth, nvfb->renderHeight); + return false; + } + + fbo_bind_as_render_target(nvfb->fbo); + ClearBuffer(); + glDisable(GL_DITHER); + */ + return true; +} + +void FramebufferManagerVulkan::UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + _assert_msg_(G3D, nvfb->fbo, "Expecting a valid nvfb in UpdateDownloadTempBuffer"); + + // Discard the previous contents of this buffer where possible. + /* + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { + fbo_bind_as_render_target(nvfb->fbo); + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_STENCIL_ATTACHMENT, GL_DEPTH_ATTACHMENT }; + glInvalidateFramebuffer(GL_FRAMEBUFFER, 3, attachments); + } else if (gl_extensions.IsGLES) { + fbo_bind_as_render_target(nvfb->fbo); + ClearBuffer(); + } + */ +} + +void FramebufferManagerVulkan::BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) { + /* + if (!dst->fbo || !src->fbo || !useBufferedRendering_) { + // This can happen if they recently switched from non-buffered. + fbo_unbind(); + return; + } + + bool useBlit = gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT | GPU_SUPPORTS_NV_FRAMEBUFFER_BLIT); + bool useNV = useBlit && !gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT); + + float srcXFactor = useBlit ? (float)src->renderWidth / (float)src->bufferWidth : 1.0f; + float srcYFactor = useBlit ? (float)src->renderHeight / (float)src->bufferHeight : 1.0f; + const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2; + if (srcBpp != bpp && bpp != 0) { + srcXFactor = (srcXFactor * bpp) / srcBpp; + } + int srcX1 = srcX * srcXFactor; + int srcX2 = (srcX + w) * srcXFactor; + int srcY1 = srcY * srcYFactor; + int srcY2 = (srcY + h) * srcYFactor; + + float dstXFactor = useBlit ? (float)dst->renderWidth / (float)dst->bufferWidth : 1.0f; + float dstYFactor = useBlit ? (float)dst->renderHeight / (float)dst->bufferHeight : 1.0f; + const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2; + if (dstBpp != bpp && bpp != 0) { + dstXFactor = (dstXFactor * bpp) / dstBpp; + } + int dstX1 = dstX * dstXFactor; + int dstX2 = (dstX + w) * dstXFactor; + int dstY1 = dstY * dstYFactor; + int dstY2 = (dstY + h) * dstYFactor; + + if (src == dst && srcX == dstX && srcY == dstY) { + // Let's just skip a copy where the destination is equal to the source. + WARN_LOG_REPORT_ONCE(blitSame, G3D, "Skipped blit with equal dst and src"); + return; + } + + if (gstate_c.Supports(GPU_SUPPORTS_ANY_COPY_IMAGE)) { + // glBlitFramebuffer can clip, but glCopyImageSubData is more restricted. + // In case the src goes outside, we just skip the optimization in that case. + const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1; + const bool sameDepth = dst->colorDepth == src->colorDepth; + const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight; + const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight; + const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2; + const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2; + if (sameSize && sameDepth && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) { +#if defined(USING_GLES2) +#ifndef IOS + glCopyImageSubDataOES( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; +#endif +#else + if (gl_extensions.ARB_copy_image) { + glCopyImageSubData( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; + } else if (gl_extensions.NV_copy_image) { + // Older, pre GL 4.x NVIDIA cards. + glCopyImageSubDataNV( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; + } +#endif + } + } + + fbo_bind_as_render_target(dst->fbo); + glstate.scissorTest.force(false); + + if (useBlit) { + fbo_bind_for_read(src->fbo); + if (!useNV) { + glBlitFramebuffer(srcX1, srcY1, srcX2, srcY2, dstX1, dstY1, dstX2, dstY2, GL_COLOR_BUFFER_BIT, GL_NEAREST); + } else { +#if defined(USING_GLES2) && defined(ANDROID) // We only support this extension on Android, it's not even available on PC. + glBlitFramebufferNV(srcX1, srcY1, srcX2, srcY2, dstX1, dstY1, dstX2, dstY2, GL_COLOR_BUFFER_BIT, GL_NEAREST); +#endif // defined(USING_GLES2) && defined(ANDROID) + } + + fbo_unbind_read(); + } else { + fbo_bind_color_as_texture(src->fbo, 0); + + // Make sure our 2D drawing program is ready. Compiles only if not already compiled. + CompileDraw2DProgram(); + + glstate.viewport.force(0, 0, dst->renderWidth, dst->renderHeight); + glstate.blend.force(false); + glstate.cullFace.force(false); + glstate.depthTest.force(false); + glstate.stencilTest.force(false); +#if !defined(USING_GLES2) + glstate.colorLogicOp.force(false); +#endif + glstate.colorMask.force(true, true, true, true); + glstate.stencilMask.force(0xFF); + + // The first four coordinates are relative to the 6th and 7th arguments of DrawActiveTexture. + // Should maybe revamp that interface. + float srcW = src->bufferWidth; + float srcH = src->bufferHeight; + DrawActiveTexture(0, dstX1, dstY1, w * dstXFactor, h, dst->bufferWidth, dst->bufferHeight, srcX1 / srcW, srcY1 / srcH, srcX2 / srcW, srcY2 / srcH, draw2dprogram_, ROTATION_LOCKED_HORIZONTAL); + glBindTexture(GL_TEXTURE_2D, 0); + textureCache_->ForgetLastTexture(); + glstate.viewport.restore(); + glstate.blend.restore(); + glstate.cullFace.restore(); + glstate.depthTest.restore(); + glstate.stencilTest.restore(); +#if !defined(USING_GLES2) + glstate.colorLogicOp.restore(); +#endif + glstate.colorMask.restore(); + glstate.stencilMask.restore(); + } + + glstate.scissorTest.restore(); + */ +} + +// TODO: SSE/NEON +// Could also make C fake-simd for 64-bit, two 8888 pixels fit in a register :) +void ConvertFromRGBA8888_Vulkan(u8 *dst, const u8 *src, u32 dstStride, u32 srcStride, u32 width, u32 height, GEBufferFormat format) { + // Must skip stride in the cases below. Some games pack data into the cracks, like MotoGP. + const u32 *src32 = (const u32 *)src; + + if (format == GE_FORMAT_8888) { + u32 *dst32 = (u32 *)dst; + if (src == dst) { + return; + } else { + // Here let's assume they don't intersect + for (u32 y = 0; y < height; ++y) { + memcpy(dst32, src32, width * 4); + src32 += srcStride; + dst32 += dstStride; + } + } + } else { + // But here it shouldn't matter if they do intersect + u16 *dst16 = (u16 *)dst; + switch (format) { + case GE_FORMAT_565: // BGR 565 + for (u32 y = 0; y < height; ++y) { + ConvertRGBA8888ToRGB565(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_5551: // ABGR 1555 + for (u32 y = 0; y < height; ++y) { + ConvertBGRA8888ToRGBA5551(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_4444: // ABGR 4444 + for (u32 y = 0; y < height; ++y) { + ConvertRGBA8888ToRGBA4444(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_8888: + case GE_FORMAT_INVALID: + // Not possible. + break; + } + } +} + +#ifdef DEBUG_READ_PIXELS +// TODO: Make more generic. +static void LogReadPixelsError(GLenum error) { + switch (error) { + case GL_NO_ERROR: + break; + case GL_INVALID_ENUM: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_ENUM"); + break; + case GL_INVALID_VALUE: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_VALUE"); + break; + case GL_INVALID_OPERATION: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_OPERATION"); + break; + case GL_INVALID_FRAMEBUFFER_OPERATION: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_FRAMEBUFFER_OPERATION"); + break; + case GL_OUT_OF_MEMORY: + ERROR_LOG(SCEGE, "glReadPixels: GL_OUT_OF_MEMORY"); + break; +#ifndef USING_GLES2 + case GL_STACK_UNDERFLOW: + ERROR_LOG(SCEGE, "glReadPixels: GL_STACK_UNDERFLOW"); + break; + case GL_STACK_OVERFLOW: + ERROR_LOG(SCEGE, "glReadPixels: GL_STACK_OVERFLOW"); + break; +#endif + default: + ERROR_LOG(SCEGE, "glReadPixels: %08x", error); + break; + } +} +#endif + +void FramebufferManagerVulkan::PackFramebufferAsync_(VirtualFramebuffer *vfb) { + /* + const int MAX_PBO = 2; + GLubyte *packed = 0; + bool unbind = false; + const u8 nextPBO = (currentPBO_ + 1) % MAX_PBO; + const bool useCPU = gstate_c.Supports(GPU_PREFER_CPU_DOWNLOAD); + + // We'll prepare two PBOs to switch between readying and reading + if (!pixelBufObj_) { + if (!vfb) { + // This call is just to flush the buffers. We don't have any yet, + // so there's nothing to do. + return; + } + + GLuint pbos[MAX_PBO]; + glGenBuffers(MAX_PBO, pbos); + + pixelBufObj_ = new AsyncPBO[MAX_PBO]; + for (int i = 0; i < MAX_PBO; i++) { + pixelBufObj_[i].handle = pbos[i]; + pixelBufObj_[i].maxSize = 0; + pixelBufObj_[i].reading = false; + } + } + + // Receive previously requested data from a PBO + AsyncPBO &pbo = pixelBufObj_[nextPBO]; + if (pbo.reading) { + glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo.handle); +#ifdef USING_GLES2 + // Not on desktop GL 2.x... + packed = (GLubyte *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo.size, GL_MAP_READ_BIT); +#else + packed = (GLubyte *)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); +#endif + + if (packed) { + DEBUG_LOG(SCEGE, "Reading PBO to memory , bufSize = %u, packed = %p, fb_address = %08x, stride = %u, pbo = %u", + pbo.size, packed, pbo.fb_address, pbo.stride, nextPBO); + + if (useCPU || (UseBGRA8888() && pbo.format == GE_FORMAT_8888)) { + u8 *dst = Memory::GetPointer(pbo.fb_address); + ConvertFromRGBA8888(dst, packed, pbo.stride, pbo.stride, pbo.stride, pbo.height, pbo.format); + } else { + // We don't need to convert, GPU already did (or should have) + Memory::MemcpyUnchecked(pbo.fb_address, packed, pbo.size); + } + + pbo.reading = false; + } + + glUnmapBuffer(GL_PIXEL_PACK_BUFFER); + unbind = true; + } + + // Order packing/readback of the framebuffer + if (vfb) { + int pixelType, pixelSize, pixelFormat, align; + + bool reverseOrder = gstate_c.Supports(GPU_PREFER_REVERSE_COLOR_ORDER); + switch (vfb->format) { + // GL_UNSIGNED_INT_8_8_8_8 returns A B G R (little-endian, tested in Nvidia card/x86 PC) + // GL_UNSIGNED_BYTE returns R G B A in consecutive bytes ("big-endian"/not treated as 32-bit value) + // We want R G B A, so we use *_REV for 16-bit formats and GL_UNSIGNED_BYTE for 32-bit + case GE_FORMAT_4444: // 16 bit RGBA +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_4_4_4_4; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_4_4_4_4_REV : GL_UNSIGNED_SHORT_4_4_4_4); +#endif + pixelFormat = GL_RGBA; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_5551: // 16 bit RGBA +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_5_5_5_1; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_1_5_5_5_REV : GL_UNSIGNED_SHORT_5_5_5_1); +#endif + pixelFormat = GL_RGBA; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_565: // 16 bit RGB +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_5_6_5; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_5_6_5_REV : GL_UNSIGNED_SHORT_5_6_5); +#endif + pixelFormat = GL_RGB; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_8888: // 32 bit RGBA + default: + pixelType = GL_UNSIGNED_BYTE; + pixelFormat = UseBGRA8888() ? GL_BGRA_EXT : GL_RGBA; + pixelSize = 4; + align = 4; + break; + } + + // If using the CPU, we need 4 bytes per pixel always. + u32 bufSize = vfb->fb_stride * vfb->height * (useCPU ? 4 : pixelSize); + u32 fb_address = (0x04000000) | vfb->fb_address; + + if (vfb->fbo) { + fbo_bind_for_read(vfb->fbo); + } else { + ERROR_LOG_REPORT_ONCE(vfbfbozero, SCEGE, "PackFramebufferAsync_: vfb->fbo == 0"); + fbo_unbind_read(); + return; + } + + GLenum fbStatus; + fbStatus = (GLenum)fbo_check_framebuffer_status(vfb->fbo); + + if (fbStatus != GL_FRAMEBUFFER_COMPLETE) { + ERROR_LOG(SCEGE, "Incomplete source framebuffer, aborting read"); + fbo_unbind_read(); + return; + } + + glBindBuffer(GL_PIXEL_PACK_BUFFER, pixelBufObj_[currentPBO_].handle); + + if (pixelBufObj_[currentPBO_].maxSize < bufSize) { + // We reserve a buffer big enough to fit all those pixels + glBufferData(GL_PIXEL_PACK_BUFFER, bufSize, NULL, GL_DYNAMIC_READ); + pixelBufObj_[currentPBO_].maxSize = bufSize; + } + + if (useCPU) { + // If converting pixel formats on the CPU we'll always request RGBA8888 + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->fb_stride, vfb->height, UseBGRA8888() ? GL_BGRA_EXT : GL_RGBA, GL_UNSIGNED_BYTE, 0); + } else { + // Otherwise we'll directly request the format we need and let the GPU sort it out + glPixelStorei(GL_PACK_ALIGNMENT, align); + SafeGLReadPixels(0, 0, vfb->fb_stride, vfb->height, pixelFormat, pixelType, 0); + } + + fbo_unbind_read(); + unbind = true; + + pixelBufObj_[currentPBO_].fb_address = fb_address; + pixelBufObj_[currentPBO_].size = bufSize; + pixelBufObj_[currentPBO_].stride = vfb->fb_stride; + pixelBufObj_[currentPBO_].height = vfb->height; + pixelBufObj_[currentPBO_].format = vfb->format; + pixelBufObj_[currentPBO_].reading = true; + } + + currentPBO_ = nextPBO; + + if (unbind) { + glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); + } + */ +} + +void FramebufferManagerVulkan::PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h) { + /* + if (vfb->fbo) { + fbo_bind_for_read(vfb->fbo); + } else { + ERROR_LOG_REPORT_ONCE(vfbfbozero, SCEGE, "PackFramebufferSync_: vfb->fbo == 0"); + fbo_unbind_read(); + return; + } + + // Pixel size always 4 here because we always request RGBA8888 + size_t bufSize = vfb->fb_stride * std::max(vfb->height, (u16)h) * 4; + u32 fb_address = (0x04000000) | vfb->fb_address; + + GLubyte *packed = 0; + + bool convert = vfb->format != GE_FORMAT_8888 || UseBGRA8888(); + const int dstBpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const int packWidth = x + w < vfb->width ? x + w : vfb->width; + + if (!convert) { + packed = (GLubyte *)Memory::GetPointer(fb_address); + } else { // End result may be 16-bit but we are reading 32-bit, so there may not be enough space at fb_address + u32 neededSize = (u32)bufSize * sizeof(GLubyte); + if (!convBuf_ || convBufSize_ < neededSize) { + delete[] convBuf_; + convBuf_ = new u8[neededSize]; + convBufSize_ = neededSize; + } + packed = convBuf_; + } + + if (packed) { + DEBUG_LOG(SCEGE, "Reading framebuffer to mem, bufSize = %u, packed = %p, fb_address = %08x", + (u32)bufSize, packed, fb_address); + + glPixelStorei(GL_PACK_ALIGNMENT, 4); + GLenum glfmt = GL_RGBA; + if (UseBGRA8888()) { + glfmt = GL_BGRA_EXT; + } + + int byteOffset = y * vfb->fb_stride * 4; + SafeGLReadPixels(0, y, h == 1 ? packWidth : vfb->fb_stride, h, glfmt, GL_UNSIGNED_BYTE, packed + byteOffset); + + if (convert) { + int dstByteOffset = y * vfb->fb_stride * dstBpp; + ConvertFromRGBA8888(Memory::GetPointer(fb_address + dstByteOffset), packed + byteOffset, vfb->fb_stride, vfb->fb_stride, packWidth, h, vfb->format); + } + } + + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { +#ifdef USING_GLES2 + // GLES3 doesn't support using GL_READ_FRAMEBUFFER here. + fbo_bind_as_render_target(vfb->fbo); + const GLenum target = GL_FRAMEBUFFER; +#else + const GLenum target = GL_READ_FRAMEBUFFER; +#endif + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(target, 3, attachments); + } + + fbo_unbind_read(); + */ +} + +#ifdef _WIN32 +void ShowScreenResolution(); +#endif + +void FramebufferManagerVulkan::EndFrame() { + if (resized_) { + // TODO: Only do this if the new size actually changed the renderwidth/height. + DestroyAllFBOs(); + + // Probably not necessary + //glstate.viewport.set(0, 0, PSP_CoreParameter().pixelWidth, PSP_CoreParameter().pixelHeight); + + // Check if postprocessing shader is doing upscaling as it requires native resolution + const ShaderInfo *shaderInfo = 0; + if (g_Config.sPostShaderName != "Off") { + shaderInfo = GetPostShaderInfo(g_Config.sPostShaderName); + } + + postShaderIsUpscalingFilter_ = shaderInfo ? shaderInfo->isUpscalingFilter : false; + + // Actually, auto mode should be more granular... + // Round up to a zoom factor for the render size. + int zoom = g_Config.iInternalResolution; + if (zoom == 0) { // auto mode + // Use the longest dimension + if (!g_Config.IsPortrait()) { + zoom = (PSP_CoreParameter().pixelWidth + 479) / 480; + } else { + zoom = (PSP_CoreParameter().pixelHeight + 479) / 480; + } + } + if (zoom <= 1 || postShaderIsUpscalingFilter_) + zoom = 1; + + if (g_Config.IsPortrait()) { + PSP_CoreParameter().renderWidth = 272 * zoom; + PSP_CoreParameter().renderHeight = 480 * zoom; + } else { + PSP_CoreParameter().renderWidth = 480 * zoom; + PSP_CoreParameter().renderHeight = 272 * zoom; + } + + UpdateSize(); + + resized_ = false; +#ifdef _WIN32 + // Seems related - if you're ok with numbers all the time, show some more :) + if (g_Config.iShowFPSCounter != 0) { + ShowScreenResolution(); + } +#endif + ClearBuffer(); + DestroyDraw2DProgram(); + } + + // We flush to memory last requested framebuffer, if any. + // Only do this in the read-framebuffer modes. + if (updateVRAM_) + PackFramebufferAsync_(nullptr); +} + +void FramebufferManagerVulkan::DeviceLost() { + DestroyAllFBOs(); + DestroyDraw2DProgram(); + resized_ = false; +} + +std::vector FramebufferManagerVulkan::GetFramebufferList() { + std::vector list; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + + FramebufferInfo info; + info.fb_address = vfb->fb_address; + info.z_address = vfb->z_address; + info.format = vfb->format; + info.width = vfb->width; + info.height = vfb->height; + info.fbo = vfb->fbo; + list.push_back(info); + } + + return list; +} + +void FramebufferManagerVulkan::DecimateFBOs() { + currentRenderVfb_ = 0; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + int age = frameLastFramebufUsed_ - std::max(vfb->last_frame_render, vfb->last_frame_used); + + if (ShouldDownloadFramebuffer(vfb) && age == 0 && !vfb->memoryUpdated) { + bool sync = true; + ReadFramebufferToMemory(vfb, sync, 0, 0, vfb->width, vfb->height); + } + + // Let's also "decimate" the usageFlags. + UpdateFramebufUsage(vfb); + + if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) { + if (age > FBO_OLD_AGE) { + INFO_LOG(SCEGE, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + DestroyFramebuf(vfb); + vfbs_.erase(vfbs_.begin() + i--); + } + } + } + + for (auto it = tempFBOs_.begin(); it != tempFBOs_.end(); ) { + int age = frameLastFramebufUsed_ - it->second.last_frame_used; + if (age > FBO_OLD_AGE) { + delete it->second.fbo_vk; + tempFBOs_.erase(it++); + } else { + ++it; + } + } + + // Do the same for ReadFramebuffersToMemory's VFBs + for (size_t i = 0; i < bvfbs_.size(); ++i) { + VirtualFramebuffer *vfb = bvfbs_[i]; + int age = frameLastFramebufUsed_ - vfb->last_frame_render; + if (age > FBO_OLD_AGE) { + INFO_LOG(SCEGE, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + DestroyFramebuf(vfb); + bvfbs_.erase(bvfbs_.begin() + i--); + } + } +} + +void FramebufferManagerVulkan::DestroyAllFBOs() { + currentRenderVfb_ = 0; + displayFramebuf_ = 0; + prevDisplayFramebuf_ = 0; + prevPrevDisplayFramebuf_ = 0; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + INFO_LOG(SCEGE, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->format); + DestroyFramebuf(vfb); + } + vfbs_.clear(); + + for (size_t i = 0; i < bvfbs_.size(); ++i) { + VirtualFramebuffer *vfb = bvfbs_[i]; + DestroyFramebuf(vfb); + } + bvfbs_.clear(); + + for (auto it = tempFBOs_.begin(), end = tempFBOs_.end(); it != end; ++it) { + delete it->second.fbo_vk; + } + tempFBOs_.clear(); +} + +void FramebufferManagerVulkan::FlushBeforeCopy() { + // Flush anything not yet drawn before blitting, downloading, or uploading. + // This might be a stalled list, or unflushed before a block transfer, etc. + + // TODO: It's really bad that we are calling SetRenderFramebuffer here with + // all the irrelevant state checking it'll use to decide what to do. Should + // do something more focused here. + SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + transformDraw_->Flush(curCmd_); +} + +void FramebufferManagerVulkan::Resized() { + resized_ = true; +} + +bool FramebufferManagerVulkan::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? +/* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } + + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + buffer = GPUDebugBuffer(Memory::GetPointer(fb_address | 0x04000000), fb_stride, 512, format); + return true; + } + + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, false, true); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer.GetData()); + */ + return false; +} + +bool FramebufferManagerVulkan::GetDisplayFramebuffer(GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + fbo_unbind_read(); + + int pw = PSP_CoreParameter().pixelWidth; + int ph = PSP_CoreParameter().pixelHeight; + + // The backbuffer is flipped. + buffer.Allocate(pw, ph, GPU_DBG_FORMAT_888_RGB, true); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + SafeGLReadPixels(0, 0, pw, ph, GL_RGB, GL_UNSIGNED_BYTE, buffer.GetData()); + */ + return false; +} + +bool FramebufferManagerVulkan::GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } + + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + buffer = GPUDebugBuffer(Memory::GetPointer(z_address | 0x04000000), z_stride, 512, GPU_DBG_FORMAT_16BIT); + return true; + } + + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GPU_DBG_FORMAT_FLOAT, false); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_DEPTH_COMPONENT, GL_FLOAT, buffer.GetData()); + */ + return false; +} + +bool FramebufferManagerVulkan::GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } + + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + // TODO: Actually get the stencil. + buffer = GPUDebugBuffer(Memory::GetPointer(fb_address | 0x04000000), fb_stride, 512, GPU_DBG_FORMAT_8888); + return true; + } + + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GPU_DBG_FORMAT_8BIT, false); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + glPixelStorei(GL_PACK_ALIGNMENT, 2); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, buffer.GetData()); + + return true; + */ + return false; +} diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h new file mode 100644 index 0000000000..0b93fabef0 --- /dev/null +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -0,0 +1,197 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/Vulkan/VulkanLoader.h" +#include "GPU/Common/FramebufferCommon.h" +#include "GPU/GPUInterface.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Vulkan/VulkanUtil.h" + +// TODO: WTF? +enum VulkanFBOColorDepth { + VK_FBO_8888, + VK_FBO_565, + VK_FBO_4444, + VK_FBO_5551, +}; + +class TextureCacheVulkan; +class DrawEngineVulkan; +class VulkanContext; +class ShaderManagerVulkan; +class VulkanTexture; + +struct PostShaderUniforms { + float texelDelta[2]; float pad[2]; + float pixelDelta[2]; float pad0[2]; + float time[4]; +}; + +// Simple struct for asynchronous PBO readbacks +// TODO: Probably will need a complete redesign. +struct AsyncPBOVulkan { + // handle; + u32 maxSize; + + u32 fb_address; + u32 stride; + u32 height; + u32 size; + GEBufferFormat format; + bool reading; +}; + +struct CardboardSettings { + bool enabled; + float leftEyeXPosition; + float rightEyeXPosition; + float screenYPosition; + float screenWidth; + float screenHeight; +}; + +class FramebufferManagerVulkan : public FramebufferManagerCommon { +public: + FramebufferManagerVulkan(VulkanContext *vulkan); + ~FramebufferManagerVulkan(); + + void SetTextureCache(TextureCacheVulkan *tc) { + textureCache_ = tc; + } + void SetShaderManager(ShaderManagerVulkan *sm) { + shaderManager_ = sm; + } + void SetDrawEngine(DrawEngineVulkan *td) { + transformDraw_ = td; + } + + void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; + void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; + void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) override; + + // If texture != 0, will bind it. + // x,y,w,h are relative to destW, destH which fill out the target completely. + void DrawActiveTexture(VulkanTexture *texture, float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, VkPipeline pipeline, int uvRotation); + + void DestroyAllFBOs(); + + virtual void Init() override; + void EndFrame(); + void Resized(); + void DeviceLost(); + void CopyDisplayToOutput(); + int GetLineWidth(); + void ReformatFramebufferFrom(VirtualFramebuffer *vfb, GEBufferFormat old); + + void BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst); + + // For use when texturing from a framebuffer. May create a duplicate if target. + void BindFramebufferColor(int stage, u32 fbRawAddress, VirtualFramebuffer *framebuffer, int flags); + + // Reads a rectangular subregion of a framebuffer to the right position in its backing memory. + void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override; + void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override; + + std::vector GetFramebufferList(); + + bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override; + + void DestroyFramebuf(VirtualFramebuffer *vfb) override; + void ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force = false) override; + + bool GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer); + bool GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer); + bool GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer); + static bool GetDisplayFramebuffer(GPUDebugBuffer &buffer); + + virtual void RebindFramebuffer() override; + + VulkanFBO *GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth = VK_FBO_8888); + + // Cardboard Settings Calculator + struct CardboardSettings * GetCardboardSettings(struct CardboardSettings * cardboardSettings); + +protected: + virtual void DisableState() override; + virtual void ClearBuffer(bool keepState = false); + virtual void FlushBeforeCopy() override; + virtual void DecimateFBOs() override; + + // Used by ReadFramebufferToMemory and later framebuffer block copies + virtual void BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) override; + + virtual void NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) override; + virtual void NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) override; + virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override; + virtual bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + virtual void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + + +private: + void UpdatePostShaderUniforms(int bufferWidth, int bufferHeight, int renderWidth, int renderHeight); + void CompileDraw2DProgram(); + void DestroyDraw2DProgram(); + + void SetNumExtraFBOs(int num); + + void PackFramebufferAsync_(VirtualFramebuffer *vfb); // Not used under ES currently + void PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h); + + VulkanContext *vulkan_; + + // The command buffer of the current framebuffer pass being rendered to. + // One framebuffer can be used as a texturing source at multiple times in a frame, + // but then the contents have to be copied out into a new texture every time. + VkCommandBuffer curCmd_; + + DrawEngineVulkan *drawEngine_; + + // Used by DrawPixels + VulkanTexture *drawPixelsTex_; + GEBufferFormat drawPixelsTexFormat_; + + int drawPixelsTexW_; + int drawPixelsTexH_; + + u8 *convBuf_; + u32 convBufSize_; + + TextureCacheVulkan *textureCache_; + ShaderManagerVulkan *shaderManager_; + DrawEngineVulkan *transformDraw_; + + // Used by post-processing shader + std::vector extraFBOs_; + + bool resized_; + + struct TempFBO { + VulkanFBO *fbo_vk; + int last_frame_used; + }; + + std::map tempFBOs_; + + // Not used under ES currently. + AsyncPBOVulkan *pixelBufObj_; //this isn't that large + u8 currentPBO_; + + // This gets copied to the current frame's push buffer as needed. + PostShaderUniforms postUniforms_; +}; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp new file mode 100644 index 0000000000..a7c345bb6b --- /dev/null +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -0,0 +1,2171 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "base/logging.h" +#include "profiler/profiler.h" + +#include "Common/ChunkFile.h" +#include "Common/GraphicsContext.h" + +#include "Core/Config.h" +#include "Core/Debugger/Breakpoints.h" +#include "Core/MemMapHelpers.h" +#include "Core/Host.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +#include "Core/System.h" + +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/GeDisasm.h" +#include "GPU/Common/FramebufferCommon.h" + +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/GPU_Vulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" + +#include "Core/MIPS/MIPS.h" +#include "Core/HLE/sceKernelThread.h" +#include "Core/HLE/sceKernelInterrupt.h" +#include "Core/HLE/sceGe.h" + +enum { + FLAG_FLUSHBEFORE = 1, + FLAG_FLUSHBEFOREONCHANGE = 2, + FLAG_EXECUTE = 4, // needs to actually be executed. unused for now. + FLAG_EXECUTEONCHANGE = 8, + FLAG_ANY_EXECUTE = 4 | 8, + FLAG_READS_PC = 16, + FLAG_WRITES_PC = 32, + FLAG_DIRTYONCHANGE = 64, +}; + +struct CommandTableEntry { + u8 cmd; + u8 flags; + u64 dirtyFlags; + GPU_Vulkan::CmdFunc func; +}; + +GPU_Vulkan::CommandInfo GPU_Vulkan::cmdInfo_[256]; + +// This table gets crunched into a faster form by init. +// TODO: Share this table between the backends. Will have to make another indirection for the function pointers though.. +static const CommandTableEntry commandTable[] = { + // Changes that dirty the framebuffer + { GE_CMD_FRAMEBUFPTR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_FRAMEBUFWIDTH, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_FRAMEBUFPIXFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_ZBUFPTR, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZBUFWIDTH, FLAG_FLUSHBEFOREONCHANGE }, + + // Changes that dirty uniforms + { GE_CMD_FOGCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOLOR, &GPU_Vulkan::Execute_FogColor }, + { GE_CMD_FOG1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOEF, &GPU_Vulkan::Execute_FogCoef }, + { GE_CMD_FOG2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOEF, &GPU_Vulkan::Execute_FogCoef }, + + // Should these maybe flush? + { GE_CMD_MINZ, FLAG_FLUSHBEFOREONCHANGE, DIRTY_DEPTHRANGE }, + { GE_CMD_MAXZ, FLAG_FLUSHBEFOREONCHANGE, DIRTY_DEPTHRANGE }, + + // Changes that dirty texture scaling. + { GE_CMD_TEXMAPMODE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexMapMode }, + { GE_CMD_TEXSCALEU, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexScaleU }, + { GE_CMD_TEXSCALEV, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexScaleV }, + { GE_CMD_TEXOFFSETU, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexOffsetU }, + { GE_CMD_TEXOFFSETV, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexOffsetV }, + + // Changes that dirty the current texture. Really should be possible to avoid executing these if we compile + // by adding some more flags. + { GE_CMD_TEXSIZE0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_TexSize0 }, + { GE_CMD_TEXSIZE1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexFormat }, + { GE_CMD_TEXLEVEL, FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexLevel }, + { GE_CMD_TEXADDR0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddr0 }, + { GE_CMD_TEXADDR1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXBUFWIDTH0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufw0 }, + { GE_CMD_TEXBUFWIDTH1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + // These must flush on change, so that LoadClut doesn't have to always flush. + { GE_CMD_CLUTADDR, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CLUTADDRUPPER, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CLUTFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ClutFormat }, + + // These affect the fragment shader so need flushing. + { GE_CMD_CLEARMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXTUREMAPENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_FOGENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXMODE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + { GE_CMD_TEXSHADELS, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_SHADEMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXFUNC, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTEST, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ALPHATESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTESTMASK, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_ALPHACOLORMASK, &GPU_Vulkan::Execute_ColorTestMask }, + + // These change the vertex shader so need flushing. + { GE_CMD_REVERSENORMAL, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTINGENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE0, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE1, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE2, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE3, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE0, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE1, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE2, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE3, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MATERIALUPDATE, FLAG_FLUSHBEFOREONCHANGE }, + + // This changes both shaders so need flushing. + { GE_CMD_LIGHTMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXFILTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + { GE_CMD_TEXWRAP, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + + // Uniform changes + { GE_CMD_ALPHATEST, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_ALPHACOLORREF | DIRTY_ALPHACOLORMASK, &GPU_Vulkan::Execute_AlphaTest }, + { GE_CMD_COLORREF, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ColorRef }, + { GE_CMD_TEXENVCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_TEXENV, &GPU_Vulkan::Execute_TexEnvColor }, + + // Simple render state changes. Handled in StateMapping.cpp. + { GE_CMD_OFFSETX, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_OFFSETY, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CULL, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CULLFACEENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_DITHERENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_STENCILOP, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_STENCILTEST, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_STENCILREPLACEVALUE, &GPU_Vulkan::Execute_StencilTest }, + { GE_CMD_STENCILTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ALPHABLENDENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDFIXEDA, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDFIXEDB, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MASKRGB, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MASKALPHA, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZTEST, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZWRITEDISABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LOGICOP, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LOGICOPENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Can probably ignore this one as we don't support AA lines. + { GE_CMD_ANTIALIASENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Morph weights. TODO: Remove precomputation? + { GE_CMD_MORPHWEIGHT0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + + // Control spline/bezier patches. Don't really require flushing as such, but meh. + { GE_CMD_PATCHDIVISION, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHPRIMITIVE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHFACING, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHCULLENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Viewport. + { GE_CMD_VIEWPORTXSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTYSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTXCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTYCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTZSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_DEPTHRANGE, &GPU_Vulkan::Execute_ViewportZType }, + { GE_CMD_VIEWPORTZCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_DEPTHRANGE, &GPU_Vulkan::Execute_ViewportZType }, + + // Region + { GE_CMD_REGION1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Region }, + { GE_CMD_REGION2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Region }, + + // Scissor + { GE_CMD_SCISSOR1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Scissor }, + { GE_CMD_SCISSOR2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Scissor }, + + // These dirty various vertex shader uniforms. Could embed information about that in this table and call dirtyuniform directly, hm... + { GE_CMD_AMBIENTCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_AMBIENT, &GPU_Vulkan::Execute_Ambient }, + { GE_CMD_AMBIENTALPHA, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_AMBIENT, &GPU_Vulkan::Execute_Ambient }, + { GE_CMD_MATERIALDIFFUSE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATDIFFUSE, &GPU_Vulkan::Execute_MaterialDiffuse }, + { GE_CMD_MATERIALEMISSIVE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATEMISSIVE, &GPU_Vulkan::Execute_MaterialEmissive }, + { GE_CMD_MATERIALAMBIENT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATAMBIENTALPHA, &GPU_Vulkan::Execute_MaterialAmbient }, + { GE_CMD_MATERIALALPHA, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATAMBIENTALPHA, &GPU_Vulkan::Execute_MaterialAmbient }, + { GE_CMD_MATERIALSPECULAR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATSPECULAR, &GPU_Vulkan::Execute_MaterialSpecular }, + { GE_CMD_MATERIALSPECULARCOEF, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATSPECULAR, &GPU_Vulkan::Execute_MaterialSpecular }, + + // These dirty uniforms, which could be table-ized to avoid execute. + { GE_CMD_LX0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LY0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LZ0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LX1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LY1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LZ1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LX2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LY2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LZ2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LX3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LY3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LZ3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LDX0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDY0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDZ0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDX1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDY1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDZ1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDX2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDY2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDZ2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDX3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDY3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDZ3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKA0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKB0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKA1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKB1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKA2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKB2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKA3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LKB3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LKC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKS0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKS1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKS2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKS3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKO0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKO1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKO2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKO3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LAC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LSC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LAC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LSC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LAC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LSC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LAC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LSC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + // Ignored commands + { GE_CMD_CLIPENABLE, 0 }, + { GE_CMD_TEXFLUSH, 0 }, + { GE_CMD_TEXLODSLOPE, 0 }, + { GE_CMD_TEXSYNC, 0 }, + + // These are just nop or part of other later commands. + { GE_CMD_NOP, 0 }, + { GE_CMD_BASE, 0 }, + { GE_CMD_TRANSFERSRC, 0 }, + { GE_CMD_TRANSFERSRCW, 0 }, + { GE_CMD_TRANSFERDST, 0 }, + { GE_CMD_TRANSFERDSTW, 0 }, + { GE_CMD_TRANSFERSRCPOS, 0 }, + { GE_CMD_TRANSFERDSTPOS, 0 }, + { GE_CMD_TRANSFERSIZE, 0 }, + + // From Common. No flushing but definitely need execute. + { GE_CMD_OFFSETADDR, FLAG_EXECUTE, 0, &GPUCommon::Execute_OffsetAddr }, + { GE_CMD_ORIGIN, FLAG_EXECUTE | FLAG_READS_PC, 0, &GPUCommon::Execute_Origin }, // Really? + { GE_CMD_PRIM, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Prim }, + { GE_CMD_JUMP, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Jump }, + { GE_CMD_CALL, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Call }, + { GE_CMD_RET, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Ret }, + { GE_CMD_END, FLAG_FLUSHBEFORE | FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_End }, // Flush? + { GE_CMD_VADDR, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Vaddr }, + { GE_CMD_IADDR, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Iaddr }, + { GE_CMD_BJUMP, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_BJump }, // EXECUTE + { GE_CMD_BOUNDINGBOX, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoundingBox }, // + FLUSHBEFORE when we implement... or not, do we need to? + + // Changing the vertex type requires us to flush. + { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_VertexType }, + + { GE_CMD_BEZIER, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Bezier }, + { GE_CMD_SPLINE, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Spline }, + + // These two are actually processed in CMD_END. + { GE_CMD_SIGNAL, FLAG_FLUSHBEFORE }, + { GE_CMD_FINISH, FLAG_FLUSHBEFORE }, + + // Changes that trigger data copies. Only flushing on change for LOADCLUT must be a bit of a hack... + { GE_CMD_LOADCLUT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_LoadClut }, + { GE_CMD_TRANSFERSTART, FLAG_FLUSHBEFORE | FLAG_EXECUTE | FLAG_READS_PC, 0, &GPU_Vulkan::Execute_BlockTransferStart }, + + // We don't use the dither table. + { GE_CMD_DITH0 }, + { GE_CMD_DITH1 }, + { GE_CMD_DITH2 }, + { GE_CMD_DITH3 }, + + // These handle their own flushing. + { GE_CMD_WORLDMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_WorldMtxNum }, + { GE_CMD_WORLDMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_WorldMtxData }, + { GE_CMD_VIEWMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_ViewMtxNum }, + { GE_CMD_VIEWMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_ViewMtxData }, + { GE_CMD_PROJMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_ProjMtxNum }, + { GE_CMD_PROJMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_ProjMtxData }, + { GE_CMD_TGENMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_TgenMtxNum }, + { GE_CMD_TGENMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_TgenMtxData }, + { GE_CMD_BONEMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_BoneMtxNum }, + { GE_CMD_BONEMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoneMtxData }, + + // Vertex Screen/Texture/Color + { GE_CMD_VSCX, FLAG_EXECUTE }, + { GE_CMD_VSCY, FLAG_EXECUTE }, + { GE_CMD_VSCZ, FLAG_EXECUTE }, + { GE_CMD_VTCS, FLAG_EXECUTE }, + { GE_CMD_VTCT, FLAG_EXECUTE }, + { GE_CMD_VTCQ, FLAG_EXECUTE }, + { GE_CMD_VCV, FLAG_EXECUTE }, + { GE_CMD_VAP, FLAG_EXECUTE }, + { GE_CMD_VFC, FLAG_EXECUTE }, + { GE_CMD_VSCV, FLAG_EXECUTE }, + + // "Missing" commands (gaps in the sequence) + { GE_CMD_UNKNOWN_03, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_0D, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_11, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_29, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_34, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_35, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_39, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_4E, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_4F, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_52, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_59, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_5A, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_B6, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_B7, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_D1, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_ED, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_EF, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FA, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FB, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FC, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FD, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FE, FLAG_EXECUTE }, + // Appears to be debugging related or something? Hit a lot in GoW. + { GE_CMD_UNKNOWN_FF, 0 }, +}; + +GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) + : vulkan_((VulkanContext *)ctx->GetAPIContext()), + drawEngine_(vulkan_), + textureCache_(vulkan_), + resized_(false), + gfxCtx_(ctx) { + UpdateVsyncInterval(true); + CheckGPUFeatures(); + + shaderManager_ = new ShaderManagerVulkan(vulkan_); + pipelineManager_ = new PipelineManagerVulkan(vulkan_); + framebufferManager_ = new FramebufferManagerVulkan(vulkan_), + drawEngine_.SetTextureCache(&textureCache_); + drawEngine_.SetFramebufferManager(framebufferManager_); + drawEngine_.SetShaderManager(shaderManager_); + drawEngine_.SetPipelineManager(pipelineManager_); + framebufferManager_->Init(); + framebufferManager_->SetTextureCache(&textureCache_); + framebufferManager_->SetDrawEngine(&drawEngine_); + textureCache_.SetFramebufferManager(framebufferManager_); + textureCache_.SetDepalShaderCache(&depalShaderCache_); + textureCache_.SetShaderManager(shaderManager_); + textureCache_.SetTransformDrawEngine(&drawEngine_); + + // Sanity check gstate + if ((int *)&gstate.transferstart - (int *)&gstate != 0xEA) { + ERROR_LOG(G3D, "gstate has drifted out of sync!"); + } + + // Sanity check cmdInfo_ table - no dupes please + std::set dupeCheck; + memset(cmdInfo_, 0, sizeof(cmdInfo_)); + for (size_t i = 0; i < ARRAY_SIZE(commandTable); i++) { + const u8 cmd = commandTable[i].cmd; + if (dupeCheck.find(cmd) != dupeCheck.end()) { + ERROR_LOG(G3D, "Command table Dupe: %02x (%i)", (int)cmd, (int)cmd); + } else { + dupeCheck.insert(cmd); + } + cmdInfo_[cmd].flags |= commandTable[i].flags; + cmdInfo_[cmd].func = commandTable[i].func; + if (!cmdInfo_[cmd].func) { + cmdInfo_[cmd].func = &GPU_Vulkan::Execute_Generic; + } + } + // Find commands missing from the table. + for (int i = 0; i < 0xEF; i++) { + if (dupeCheck.find((u8)i) == dupeCheck.end()) { + ERROR_LOG(G3D, "Command missing from table: %02x (%i)", i, i); + } + } + + // No need to flush before the tex scale/offset commands if we are baking + // the tex scale/offset into the vertices anyway. + + UpdateCmdInfo(); + + BuildReportingInfo(); + // Update again after init to be sure of any silly driver problems. + UpdateVsyncInterval(true); +} + +GPU_Vulkan::~GPU_Vulkan() { + framebufferManager_->DestroyAllFBOs(); + depalShaderCache_.Clear(); + delete framebufferManager_; + delete pipelineManager_; + delete shaderManager_; +} + +void GPU_Vulkan::CheckGPUFeatures() { + gstate_c.featureFlags = 0; + if (vulkan_->GetFeaturesEnabled().wideLines) { + gstate_c.featureFlags |= GPU_SUPPORTS_WIDE_LINES; + } + if (vulkan_->GetFeaturesEnabled().dualSrcBlend) { + gstate_c.featureFlags |= GPU_SUPPORTS_DUALSOURCE_BLEND; + } + if (vulkan_->GetFeaturesEnabled().logicOp) { + gstate_c.featureFlags |= GPU_SUPPORTS_LOGIC_OP; + } + if (vulkan_->GetFeaturesEnabled().samplerAnisotropy) { + gstate_c.featureFlags |= GPU_SUPPORTS_ANISOTROPY; + } + // Mandatory features on Vulkan, which may be checked in "centralized" code + gstate_c.featureFlags |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; + gstate_c.featureFlags |= GPU_SUPPORTS_FBO; + gstate_c.featureFlags |= GPU_SUPPORTS_BLEND_MINMAX; + gstate_c.featureFlags |= GPU_SUPPORTS_ANY_COPY_IMAGE; + gstate_c.featureFlags |= GPU_SUPPORTS_OES_TEXTURE_NPOT; + gstate_c.featureFlags |= GPU_SUPPORTS_LARGE_VIEWPORTS; +} + +void GPU_Vulkan::BeginHostFrame() { + if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) { + // Draw everything directly to the backbuffer. + drawEngine_.SetCmdBuffer(vulkan_->GetSurfaceCommandBuffer()); + } + drawEngine_.BeginFrame(); + + if (resized_) { + CheckGPUFeatures(); + UpdateCmdInfo(); + drawEngine_.Resized(); + } + resized_ = false; + + textureCache_.StartFrame(); + depalShaderCache_.Decimate(); + + if (dumpNextFrame_) { + NOTICE_LOG(G3D, "DUMPING THIS FRAME"); + dumpThisFrame_ = true; + dumpNextFrame_ = false; + } else if (dumpThisFrame_) { + dumpThisFrame_ = false; + } + + shaderManager_->DirtyShader(); + shaderManager_->DirtyUniform(DIRTY_ALL); + + framebufferManager_->BeginFrame(); +} + +void GPU_Vulkan::EndHostFrame() { + drawEngine_.EndFrame(); + framebufferManager_->EndFrame(); +} + +// Needs to be called on GPU thread, not reporting thread. +// TODO +void GPU_Vulkan::BuildReportingInfo() { + char temp[16384]; + snprintf(temp, sizeof(temp), "Vulkan"); + reportingPrimaryInfo_ = "VulkanVendor"; + reportingFullInfo_ = temp; + + Reporting::UpdateConfig(); +} + +void GPU_Vulkan::InitClear() { + ScheduleEvent(GPU_EVENT_INIT_CLEAR); +} + +void GPU_Vulkan::Reinitialize() { + GPUCommon::Reinitialize(); + ScheduleEvent(GPU_EVENT_REINITIALIZE); +} + +void GPU_Vulkan::ReinitializeInternal() { + textureCache_.Clear(true); + depalShaderCache_.Clear(); + framebufferManager_->DestroyAllFBOs(); + framebufferManager_->Resized(); +} + +void GPU_Vulkan::InitClearInternal() { + bool useNonBufferedRendering = g_Config.iRenderingMode == FB_NON_BUFFERED_MODE; + if (useNonBufferedRendering) { + /* + glstate.depthWrite.set(GL_TRUE); + glstate.colorMask.set(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glClearColor(0, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + */ + } +} + +void GPU_Vulkan::DumpNextFrame() { + dumpNextFrame_ = true; +} + +void GPU_Vulkan::BeginFrame() { + ScheduleEvent(GPU_EVENT_BEGIN_FRAME); +} + +void GPU_Vulkan::UpdateVsyncInterval(bool force) { + // TODO +} + +void GPU_Vulkan::UpdateCmdInfo() { + if (g_Config.bPrescaleUV) { + cmdInfo_[GE_CMD_TEXSCALEU].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXSCALEV].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETU].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETV].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + } else { + cmdInfo_[GE_CMD_TEXSCALEU].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXSCALEV].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETU].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETV].flags |= FLAG_FLUSHBEFOREONCHANGE; + } + + cmdInfo_[GE_CMD_VERTEXTYPE].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexType; +} + +void GPU_Vulkan::ReapplyGfxStateInternal() { + GPUCommon::ReapplyGfxStateInternal(); +} + +void GPU_Vulkan::BeginFrameInternal() { +} + +void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { + host->GPUNotifyDisplay(framebuf, stride, format); + framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); +} + +bool GPU_Vulkan::FramebufferDirty() { + if (ThreadEnabled()) { + // Allow it to process fully before deciding if it's dirty. + SyncThread(); + } + + VirtualFramebuffer *vfb = framebufferManager_->GetDisplayVFB(); + if (vfb) { + bool dirty = vfb->dirtyAfterDisplay; + vfb->dirtyAfterDisplay = false; + return dirty; + } + return true; +} + +bool GPU_Vulkan::FramebufferReallyDirty() { + if (ThreadEnabled()) { + // Allow it to process fully before deciding if it's dirty. + SyncThread(); + } + + VirtualFramebuffer *vfb = framebufferManager_->GetDisplayVFB(); + if (vfb) { + bool dirty = vfb->reallyDirtyAfterDisplay; + vfb->reallyDirtyAfterDisplay = false; + return dirty; + } + return true; +} + +void GPU_Vulkan::CopyDisplayToOutput() { + ScheduleEvent(GPU_EVENT_COPY_DISPLAY_TO_OUTPUT); +} + +void GPU_Vulkan::CopyDisplayToOutputInternal() { + // Flush anything left over. + drawEngine_.Flush(curCmd_); + + shaderManager_->DirtyLastShader(); + + framebufferManager_->CopyDisplayToOutput(); + + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +// Maybe should write this in ASM... +void GPU_Vulkan::FastRunLoop(DisplayList &list) { + PROFILE_THIS_SCOPE("gpuloop"); + const CommandInfo *cmdInfo = cmdInfo_; + int dc = downcount; + for (; dc > 0; --dc) { + // We know that display list PCs have the upper nibble == 0 - no need to mask the pointer + const u32 op = *(const u32 *)(Memory::base + list.pc); + const u32 cmd = op >> 24; + const CommandInfo info = cmdInfo[cmd]; + const u8 cmdFlags = info.flags; // If we stashed the cmdFlags in the top bits of the cmdmem, we could get away with one table lookup instead of two + const u32 diff = op ^ gstate.cmdmem[cmd]; + // Inlined CheckFlushOp here to get rid of the dumpThisFrame_ check. + if ((cmdFlags & FLAG_FLUSHBEFORE) || (diff && (cmdFlags & FLAG_FLUSHBEFOREONCHANGE))) { + drawEngine_.Flush(curCmd_); + } + gstate.cmdmem[cmd] = op; // TODO: no need to write if diff==0... + if ((cmdFlags & FLAG_EXECUTE) || (diff && (cmdFlags & FLAG_EXECUTEONCHANGE))) { + downcount = dc; + (this->*info.func)(op, diff); + dc = downcount; + } + list.pc += 4; + } + downcount = 0; +} + +void GPU_Vulkan::FinishDeferred() { +} + +void GPU_Vulkan::ProcessEvent(GPUEvent ev) { + switch (ev.type) { + case GPU_EVENT_INIT_CLEAR: + InitClearInternal(); + break; + + case GPU_EVENT_BEGIN_FRAME: + BeginFrameInternal(); + break; + + case GPU_EVENT_COPY_DISPLAY_TO_OUTPUT: + CopyDisplayToOutputInternal(); + break; + + case GPU_EVENT_INVALIDATE_CACHE: + InvalidateCacheInternal(ev.invalidate_cache.addr, ev.invalidate_cache.size, ev.invalidate_cache.type); + break; + + case GPU_EVENT_FB_MEMCPY: + PerformMemoryCopyInternal(ev.fb_memcpy.dst, ev.fb_memcpy.src, ev.fb_memcpy.size); + break; + + case GPU_EVENT_FB_MEMSET: + PerformMemorySetInternal(ev.fb_memset.dst, ev.fb_memset.v, ev.fb_memset.size); + break; + + case GPU_EVENT_FB_STENCIL_UPLOAD: + PerformStencilUploadInternal(ev.fb_stencil_upload.dst, ev.fb_stencil_upload.size); + break; + + case GPU_EVENT_REINITIALIZE: + ReinitializeInternal(); + break; + + default: + GPUCommon::ProcessEvent(ev); + } +} + +inline void GPU_Vulkan::CheckFlushOp(int cmd, u32 diff) { + const u8 cmdFlags = cmdInfo_[cmd].flags; + if ((cmdFlags & FLAG_FLUSHBEFORE) || (diff && (cmdFlags & FLAG_FLUSHBEFOREONCHANGE))) { + if (dumpThisFrame_) { + NOTICE_LOG(G3D, "================ FLUSH ================"); + } + drawEngine_.Flush(curCmd_); + } +} + +void GPU_Vulkan::PreExecuteOp(u32 op, u32 diff) { + CheckFlushOp(op >> 24, diff); +} + +void GPU_Vulkan::ExecuteOp(u32 op, u32 diff) { + const u8 cmd = op >> 24; + const CommandInfo info = cmdInfo_[cmd]; + const u8 cmdFlags = info.flags; + if ((cmdFlags & FLAG_EXECUTE) || (diff && (cmdFlags & FLAG_EXECUTEONCHANGE))) { + (this->*info.func)(op, diff); + } +} + +void GPU_Vulkan::Execute_Vaddr(u32 op, u32 diff) { + gstate_c.vertexAddr = gstate_c.getRelativeAddress(op & 0x00FFFFFF); +} + +void GPU_Vulkan::Execute_Iaddr(u32 op, u32 diff) { + gstate_c.indexAddr = gstate_c.getRelativeAddress(op & 0x00FFFFFF); +} + +void GPU_Vulkan::Execute_Prim(u32 op, u32 diff) { + // This drives all drawing. All other state we just buffer up, then we apply it only + // when it's time to draw. As most PSP games set state redundantly ALL THE TIME, this is a huge optimization. + + u32 data = op & 0xFFFFFF; + u32 count = data & 0xFFFF; + GEPrimitiveType prim = static_cast(data >> 16); + + if (count == 0) + return; + + // Discard AA lines as we can't do anything that makes sense with these anyway. The SW plugin might, though. + + if (gstate.isAntiAliasEnabled()) { + // Discard AA lines in DOA + if (prim == GE_PRIM_LINE_STRIP) + return; + // Discard AA lines in Summon Night 5 + if ((prim == GE_PRIM_LINES) && gstate.isSkinningEnabled()) + return; + } + + // This also makes skipping drawing very effective. + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + drawEngine_.SetupVertexDecoder(gstate.vertType); + // Rough estimate, not sure what's correct. + int vertexCost = drawEngine_.EstimatePerVertexCost(); + cyclesExecuted += vertexCost * count; + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *inds = 0; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + inds = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + +#ifndef MOBILE_DEVICE + if (prim > GE_PRIM_RECTANGLES) { + ERROR_LOG_REPORT_ONCE(reportPrim, G3D, "Unexpected prim type: %d", prim); + } +#endif + + int bytesRead = 0; + drawEngine_.SubmitPrim(verts, inds, prim, count, gstate.vertType, &bytesRead); + + int vertexCost = drawEngine_.EstimatePerVertexCost(); + gpuStats.vertexGPUCycles += vertexCost * count; + cyclesExecuted += vertexCost * count; + + // After drawing, we advance the vertexAddr (when non indexed) or indexAddr (when indexed). + // Some games rely on this, they don't bother reloading VADDR and IADDR. + // The VADDR/IADDR registers are NOT updated. + if (inds) { + int indexSize = 1; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) == GE_VTYPE_IDX_16BIT) + indexSize = 2; + gstate_c.indexAddr += count * indexSize; + } else { + gstate_c.vertexAddr += bytesRead; + } +} + +void GPU_Vulkan::Execute_VertexType(u32 op, u32 diff) { + if (diff & (GE_VTYPE_TC_MASK | GE_VTYPE_THROUGH_MASK)) { + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); + } +} + +void GPU_Vulkan::Execute_Bezier(u32 op, u32 diff) { + // This also make skipping drawing very effective. + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + // TODO: Should this eat some cycles? Probably yes. Not sure if important. + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *indices = NULL; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + indices = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + + if (gstate.getPatchPrimitiveType() == GE_PATCHPRIM_UNKNOWN) { + ERROR_LOG_REPORT(G3D, "Unsupported patch primitive %x", gstate.getPatchPrimitiveType()); + return; + } + + if (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) { + DEBUG_LOG_REPORT(G3D, "Bezier + morph: %i", (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) >> GE_VTYPE_MORPHCOUNT_SHIFT); + } + if (vertTypeIsSkinningEnabled(gstate.vertType)) { + DEBUG_LOG_REPORT(G3D, "Bezier + skinning: %i", vertTypeGetNumBoneWeights(gstate.vertType)); + } + + GEPatchPrimType patchPrim = gstate.getPatchPrimitiveType(); + int bz_ucount = op & 0xFF; + int bz_vcount = (op >> 8) & 0xFF; + bool computeNormals = gstate.isLightingEnabled(); + bool patchFacing = gstate.patchfacing & 1; + drawEngine_.SubmitBezier(control_points, indices, gstate.getPatchDivisionU(), gstate.getPatchDivisionV(), bz_ucount, bz_vcount, patchPrim, computeNormals, patchFacing, gstate.vertType); +} + +void GPU_Vulkan::Execute_Spline(u32 op, u32 diff) { + // This also make skipping drawing very effective. + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + // TODO: Should this eat some cycles? Probably yes. Not sure if important. + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *indices = NULL; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + indices = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + + if (gstate.getPatchPrimitiveType() == GE_PATCHPRIM_UNKNOWN) { + ERROR_LOG_REPORT(G3D, "Unsupported patch primitive %x", gstate.getPatchPrimitiveType()); + return; + } + + if (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) { + DEBUG_LOG_REPORT(G3D, "Spline + morph: %i", (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) >> GE_VTYPE_MORPHCOUNT_SHIFT); + } + if (vertTypeIsSkinningEnabled(gstate.vertType)) { + DEBUG_LOG_REPORT(G3D, "Spline + skinning: %i", vertTypeGetNumBoneWeights(gstate.vertType)); + } + + int sp_ucount = op & 0xFF; + int sp_vcount = (op >> 8) & 0xFF; + int sp_utype = (op >> 16) & 0x3; + int sp_vtype = (op >> 18) & 0x3; + GEPatchPrimType patchPrim = gstate.getPatchPrimitiveType(); + bool computeNormals = gstate.isLightingEnabled(); + bool patchFacing = gstate.patchfacing & 1; + u32 vertType = gstate.vertType; + drawEngine_.SubmitSpline(control_points, indices, gstate.getPatchDivisionU(), gstate.getPatchDivisionV(), sp_ucount, sp_vcount, sp_utype, sp_vtype, patchPrim, computeNormals, patchFacing, vertType); +} + +void GPU_Vulkan::Execute_BoundingBox(u32 op, u32 diff) { + // Just resetting, nothing to bound. + const u32 data = op & 0x00FFFFFF; + if (data == 0) { + // TODO: Should this set the bboxResult? Let's set it true for now. + currentList->bboxResult = true; + return; + } + if (((data & 7) == 0) && data <= 64) { // Sanity check + void *control_points = Memory::GetPointer(gstate_c.vertexAddr); + if (gstate.vertType & GE_VTYPE_IDX_MASK) { + ERROR_LOG_REPORT_ONCE(boundingbox, G3D, "Indexed bounding box data not supported."); + // Data seems invalid. Let's assume the box test passed. + currentList->bboxResult = true; + return; + } + + // Test if the bounding box is within the drawing region. + currentList->bboxResult = drawEngine_.TestBoundingBox(control_points, data, gstate.vertType); + } else { + ERROR_LOG_REPORT_ONCE(boundingbox, G3D, "Bad bounding box data: %06x", data); + // Data seems invalid. Let's assume the box test passed. + currentList->bboxResult = true; + } +} + +void GPU_Vulkan::Execute_Region(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_Scissor(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_FramebufType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_ViewportType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_ViewportZType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + shaderManager_->DirtyUniform(DIRTY_DEPTHRANGE); +} + +void GPU_Vulkan::Execute_TexScaleU(u32 op, u32 diff) { + gstate_c.uv.uScale = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexScaleV(u32 op, u32 diff) { + gstate_c.uv.vScale = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexOffsetU(u32 op, u32 diff) { + gstate_c.uv.uOff = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexOffsetV(u32 op, u32 diff) { + gstate_c.uv.vOff = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexAddr0(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexAddrN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexBufw0(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_TexBufwN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexSize0(u32 op, u32 diff) { + // Render to texture may have overridden the width/height. + // Don't reset it unless the size is different / the texture has changed. + if (diff || gstate_c.textureChanged != TEXCHANGE_UNCHANGED) { + gstate_c.curTextureWidth = gstate.getTextureWidth(0); + gstate_c.curTextureHeight = gstate.getTextureHeight(0); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); + // We will need to reset the texture now. + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + } +} + +void GPU_Vulkan::Execute_TexSizeN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexFormat(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_TexMapMode(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexParamType(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexEnvColor(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_TEXENV); +} + +void GPU_Vulkan::Execute_TexLevel(u32 op, u32 diff) { + // I had hoped that this would let us avoid excessively flushing in Gran Turismo, but not so, + // as the game switches rapidly between modes 0 and 1. + /* + if (gstate.getTexLevelMode() == GE_TEXLEVEL_MODE_CONST) { + gstate.texlevel ^= diff; + Flush(); + gstate.texlevel ^= diff; + } + */ + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_LoadClut(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + textureCache_.LoadClut(gstate.getClutAddress(), gstate.getClutLoadBytes()); + // This could be used to "dirty" textures with clut. +} + +void GPU_Vulkan::Execute_ClutFormat(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + // This could be used to "dirty" textures with clut. +} + +void GPU_Vulkan::Execute_Ambient(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_AMBIENT); +} + +void GPU_Vulkan::Execute_MaterialDiffuse(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATDIFFUSE); +} + +void GPU_Vulkan::Execute_MaterialEmissive(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATEMISSIVE); +} + +void GPU_Vulkan::Execute_MaterialAmbient(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATAMBIENTALPHA); +} + +void GPU_Vulkan::Execute_MaterialSpecular(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATSPECULAR); +} + +void GPU_Vulkan::Execute_Light0Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT0); +} + +void GPU_Vulkan::Execute_Light1Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT1); +} + +void GPU_Vulkan::Execute_Light2Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT2); +} + +void GPU_Vulkan::Execute_Light3Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT3); +} + +void GPU_Vulkan::Execute_FogColor(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_FOGCOLOR); +} + +void GPU_Vulkan::Execute_FogCoef(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_FOGCOEF); +} + +void GPU_Vulkan::Execute_ColorTestMask(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORMASK); +} + +void GPU_Vulkan::Execute_AlphaTest(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORREF); + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORMASK); +} + +void GPU_Vulkan::Execute_StencilTest(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_STENCILREPLACEVALUE); +} + +void GPU_Vulkan::Execute_ColorRef(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORREF); +} + +void GPU_Vulkan::Execute_WorldMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_WORLDMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.worldMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_WORLDMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_WORLDMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_WorldMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.worldmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.worldMatrix)[num]) { + Flush(); + ((u32 *)gstate.worldMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_WORLDMATRIX); + } + num++; + gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_ViewMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_VIEWMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.viewMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_VIEWMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_VIEWMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_ViewMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.viewmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.viewMatrix)[num]) { + Flush(); + ((u32 *)gstate.viewMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_VIEWMATRIX); + } + num++; + gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_ProjMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_PROJMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.projMatrix + (op & 0xF)); + const int end = 16 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_PROJMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_ProjMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.projmtxnum & 0xF; + u32 newVal = op << 8; + if (newVal != ((const u32 *)gstate.projMatrix)[num]) { + Flush(); + ((u32 *)gstate.projMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + num++; + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_TgenMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_TGENMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.tgenMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_TGENMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_TEXMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_TgenMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.texmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.tgenMatrix)[num]) { + Flush(); + ((u32 *)gstate.tgenMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_TEXMATRIX); + } + num++; + gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_BoneMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_BONEMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.boneMatrix + (op & 0x7F)); + const int end = 12 * 8 - (op & 0x7F); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + } + if (++i >= end) { + break; + } + } + + const int numPlusCount = (op & 0x7F) + i; + for (int num = op & 0x7F; num < numPlusCount; num += 12) { + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); + } + + const int count = i; + gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | ((op + count) & 0x7F); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_BoneMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.boneMatrixNumber & 0x7F; + u32 newVal = op << 8; + if (num < 96 && newVal != ((const u32 *)gstate.boneMatrix)[num]) { + Flush(); + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); + ((u32 *)gstate.boneMatrix)[num] = newVal; + } + num++; + gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); +} + +void GPU_Vulkan::Execute_BlockTransferStart(u32 op, u32 diff) { + // TODO: Here we should check if the transfer overlaps a framebuffer or any textures, + // and take appropriate action. This is a block transfer between RAM and VRAM, or vice versa. + // Can we skip this on SkipDraw? + DoBlockTransfer(gstate_c.skipDrawReason); + + // Fixes Gran Turismo's funky text issue, since it overwrites the current texture. + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_Generic(u32 op, u32 diff) { + u32 cmd = op >> 24; + u32 data = op & 0xFFFFFF; + + // Handle control and drawing commands here directly. The others we delegate. + switch (cmd) { + case GE_CMD_BASE: + break; + + case GE_CMD_VADDR: + Execute_Vaddr(op, diff); + break; + + case GE_CMD_IADDR: + Execute_Iaddr(op, diff); + break; + + case GE_CMD_PRIM: + Execute_Prim(op, diff); + break; + + // The arrow and other rotary items in Puzbob are bezier patches, strangely enough. + case GE_CMD_BEZIER: + Execute_Bezier(op, diff); + break; + + case GE_CMD_SPLINE: + Execute_Spline(op, diff); + break; + + case GE_CMD_BOUNDINGBOX: + Execute_BoundingBox(op, diff); + break; + + case GE_CMD_VERTEXTYPE: + Execute_VertexType(op, diff); + break; + + case GE_CMD_REGION1: + case GE_CMD_REGION2: + Execute_Region(op, diff); + break; + + case GE_CMD_CLIPENABLE: + //we always clip, this is opengl + break; + + case GE_CMD_CULLFACEENABLE: + case GE_CMD_CULL: + break; + + case GE_CMD_TEXTUREMAPENABLE: + // Don't need to dirty the texture here, already dirtied at list start/etc. + break; + + case GE_CMD_LIGHTINGENABLE: + break; + + case GE_CMD_FOGCOLOR: + Execute_FogColor(op, diff); + break; + + case GE_CMD_FOG1: + case GE_CMD_FOG2: + Execute_FogCoef(op, diff); + break; + + case GE_CMD_FOGENABLE: + break; + + case GE_CMD_DITHERENABLE: + break; + + case GE_CMD_OFFSETX: + break; + + case GE_CMD_OFFSETY: + break; + + case GE_CMD_TEXSCALEU: + Execute_TexScaleU(op, diff); + break; + + case GE_CMD_TEXSCALEV: + Execute_TexScaleV(op, diff); + break; + + case GE_CMD_TEXOFFSETU: + Execute_TexOffsetU(op, diff); + break; + + case GE_CMD_TEXOFFSETV: + Execute_TexOffsetV(op, diff); + break; + + case GE_CMD_SCISSOR1: + case GE_CMD_SCISSOR2: + Execute_Scissor(op, diff); + break; + + /// + case GE_CMD_MINZ: + case GE_CMD_MAXZ: + break; + + case GE_CMD_FRAMEBUFPTR: + case GE_CMD_FRAMEBUFWIDTH: + case GE_CMD_FRAMEBUFPIXFORMAT: + Execute_FramebufType(op, diff); + break; + + case GE_CMD_TEXADDR0: + Execute_TexAddr0(op, diff); + break; + + case GE_CMD_TEXADDR1: + case GE_CMD_TEXADDR2: + case GE_CMD_TEXADDR3: + case GE_CMD_TEXADDR4: + case GE_CMD_TEXADDR5: + case GE_CMD_TEXADDR6: + case GE_CMD_TEXADDR7: + Execute_TexAddrN(op, diff); + break; + + case GE_CMD_TEXBUFWIDTH0: + Execute_TexBufw0(op, diff); + break; + + case GE_CMD_TEXBUFWIDTH1: + case GE_CMD_TEXBUFWIDTH2: + case GE_CMD_TEXBUFWIDTH3: + case GE_CMD_TEXBUFWIDTH4: + case GE_CMD_TEXBUFWIDTH5: + case GE_CMD_TEXBUFWIDTH6: + case GE_CMD_TEXBUFWIDTH7: + Execute_TexBufwN(op, diff); + break; + + case GE_CMD_CLUTFORMAT: + Execute_ClutFormat(op, diff); + break; + + case GE_CMD_CLUTADDR: + case GE_CMD_CLUTADDRUPPER: + // Hm, LOADCLUT actually changes the CLUT so no need to dirty here. + break; + + case GE_CMD_LOADCLUT: + Execute_LoadClut(op, diff); + break; + + case GE_CMD_TEXMAPMODE: + Execute_TexMapMode(op, diff); + break; + + case GE_CMD_TEXSHADELS: + break; + + case GE_CMD_TRANSFERSRC: + case GE_CMD_TRANSFERSRCW: + case GE_CMD_TRANSFERDST: + case GE_CMD_TRANSFERDSTW: + case GE_CMD_TRANSFERSRCPOS: + case GE_CMD_TRANSFERDSTPOS: + break; + + case GE_CMD_TRANSFERSIZE: + break; + + case GE_CMD_TRANSFERSTART: // Orphis calls this TRXKICK + Execute_BlockTransferStart(op, diff); + break; + + case GE_CMD_TEXSIZE0: + Execute_TexSize0(op, diff); + break; + + case GE_CMD_TEXSIZE1: + case GE_CMD_TEXSIZE2: + case GE_CMD_TEXSIZE3: + case GE_CMD_TEXSIZE4: + case GE_CMD_TEXSIZE5: + case GE_CMD_TEXSIZE6: + case GE_CMD_TEXSIZE7: + Execute_TexSizeN(op, diff); + break; + + case GE_CMD_ZBUFPTR: + case GE_CMD_ZBUFWIDTH: + break; + + case GE_CMD_AMBIENTCOLOR: + case GE_CMD_AMBIENTALPHA: + Execute_Ambient(op, diff); + break; + + case GE_CMD_MATERIALDIFFUSE: + Execute_MaterialDiffuse(op, diff); + break; + + case GE_CMD_MATERIALEMISSIVE: + Execute_MaterialEmissive(op, diff); + break; + + case GE_CMD_MATERIALAMBIENT: + case GE_CMD_MATERIALALPHA: + Execute_MaterialAmbient(op, diff); + break; + + case GE_CMD_MATERIALSPECULAR: + case GE_CMD_MATERIALSPECULARCOEF: + Execute_MaterialSpecular(op, diff); + break; + + case GE_CMD_LIGHTTYPE0: + case GE_CMD_LIGHTTYPE1: + case GE_CMD_LIGHTTYPE2: + case GE_CMD_LIGHTTYPE3: + break; + + case GE_CMD_LX0:case GE_CMD_LY0:case GE_CMD_LZ0: + case GE_CMD_LDX0:case GE_CMD_LDY0:case GE_CMD_LDZ0: + case GE_CMD_LKA0:case GE_CMD_LKB0:case GE_CMD_LKC0: + case GE_CMD_LKS0: // spot coef ("conv") + case GE_CMD_LKO0: // light angle ("cutoff") + case GE_CMD_LAC0: + case GE_CMD_LDC0: + case GE_CMD_LSC0: + Execute_Light0Param(op, diff); + break; + case GE_CMD_LX1:case GE_CMD_LY1:case GE_CMD_LZ1: + case GE_CMD_LDX1:case GE_CMD_LDY1:case GE_CMD_LDZ1: + case GE_CMD_LKA1:case GE_CMD_LKB1:case GE_CMD_LKC1: + case GE_CMD_LKS1: + case GE_CMD_LKO1: + case GE_CMD_LAC1: + case GE_CMD_LDC1: + case GE_CMD_LSC1: + Execute_Light1Param(op, diff); + break; + case GE_CMD_LX2:case GE_CMD_LY2:case GE_CMD_LZ2: + case GE_CMD_LDX2:case GE_CMD_LDY2:case GE_CMD_LDZ2: + case GE_CMD_LKA2:case GE_CMD_LKB2:case GE_CMD_LKC2: + case GE_CMD_LKS2: + case GE_CMD_LKO2: + case GE_CMD_LAC2: + case GE_CMD_LDC2: + case GE_CMD_LSC2: + Execute_Light2Param(op, diff); + break; + case GE_CMD_LX3:case GE_CMD_LY3:case GE_CMD_LZ3: + case GE_CMD_LDX3:case GE_CMD_LDY3:case GE_CMD_LDZ3: + case GE_CMD_LKA3:case GE_CMD_LKB3:case GE_CMD_LKC3: + case GE_CMD_LKS3: + case GE_CMD_LKO3: + case GE_CMD_LAC3: + case GE_CMD_LDC3: + case GE_CMD_LSC3: + Execute_Light3Param(op, diff); + break; + + case GE_CMD_VIEWPORTXSCALE: + case GE_CMD_VIEWPORTYSCALE: + case GE_CMD_VIEWPORTXCENTER: + case GE_CMD_VIEWPORTYCENTER: + case GE_CMD_VIEWPORTZSCALE: + case GE_CMD_VIEWPORTZCENTER: + Execute_ViewportType(op, diff); + break; + + case GE_CMD_LIGHTENABLE0: + case GE_CMD_LIGHTENABLE1: + case GE_CMD_LIGHTENABLE2: + case GE_CMD_LIGHTENABLE3: + break; + + case GE_CMD_SHADEMODE: + break; + + case GE_CMD_PATCHDIVISION: + case GE_CMD_PATCHPRIMITIVE: + case GE_CMD_PATCHFACING: + break; + + + case GE_CMD_MATERIALUPDATE: + break; + + ////////////////////////////////////////////////////////////////// + // CLEARING + ////////////////////////////////////////////////////////////////// + case GE_CMD_CLEARMODE: + break; + + ////////////////////////////////////////////////////////////////// + // ALPHA BLENDING + ////////////////////////////////////////////////////////////////// + case GE_CMD_ALPHABLENDENABLE: + case GE_CMD_BLENDMODE: + break; + + case GE_CMD_BLENDFIXEDA: + case GE_CMD_BLENDFIXEDB: + break; + + case GE_CMD_ALPHATESTENABLE: + case GE_CMD_COLORTESTENABLE: + // They are done in the fragment shader. + break; + + case GE_CMD_COLORTEST: + break; + + case GE_CMD_COLORTESTMASK: + Execute_ColorTestMask(op, diff); + break; + + case GE_CMD_ALPHATEST: + Execute_AlphaTest(op, diff); + break; + + case GE_CMD_COLORREF: + Execute_ColorRef(op, diff); + break; + + case GE_CMD_TEXENVCOLOR: + Execute_TexEnvColor(op, diff); + break; + + case GE_CMD_TEXFUNC: + case GE_CMD_TEXFLUSH: + break; + + case GE_CMD_TEXFORMAT: + Execute_TexFormat(op, diff); + break; + + case GE_CMD_TEXMODE: + case GE_CMD_TEXFILTER: + case GE_CMD_TEXWRAP: + Execute_TexParamType(op, diff); + break; + + ////////////////////////////////////////////////////////////////// + // DEPTH TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_ZTESTENABLE: + case GE_CMD_ZTEST: + case GE_CMD_ZWRITEDISABLE: + break; + + case GE_CMD_MORPHWEIGHT0: + case GE_CMD_MORPHWEIGHT1: + case GE_CMD_MORPHWEIGHT2: + case GE_CMD_MORPHWEIGHT3: + case GE_CMD_MORPHWEIGHT4: + case GE_CMD_MORPHWEIGHT5: + case GE_CMD_MORPHWEIGHT6: + case GE_CMD_MORPHWEIGHT7: + gstate_c.morphWeights[cmd - GE_CMD_MORPHWEIGHT0] = getFloat24(data); + break; + + case GE_CMD_DITH0: + case GE_CMD_DITH1: + case GE_CMD_DITH2: + case GE_CMD_DITH3: + break; + + case GE_CMD_WORLDMATRIXNUMBER: + Execute_WorldMtxNum(op, diff); + break; + + case GE_CMD_WORLDMATRIXDATA: + Execute_WorldMtxData(op, diff); + break; + + case GE_CMD_VIEWMATRIXNUMBER: + Execute_ViewMtxNum(op, diff); + break; + + case GE_CMD_VIEWMATRIXDATA: + Execute_ViewMtxData(op, diff); + break; + + case GE_CMD_PROJMATRIXNUMBER: + Execute_ProjMtxNum(op, diff); + break; + + case GE_CMD_PROJMATRIXDATA: + Execute_ProjMtxData(op, diff); + break; + + case GE_CMD_TGENMATRIXNUMBER: + Execute_TgenMtxNum(op, diff); + break; + + case GE_CMD_TGENMATRIXDATA: + Execute_TgenMtxData(op, diff); + break; + + case GE_CMD_BONEMATRIXNUMBER: + Execute_BoneMtxNum(op, diff); + break; + + case GE_CMD_BONEMATRIXDATA: + Execute_BoneMtxData(op, diff); + break; + +#ifndef MOBILE_DEVICE + case GE_CMD_ANTIALIASENABLE: + if (data != 0) + WARN_LOG_REPORT_ONCE(antiAlias, G3D, "Unsupported antialias enabled: %06x", data); + break; + + case GE_CMD_TEXLODSLOPE: + if (data != 0) + WARN_LOG_REPORT_ONCE(texLodSlope, G3D, "Unsupported texture lod slope: %06x", data); + break; +#endif + + case GE_CMD_TEXLEVEL: + Execute_TexLevel(op, diff); + break; + + ////////////////////////////////////////////////////////////////// + // STENCIL TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_STENCILTEST: + Execute_StencilTest(op, diff); + break; + + case GE_CMD_STENCILTESTENABLE: + case GE_CMD_STENCILOP: + break; + + case GE_CMD_MASKRGB: + case GE_CMD_MASKALPHA: + break; + + case GE_CMD_REVERSENORMAL: + break; + + case GE_CMD_VSCX: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscx, G3D, "Unsupported Vertex Screen Coordinate X : %06x", data); + break; + + case GE_CMD_VSCY: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscy, G3D, "Unsupported Vertex Screen Coordinate Y : %06x", data); + break; + + case GE_CMD_VSCZ: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscz, G3D, "Unsupported Vertex Screen Coordinate Z : %06x", data); + break; + + case GE_CMD_VTCS: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtcs, G3D, "Unsupported Vertex Texture Coordinate S : %06x", data); + break; + + case GE_CMD_VTCT: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtct, G3D, "Unsupported Vertex Texture Coordinate T : %06x", data); + break; + + case GE_CMD_VTCQ: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtcq, G3D, "Unsupported Vertex Texture Coordinate Q : %06x", data); + break; + + case GE_CMD_VCV: + if (data != 0) + WARN_LOG_REPORT_ONCE(vcv, G3D, "Unsupported Vertex Color Value : %06x", data); + break; + + case GE_CMD_VAP: + if (data != 0) + WARN_LOG_REPORT_ONCE(vap, G3D, "Unsupported Vertex Alpha and Primitive : %06x", data); + break; + + case GE_CMD_VFC: + if (data != 0) + WARN_LOG_REPORT_ONCE(vfc, G3D, "Unsupported Vertex Fog Coefficient : %06x", data); + break; + + case GE_CMD_VSCV: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscv, G3D, "Unsupported Vertex Secondary Color Value : %06x", data); + break; + + + case GE_CMD_UNKNOWN_03: + case GE_CMD_UNKNOWN_0D: + case GE_CMD_UNKNOWN_11: + case GE_CMD_UNKNOWN_29: + case GE_CMD_UNKNOWN_34: + case GE_CMD_UNKNOWN_35: + case GE_CMD_UNKNOWN_39: + case GE_CMD_UNKNOWN_4E: + case GE_CMD_UNKNOWN_4F: + case GE_CMD_UNKNOWN_52: + case GE_CMD_UNKNOWN_59: + case GE_CMD_UNKNOWN_5A: + case GE_CMD_UNKNOWN_B6: + case GE_CMD_UNKNOWN_B7: + case GE_CMD_UNKNOWN_D1: + case GE_CMD_UNKNOWN_ED: + case GE_CMD_UNKNOWN_EF: + case GE_CMD_UNKNOWN_FA: + case GE_CMD_UNKNOWN_FB: + case GE_CMD_UNKNOWN_FC: + case GE_CMD_UNKNOWN_FD: + case GE_CMD_UNKNOWN_FE: + if (data != 0) + WARN_LOG_REPORT_ONCE(unknowncmd, G3D, "Unknown GE command : %08x ", op); + break; + case GE_CMD_UNKNOWN_FF: + // This is hit in quite a few games, supposedly it is a no-op. + // Might be used for debugging or something? + break; + + default: + GPUCommon::ExecuteOp(op, diff); + break; + } +} + +void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { + const int num = gstate.boneMatrixNumber & 0x7F; + const int mtxNum = num / 12; + uint32_t uniformsToDirty = DIRTY_BONEMATRIX0 << mtxNum; + if ((num - 12 * mtxNum) != 0) { + uniformsToDirty |= DIRTY_BONEMATRIX0 << ((mtxNum + 1) & 7); + } + Flush(); + shaderManager_->DirtyUniform(uniformsToDirty); + gstate.FastLoadBoneMatrix(target); +} + +void GPU_Vulkan::DeviceLost() { + // TODO +} + +void GPU_Vulkan::UpdateStats() { + gpuStats.numVertexShaders = shaderManager_->GetNumVertexShaders(); + gpuStats.numFragmentShaders = shaderManager_->GetNumFragmentShaders(); + gpuStats.numShaders = pipelineManager_->GetNumPipelines(); + gpuStats.numTextures = (int)textureCache_.NumLoadedTextures(); + gpuStats.numFBOs = (int)framebufferManager_->NumVFBs(); +} + +void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { + // TODO: This is used a lot to copy data around between render targets and textures, + // and also to quickly load textures from RAM to VRAM. So we should do checks like the following: + // * Does dstBasePtr point to an existing texture? If so maybe reload it immediately. + // + // * Does srcBasePtr point to a render target, and dstBasePtr to a texture? If so + // either copy between rt and texture or reassign the texture to point to the render target + // + // etc.... + + u32 srcBasePtr = gstate.getTransferSrcAddress(); + u32 srcStride = gstate.getTransferSrcStride(); + + u32 dstBasePtr = gstate.getTransferDstAddress(); + u32 dstStride = gstate.getTransferDstStride(); + + int srcX = gstate.getTransferSrcX(); + int srcY = gstate.getTransferSrcY(); + + int dstX = gstate.getTransferDstX(); + int dstY = gstate.getTransferDstY(); + + int width = gstate.getTransferWidth(); + int height = gstate.getTransferHeight(); + + int bpp = gstate.getTransferBpp(); + + DEBUG_LOG(G3D, "Block transfer: %08x/%x -> %08x/%x, %ix%ix%i (%i,%i)->(%i,%i)", srcBasePtr, srcStride, dstBasePtr, dstStride, width, height, bpp, srcX, srcY, dstX, dstY); + + if (!Memory::IsValidAddress(srcBasePtr)) { + ERROR_LOG_REPORT(G3D, "BlockTransfer: Bad source transfer address %08x!", srcBasePtr); + return; + } + + if (!Memory::IsValidAddress(dstBasePtr)) { + ERROR_LOG_REPORT(G3D, "BlockTransfer: Bad destination transfer address %08x!", dstBasePtr); + return; + } + + // Check that the last address of both source and dest are valid addresses + + u32 srcLastAddr = srcBasePtr + ((srcY + height - 1) * srcStride + (srcX + width - 1)) * bpp; + u32 dstLastAddr = dstBasePtr + ((dstY + height - 1) * dstStride + (dstX + width - 1)) * bpp; + + if (!Memory::IsValidAddress(srcLastAddr)) { + ERROR_LOG_REPORT(G3D, "Bottom-right corner of source of block transfer is at an invalid address: %08x", srcLastAddr); + return; + } + if (!Memory::IsValidAddress(dstLastAddr)) { + ERROR_LOG_REPORT(G3D, "Bottom-right corner of destination of block transfer is at an invalid address: %08x", srcLastAddr); + return; + } + + // Tell the framebuffer manager to take action if possible. If it does the entire thing, let's just return. + if (!framebufferManager_->NotifyBlockTransferBefore(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason)) { + // Do the copy! (Hm, if we detect a drawn video frame (see below) then we could maybe skip this?) + // Can use GetPointerUnchecked because we checked the addresses above. We could also avoid them + // entirely by walking a couple of pointers... + if (srcStride == dstStride && (u32)width == srcStride) { + // Common case in God of War, let's do it all in one chunk. + u32 srcLineStartAddr = srcBasePtr + (srcY * srcStride + srcX) * bpp; + u32 dstLineStartAddr = dstBasePtr + (dstY * dstStride + dstX) * bpp; + const u8 *src = Memory::GetPointerUnchecked(srcLineStartAddr); + u8 *dst = Memory::GetPointerUnchecked(dstLineStartAddr); + memcpy(dst, src, width * height * bpp); + } else { + for (int y = 0; y < height; y++) { + u32 srcLineStartAddr = srcBasePtr + ((y + srcY) * srcStride + srcX) * bpp; + u32 dstLineStartAddr = dstBasePtr + ((y + dstY) * dstStride + dstX) * bpp; + + const u8 *src = Memory::GetPointerUnchecked(srcLineStartAddr); + u8 *dst = Memory::GetPointerUnchecked(dstLineStartAddr); + memcpy(dst, src, width * bpp); + } + } + + textureCache_.Invalidate(dstBasePtr + (dstY * dstStride + dstX) * bpp, height * dstStride * bpp, GPU_INVALIDATE_HINT); + framebufferManager_->NotifyBlockTransferAfter(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason); + } + +#ifndef MOBILE_DEVICE + CBreakPoints::ExecMemCheck(srcBasePtr + (srcY * srcStride + srcX) * bpp, false, height * srcStride * bpp, currentMIPS->pc); + CBreakPoints::ExecMemCheck(dstBasePtr + (srcY * dstStride + srcX) * bpp, true, height * dstStride * bpp, currentMIPS->pc); +#endif + + // TODO: Correct timing appears to be 1.9, but erring a bit low since some of our other timing is inaccurate. + cyclesExecuted += ((height * width * bpp) * 16) / 10; +} + +void GPU_Vulkan::InvalidateCache(u32 addr, int size, GPUInvalidationType type) { + GPUEvent ev(GPU_EVENT_INVALIDATE_CACHE); + ev.invalidate_cache.addr = addr; + ev.invalidate_cache.size = size; + ev.invalidate_cache.type = type; + ScheduleEvent(ev); +} + +void GPU_Vulkan::InvalidateCacheInternal(u32 addr, int size, GPUInvalidationType type) { + if (size > 0) + textureCache_.Invalidate(addr, size, type); + else + textureCache_.InvalidateAll(type); + + if (type != GPU_INVALIDATE_ALL && framebufferManager_->MayIntersectFramebuffer(addr)) { + // If we're doing block transfers, we shouldn't need this, and it'll only confuse us. + // Vempire invalidates (with writeback) after drawing, but before blitting. + if (!g_Config.bBlockTransferGPU || type == GPU_INVALIDATE_SAFE) { + framebufferManager_->UpdateFromMemory(addr, size, type == GPU_INVALIDATE_SAFE); + } + } +} + +void GPU_Vulkan::PerformMemoryCopyInternal(u32 dest, u32 src, int size) { + if (!framebufferManager_->NotifyFramebufferCopy(src, dest, size, false, gstate_c.skipDrawReason)) { + // We use a little hack for Download/Upload using a VRAM mirror. + // Since they're identical we don't need to copy. + if (!Memory::IsVRAMAddress(dest) || (dest ^ 0x00400000) != src) { + Memory::Memcpy(dest, src, size); + } + } + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); +} + +void GPU_Vulkan::PerformMemorySetInternal(u32 dest, u8 v, int size) { + if (!framebufferManager_->NotifyFramebufferCopy(dest, dest, size, true, gstate_c.skipDrawReason)) { + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + } +} + +void GPU_Vulkan::PerformStencilUploadInternal(u32 dest, int size) { + framebufferManager_->NotifyStencilUpload(dest, size); +} + +bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { + // Track stray copies of a framebuffer in RAM. MotoGP does this. + if (framebufferManager_->MayIntersectFramebuffer(src) || framebufferManager_->MayIntersectFramebuffer(dest)) { + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_MEMCPY); + ev.fb_memcpy.dst = dest; + ev.fb_memcpy.src = src; + ev.fb_memcpy.size = size; + ScheduleEvent(ev); + + // This is a memcpy, so we need to wait for it to complete. + SyncThread(); + } else { + PerformMemoryCopyInternal(dest, src, size); + } + return true; + } + + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + return false; +} + +bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { + // This may indicate a memset, usually to 0, of a framebuffer. + if (framebufferManager_->MayIntersectFramebuffer(dest)) { + Memory::Memset(dest, v, size); + + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_MEMSET); + ev.fb_memset.dst = dest; + ev.fb_memset.v = v; + ev.fb_memset.size = size; + ScheduleEvent(ev); + + // We don't need to wait for the framebuffer to be updated. + } else { + PerformMemorySetInternal(dest, v, size); + } + return true; + } + + // Or perhaps a texture, let's invalidate. + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + return false; +} + +void GPU_Vulkan::NotifyVideoUpload(u32 addr, int size, int width, int format) { + +} + +bool GPU_Vulkan::PerformMemoryDownload(u32 dest, int size) { + // Cheat a bit to force a download of the framebuffer. + // VRAM + 0x00400000 is simply a VRAM mirror. + if (Memory::IsVRAMAddress(dest)) { + return PerformMemoryCopy(dest ^ 0x00400000, dest, size); + } + return false; +} + +bool GPU_Vulkan::PerformMemoryUpload(u32 dest, int size) { + // Cheat a bit to force an upload of the framebuffer. + // VRAM + 0x00400000 is simply a VRAM mirror. + if (Memory::IsVRAMAddress(dest)) { + return PerformMemoryCopy(dest, dest ^ 0x00400000, size); + } + return false; +} + +bool GPU_Vulkan::PerformStencilUpload(u32 dest, int size) { + if (framebufferManager_->MayIntersectFramebuffer(dest)) { + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_STENCIL_UPLOAD); + ev.fb_stencil_upload.dst = dest; + ev.fb_stencil_upload.size = size; + ScheduleEvent(ev); + } else { + PerformStencilUploadInternal(dest, size); + } + return true; + } + return false; +} + +void GPU_Vulkan::ClearCacheNextFrame() { + textureCache_.ClearNextFrame(); +} + +void GPU_Vulkan::Resized() { + resized_ = true; + framebufferManager_->Resized(); +} + +void GPU_Vulkan::ClearShaderCache() { + // TODO +} + +std::vector GPU_Vulkan::GetFramebufferList() { + return framebufferManager_->GetFramebufferList(); +} + +void GPU_Vulkan::DoState(PointerWrap &p) { + GPUCommon::DoState(p); + + // TODO: Some of these things may not be necessary. + // None of these are necessary when saving. + // In Freeze-Frame mode, we don't want to do any of this. + if (p.mode == p.MODE_READ && !PSP_CoreParameter().frozen) { + textureCache_.Clear(true); + depalShaderCache_.Clear(); + + gstate_c.textureChanged = TEXCHANGE_UPDATED; + framebufferManager_->DestroyAllFBOs(); + shaderManager_->ClearShaders(); + pipelineManager_->Clear(); + } +} + +bool GPU_Vulkan::GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices) { + return drawEngine_.GetCurrentSimpleVertices(count, vertices, indices); +} + +bool GPU_Vulkan::DescribeCodePtr(const u8 *ptr, std::string &name) { + if (drawEngine_.IsCodePtrVertexDecoder(ptr)) { + name = "VertexDecoderJit"; + return true; + } + return false; +} + +std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { + if (type == SHADER_TYPE_VERTEXLOADER) { + return drawEngine_.DebugGetVertexLoaderIDs(); + } else if (type == SHADER_TYPE_PIPELINE) { + return pipelineManager_->DebugGetObjectIDs(type); + } else { + return shaderManager_->DebugGetShaderIDs(type); + } +} + +std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + if (type == SHADER_TYPE_VERTEXLOADER) { + return drawEngine_.DebugGetVertexLoaderString(id, stringType); + } else if (type == SHADER_TYPE_PIPELINE) { + return pipelineManager_->DebugGetObjectString(id, type, stringType); + } else { + return shaderManager_->DebugGetShaderString(id, type, stringType); + } +} diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h new file mode 100644 index 0000000000..45d60b43bf --- /dev/null +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -0,0 +1,198 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include +#include + +#include "GPU/GPUCommon.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" + +class FramebufferManagerVulkan; +class ShaderManagerVulkan; +class LinkedShader; + +class GPU_Vulkan : public GPUCommon { +public: + GPU_Vulkan(GraphicsContext *ctx); + ~GPU_Vulkan(); + + // This gets called on startup and when we get back from settings. + void CheckGPUFeatures(); + + // These are where we can reset command buffers etc. + void BeginHostFrame(); + void EndHostFrame(); + + void InitClear() override; + void Reinitialize() override; + void PreExecuteOp(u32 op, u32 diff) override; + void Execute_Generic(u32 op, u32 diff); + void ExecuteOp(u32 op, u32 diff) override; + + void ReapplyGfxStateInternal() override; + void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; + void CopyDisplayToOutput() override; + void NotifyVideoUpload(u32 addr, int size, int width, int format) override; + void BeginFrame() override; + void UpdateStats() override; + void InvalidateCache(u32 addr, int size, GPUInvalidationType type) override; + bool PerformMemoryCopy(u32 dest, u32 src, int size) override; + bool PerformMemorySet(u32 dest, u8 v, int size) override; + bool PerformMemoryDownload(u32 dest, int size) override; + bool PerformMemoryUpload(u32 dest, int size) override; + bool PerformStencilUpload(u32 dest, int size) override; + void ClearCacheNextFrame() override; + void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. + + void DumpNextFrame() override; + void DoState(PointerWrap &p) override; + + // Called by the window system if the window size changed. This will be reflected in PSPCoreParam.pixel*. + void Resized() override; + void ClearShaderCache() override; + bool DecodeTexture(u8 *dest, const GPUgstate &state) override { + return false; + } + bool FramebufferDirty() override; + bool FramebufferReallyDirty() override; + + void GetReportingInfo(std::string &primaryInfo, std::string &fullInfo) override { + primaryInfo = reportingPrimaryInfo_; + fullInfo = reportingFullInfo_; + } + + typedef void (GPU_Vulkan::*CmdFunc)(u32 op, u32 diff); + struct CommandInfo { + u8 flags; + GPU_Vulkan::CmdFunc func; + }; + + void Execute_Vaddr(u32 op, u32 diff); + void Execute_Iaddr(u32 op, u32 diff); + void Execute_Prim(u32 op, u32 diff); + void Execute_Bezier(u32 op, u32 diff); + void Execute_Spline(u32 op, u32 diff); + void Execute_BoundingBox(u32 op, u32 diff); + void Execute_VertexType(u32 op, u32 diff); + void Execute_VertexTypeSkinning(u32 op, u32 diff); + void Execute_Region(u32 op, u32 diff); + void Execute_Scissor(u32 op, u32 diff); + void Execute_FramebufType(u32 op, u32 diff); + void Execute_ViewportType(u32 op, u32 diff); + void Execute_ViewportZType(u32 op, u32 diff); + void Execute_TexScaleU(u32 op, u32 diff); + void Execute_TexScaleV(u32 op, u32 diff); + void Execute_TexOffsetU(u32 op, u32 diff); + void Execute_TexOffsetV(u32 op, u32 diff); + void Execute_TexAddr0(u32 op, u32 diff); + void Execute_TexAddrN(u32 op, u32 diff); + void Execute_TexBufw0(u32 op, u32 diff); + void Execute_TexBufwN(u32 op, u32 diff); + void Execute_TexSize0(u32 op, u32 diff); + void Execute_TexSizeN(u32 op, u32 diff); + void Execute_TexFormat(u32 op, u32 diff); + void Execute_TexMapMode(u32 op, u32 diff); + void Execute_TexParamType(u32 op, u32 diff); + void Execute_TexEnvColor(u32 op, u32 diff); + void Execute_TexLevel(u32 op, u32 diff); + void Execute_LoadClut(u32 op, u32 diff); + void Execute_ClutFormat(u32 op, u32 diff); + void Execute_Ambient(u32 op, u32 diff); + void Execute_MaterialDiffuse(u32 op, u32 diff); + void Execute_MaterialEmissive(u32 op, u32 diff); + void Execute_MaterialAmbient(u32 op, u32 diff); + void Execute_MaterialSpecular(u32 op, u32 diff); + void Execute_Light0Param(u32 op, u32 diff); + void Execute_Light1Param(u32 op, u32 diff); + void Execute_Light2Param(u32 op, u32 diff); + void Execute_Light3Param(u32 op, u32 diff); + void Execute_FogColor(u32 op, u32 diff); + void Execute_FogCoef(u32 op, u32 diff); + void Execute_ColorTestMask(u32 op, u32 diff); + void Execute_AlphaTest(u32 op, u32 diff); + void Execute_StencilTest(u32 op, u32 diff); + void Execute_ColorRef(u32 op, u32 diff); + void Execute_WorldMtxNum(u32 op, u32 diff); + void Execute_WorldMtxData(u32 op, u32 diff); + void Execute_ViewMtxNum(u32 op, u32 diff); + void Execute_ViewMtxData(u32 op, u32 diff); + void Execute_ProjMtxNum(u32 op, u32 diff); + void Execute_ProjMtxData(u32 op, u32 diff); + void Execute_TgenMtxNum(u32 op, u32 diff); + void Execute_TgenMtxData(u32 op, u32 diff); + void Execute_BoneMtxNum(u32 op, u32 diff); + void Execute_BoneMtxData(u32 op, u32 diff); + void Execute_BlockTransferStart(u32 op, u32 diff); + + // Using string because it's generic - makes no assumptions on the size of the shader IDs of this backend. + std::vector DebugGetShaderIDs(DebugShaderType shader) override; + std::string DebugGetShaderString(std::string id, DebugShaderType shader, DebugShaderStringType stringType) override; + std::vector GetFramebufferList(); + bool GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices); + bool DescribeCodePtr(const u8 *ptr, std::string &name); + + +protected: + void FastRunLoop(DisplayList &list) override; + void ProcessEvent(GPUEvent ev) override; + void FastLoadBoneMatrix(u32 target) override; + void FinishDeferred() override; + +private: + void Flush() { + drawEngine_.Flush(nullptr); + } + void DoBlockTransfer(u32 skipDrawReason); + void CheckFlushOp(int cmd, u32 diff); + void BuildReportingInfo(); + void InitClearInternal(); + void BeginFrameInternal(); + void CopyDisplayToOutputInternal(); + void PerformMemoryCopyInternal(u32 dest, u32 src, int size); + void PerformMemorySetInternal(u32 dest, u8 v, int size); + void PerformStencilUploadInternal(u32 dest, int size); + void InvalidateCacheInternal(u32 addr, int size, GPUInvalidationType type); + void ReinitializeInternal(); + inline void UpdateVsyncInterval(bool force); + void UpdateCmdInfo(); + static CommandInfo cmdInfo_[256]; + + GraphicsContext *gfxCtx_; + VulkanContext *vulkan_; + FramebufferManagerVulkan *framebufferManager_; + TextureCacheVulkan textureCache_; + DepalShaderCacheVulkan depalShaderCache_; + DrawEngineVulkan drawEngine_; + + // Manages shaders and UBO data + ShaderManagerVulkan *shaderManager_; + + // Manages state and pipeline objects + PipelineManagerVulkan *pipelineManager_; + + bool resized_; + int lastVsync_; + VkCommandBuffer curCmd_; + + std::string reportingPrimaryInfo_; + std::string reportingFullInfo_; +}; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp new file mode 100644 index 0000000000..9a9998b6b8 --- /dev/null +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -0,0 +1,339 @@ +#include + +#include "Common/Log.h" +#include "Common/StringUtils.h" +#include "Common/Vulkan/VulkanContext.h" +#include "GPU/Vulkan/VulkanUtil.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" + +PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) { + pipelineCache_ = vulkan->CreatePipelineCache(); +} + +PipelineManagerVulkan::~PipelineManagerVulkan() { + Clear(); + vulkan_->Delete().QueueDeletePipelineCache(pipelineCache_); +} + +void PipelineManagerVulkan::Clear() { + // This should kill off all the shaders at once. + // This could also be an opportunity to store the whole cache to disk. Will need to also + // store the keys. + for (auto iter : pipelines_) { + delete iter.second; + } + pipelines_.clear(); +} + +struct DeclTypeInfo { + VkFormat type; + const char *name; +}; + +static const DeclTypeInfo VComp[] = { + { VK_FORMAT_UNDEFINED, "NULL" }, // DEC_NONE, + { VK_FORMAT_R32_SFLOAT, "R32_SFLOAT " }, // DEC_FLOAT_1, + { VK_FORMAT_R32G32_SFLOAT, "R32G32_SFLOAT " }, // DEC_FLOAT_2, + { VK_FORMAT_R32G32B32_SFLOAT, "R32G32B32_SFLOAT " }, // DEC_FLOAT_3, + { VK_FORMAT_R32G32B32A32_SFLOAT, "R32G32B32A32_SFLOAT " }, // DEC_FLOAT_4, + + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM" }, // DEC_S8_3, + { VK_FORMAT_R16G16B16A16_SNORM, "R16G16B16A16_SNORM " }, // DEC_S16_3, + + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_1, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_2, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_3, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_4, + { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_1, + { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_2, + { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_3, + { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_4, + + { VK_FORMAT_R8G8_UINT, "R8G8_UINT" }, // DEC_U8A_2, + { VK_FORMAT_R16G16_UINT, "R16G16_UINT" }, // DEC_U16A_2, +}; + +void VertexAttribSetup(VkVertexInputAttributeDescription *attr, int fmt, int offset, PspAttributeLocation location) { + attr->location = (uint32_t)location; + attr->binding = 0; + attr->format = VComp[fmt].type; + attr->offset = offset; +} + +// Returns the number of attributes that were set. +// We could cache these AttributeDescription arrays (with pspFmt as the key), but hardly worth bothering +// as we will only call this code when we need to create a new VkPipeline. +int SetupVertexAttribs(VkVertexInputAttributeDescription attrs[], const DecVtxFormat &decFmt) { + int count = 0; + if (decFmt.w0fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.w0fmt, decFmt.w0off, PspAttributeLocation::W1); + } + if (decFmt.w1fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.w1fmt, decFmt.w1off, PspAttributeLocation::W2); + } + if (decFmt.uvfmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.uvfmt, decFmt.uvoff, PspAttributeLocation::TEXCOORD); + } + if (decFmt.c0fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.c0fmt, decFmt.c0off, PspAttributeLocation::COLOR0); + } + if (decFmt.c1fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.c1fmt, decFmt.c1off, PspAttributeLocation::COLOR1); + } + if (decFmt.nrmfmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.nrmfmt, decFmt.nrmoff, PspAttributeLocation::NORMAL); + } + // Position is always there. + VertexAttribSetup(&attrs[count++], decFmt.posfmt, decFmt.posoff, PspAttributeLocation::POSITION); + return count; +} + +int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[], const DecVtxFormat &decFmt) { + int count = 0; + VertexAttribSetup(&attrs[count++], DEC_FLOAT_4, 0, PspAttributeLocation::POSITION); + VertexAttribSetup(&attrs[count++], DEC_FLOAT_3, 16, PspAttributeLocation::TEXCOORD); + VertexAttribSetup(&attrs[count++], DEC_U8_4, 28, PspAttributeLocation::COLOR0); + VertexAttribSetup(&attrs[count++], DEC_U8_4, 32, PspAttributeLocation::COLOR1); + return count; +} + +static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, + VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, + const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { + VkPipelineColorBlendAttachmentState blend0 = {}; + blend0.blendEnable = key.blendEnable; + if (key.blendEnable) { + blend0.colorBlendOp = (VkBlendOp)key.blendOpColor; + blend0.alphaBlendOp = (VkBlendOp)key.blendOpAlpha; + blend0.srcColorBlendFactor = (VkBlendFactor)key.srcColor; + blend0.srcAlphaBlendFactor = (VkBlendFactor)key.srcAlpha; + blend0.dstColorBlendFactor = (VkBlendFactor)key.destColor; + blend0.dstAlphaBlendFactor = (VkBlendFactor)key.destAlpha; + } + blend0.colorWriteMask = key.colorWriteMask; + + VkPipelineColorBlendStateCreateInfo cbs = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO }; + cbs.flags = 0; + cbs.pAttachments = &blend0; + cbs.attachmentCount = 1; + cbs.logicOpEnable = key.logicOpEnable; + if (key.logicOpEnable) + cbs.logicOp = (VkLogicOp)key.logicOp; + else + cbs.logicOp = VK_LOGIC_OP_COPY; + + VkPipelineDepthStencilStateCreateInfo dss = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO }; + dss.depthBoundsTestEnable = false; + dss.stencilTestEnable = key.stencilTestEnable; + if (key.stencilTestEnable) { + dss.front.compareOp = (VkCompareOp)key.stencilCompareOp; + dss.front.passOp = (VkStencilOp)key.stencilPassOp; + dss.front.failOp = (VkStencilOp)key.stencilFailOp; + dss.front.depthFailOp = (VkStencilOp)key.stencilDepthFailOp; + // Back stencil is always the same as front on PSP. + memcpy(&dss.back, &dss.front, sizeof(dss.front)); + } + dss.depthTestEnable = key.depthTestEnable; + if (key.depthTestEnable) { + dss.depthCompareOp = (VkCompareOp)key.depthCompareOp; + dss.depthWriteEnable = key.depthWriteEnable; + } + + VkDynamicState dynamicStates[8]; + int numDyn = 0; + if (key.blendEnable) { + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; + } + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_SCISSOR; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_VIEWPORT; + if (key.stencilTestEnable) { + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_WRITE_MASK; + } + + VkPipelineDynamicStateCreateInfo ds = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO }; + ds.flags = 0; + ds.pDynamicStates = dynamicStates; + ds.dynamicStateCount = numDyn; + + VkPipelineRasterizationStateCreateInfo rs = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; + rs.flags = 0; + rs.depthBiasEnable = false; + rs.cullMode = key.cullMode; + rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rs.lineWidth = 1.0f; + rs.rasterizerDiscardEnable = false; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.depthClampEnable = false; + + VkPipelineMultisampleStateCreateInfo ms = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; + ms.pSampleMask = nullptr; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineShaderStageCreateInfo ss[2]; + ss[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + ss[0].pNext = nullptr; + ss[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + ss[0].pSpecializationInfo = nullptr; + ss[0].module = vs->GetModule(); + ss[0].pName = "main"; + ss[0].flags = 0; + ss[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + ss[1].pNext = nullptr; + ss[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + ss[1].pSpecializationInfo = nullptr; + ss[1].module = fs->GetModule(); + ss[1].pName = "main"; + ss[1].flags = 0; + + if (!ss[0].module || !ss[1].module) { + ERROR_LOG(G3D, "Failed creating graphics pipeline - bad shaders"); + return nullptr; + } + + VkPipelineInputAssemblyStateCreateInfo inputAssembly = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; + inputAssembly.flags = 0; + inputAssembly.topology = (VkPrimitiveTopology)key.topology; + inputAssembly.primitiveRestartEnable = false; + + int vertexStride = 0; + + int offset = 0; + VkVertexInputAttributeDescription attrs[8]; + int attributeCount; + if (useHwTransform) { + attributeCount = SetupVertexAttribs(attrs, vtxDec->decFmt); + vertexStride = vtxDec->decFmt.stride; + } else { + attributeCount = SetupVertexAttribsPretransformed(attrs, vtxDec->decFmt); + vertexStride = 36; + } + + VkVertexInputBindingDescription ibd; + ibd.binding = 0; + ibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + ibd.stride = vertexStride; + + VkPipelineVertexInputStateCreateInfo vis = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; + vis.flags = 0; + vis.vertexBindingDescriptionCount = 1; + vis.pVertexBindingDescriptions = &ibd; + vis.vertexAttributeDescriptionCount = attributeCount; + vis.pVertexAttributeDescriptions = attrs; + + VkPipelineViewportStateCreateInfo views = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; + views.flags = 0; + views.viewportCount = 1; + views.scissorCount = 1; + views.pViewports = nullptr; // dynamic + views.pScissors = nullptr; // dynamic + + VkGraphicsPipelineCreateInfo pipe = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; + pipe.flags = 0; + pipe.stageCount = 2; + pipe.pStages = ss; + pipe.basePipelineIndex = 0; + + pipe.pColorBlendState = &cbs; + pipe.pDepthStencilState = &dss; + pipe.pRasterizationState = &rs; + + // We will use dynamic viewport state. + pipe.pVertexInputState = &vis; + pipe.pViewportState = &views; + pipe.pTessellationState = nullptr; + pipe.pDynamicState = &ds; + pipe.pInputAssemblyState = &inputAssembly; + pipe.pMultisampleState = &ms; + pipe.layout = layout; + pipe.basePipelineHandle = VK_NULL_HANDLE; + pipe.basePipelineIndex = 0; + pipe.renderPass = renderPass; + pipe.subpass = 0; + + VkPipeline pipeline; + VkResult result = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipe, nullptr, &pipeline); + if (result != VK_SUCCESS) { + ERROR_LOG(G3D, "Failed creating graphics pipeline!"); + return nullptr; + } + + VulkanPipeline *vulkanPipeline = new VulkanPipeline(); + vulkanPipeline->pipeline = pipeline; + vulkanPipeline->uniformBlocks = UB_VS_FS_BASE; + if (useHwTransform) { + if (vs->HasLights()) { + vulkanPipeline->uniformBlocks |= UB_VS_LIGHTS; + } + if (vs->HasBones()) { + vulkanPipeline->uniformBlocks |= UB_VS_BONES; + } + } + return vulkanPipeline; +} + +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { + VulkanPipelineKey key; + key.raster = rasterKey; + key.useHWTransform = useHwTransform; + key.vShader = vs->GetModule(); + key.fShader = fs->GetModule(); + key.vtxDec = useHwTransform ? vtxDec : nullptr; + auto iter = pipelines_.find(key); + if (iter != pipelines_.end()) { + return iter->second; + } + + VulkanPipeline *pipeline = CreateVulkanPipeline( + vulkan_->GetDevice(), pipelineCache_, layout, vulkan_->GetSurfaceRenderPass(), + rasterKey, vtxDec, vs, fs, useHwTransform); + pipelines_[key] = pipeline; + return pipeline; +} + +std::vector PipelineManagerVulkan::DebugGetObjectIDs(DebugShaderType type) { + std::string id; + std::vector ids; + switch (type) { + case SHADER_TYPE_PIPELINE: + { + for (auto iter : pipelines_) { + iter.first.ToString(&id); + ids.push_back(id); + } + } + break; + default: + break; + } + return ids; +} + +std::string PipelineManagerVulkan::DebugGetObjectString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + if (type != SHADER_TYPE_PIPELINE) + return "N/A"; + + VulkanPipelineKey shaderId; + shaderId.FromString(id); + + auto iter = pipelines_.find(shaderId); + if (iter == pipelines_.end()) { + return ""; + } + + switch (stringType) { + case SHADER_STRING_SHORT_DESC: + { + return StringFromFormat("%p", &iter->second); + } + + case SHADER_STRING_SOURCE_CODE: + { + return "N/A"; + } + default: + return "N/A"; + } +} diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h new file mode 100644 index 0000000000..1d6bd6178d --- /dev/null +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -0,0 +1,97 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/VulkanUtil.h" +#include "GPU/Vulkan/StateMappingVulkan.h" + +// PSP vertex format. +enum class PspAttributeLocation { + POSITION = 0, + TEXCOORD = 1, + NORMAL = 2, + W1 = 3, + W2 = 4, + COLOR0 = 5, + COLOR1 = 6, + + COUNT +}; + +struct VulkanPipelineKey { + VulkanPipelineRasterStateKey raster; // prim is included here + bool useHWTransform; + const VertexDecoder *vtxDec; + VkShaderModule vShader; + VkShaderModule fShader; + + bool operator < (const VulkanPipelineKey &other) const { + if (raster < other.raster) return true; else if (other.raster < raster) return false; + if (useHWTransform < other.useHWTransform) return true; else if (other.useHWTransform < useHWTransform) return false; + if (vtxDec < other.vtxDec) return true; else if (other.vtxDec < vtxDec) return false; + if (vShader < other.vShader) return true; else if (other.vShader < vShader) return false; + if (fShader < other.fShader) return true; else if (other.fShader < fShader) return false; + return false; + } + void ToString(std::string *str) const { + str->resize(sizeof(*this)); + memcpy(&(*str)[0], this, sizeof(*this)); + } + void FromString(const std::string &str) { + memcpy(this, &str[0], sizeof(*this)); + } +}; + +enum { + UB_VS_FS_BASE = (1 << 0), + UB_VS_BONES = (1 << 1), + UB_VS_LIGHTS = (1 << 2), +}; + +// Simply wraps a Vulkan pipeline, providing some metadata. +struct VulkanPipeline { + VkPipeline pipeline; + int uniformBlocks; // UB_ enum above. +}; + +class VulkanContext; +class VulkanVertexShader; +class VulkanFragmentShader; + +class PipelineManagerVulkan { +public: + PipelineManagerVulkan(VulkanContext *ctx); + ~PipelineManagerVulkan(); + + VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); + int GetNumPipelines() const { return (int)pipelines_.size(); } + + void Clear(); + + std::string DebugGetObjectString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + std::vector DebugGetObjectIDs(DebugShaderType type); + +private: + std::map pipelines_; + VkPipelineCache pipelineCache_; + VulkanContext *vulkan_; +}; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp new file mode 100644 index 0000000000..3fee8bd807 --- /dev/null +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -0,0 +1,577 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#ifdef _WIN32 +#define SHADERLOG +#endif + +#include + +#include "base/logging.h" +#include "math/lin/matrix4x4.h" +#include "math/math_util.h" +#include "math/dataconv.h" +#include "util/text/utf8.h" +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanMemory.h" +#include "Common/Common.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "UI/OnScreenDisplay.h" + +VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform) + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(0) { + source_ = code; + + std::string errorMessage; + std::vector spirv; +#ifdef SHADERLOG + OutputDebugStringA(code); +#endif + + bool success = GLSLtoSPV(VK_SHADER_STAGE_FRAGMENT_BIT, code, spirv, &errorMessage); + if (!errorMessage.empty()) { + if (success) { + ERROR_LOG(G3D, "Warnings in shader compilation!"); + } else { + ERROR_LOG(G3D, "Error in shader compilation!"); + } + ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); + ERROR_LOG(G3D, "Shader source:\n%s", code); +#ifdef SHADERLOG + OutputDebugStringA("Messages:\n"); + OutputDebugStringA(errorMessage.c_str()); + OutputDebugStringA(code); +#endif + Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); + } else { + success = vulkan_->CreateShaderModule(spirv, &module_); +#ifdef SHADERLOG + OutputDebugStringA("OK\n"); +#endif + } + + if (!success) { + failed_ = true; + return; + } else { + DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code); + } +} + +VulkanFragmentShader::~VulkanFragmentShader() { + if (module_) { + vulkan_->Delete().QueueDeleteShaderModule(module_); + } +} + +std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) const { + switch (type) { + case SHADER_STRING_SOURCE_CODE: + return source_; + case SHADER_STRING_SHORT_DESC: + return FragmentShaderDesc(id_); + default: + return "N/A"; + } +} + +VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform, bool usesLighting) + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(VK_NULL_HANDLE), usesLighting_(usesLighting) { + source_ = code; + std::string errorMessage; + std::vector spirv; +#ifdef SHADERLOG + OutputDebugStringA(code); +#endif + bool success = GLSLtoSPV(VK_SHADER_STAGE_VERTEX_BIT, code, spirv, &errorMessage); + if (!errorMessage.empty()) { + if (success) { + ERROR_LOG(G3D, "Warnings in shader compilation!"); + } else { + ERROR_LOG(G3D, "Error in shader compilation!"); + } + ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); + ERROR_LOG(G3D, "Shader source:\n%s", code); + OutputDebugStringUTF8("Messages:\n"); + OutputDebugStringUTF8(errorMessage.c_str()); + Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); + } else { + success = vulkan_->CreateShaderModule(spirv, &module_); +#ifdef SHADERLOG + OutputDebugStringA("OK\n"); +#endif + } + + if (!success) { + failed_ = true; + module_ = VK_NULL_HANDLE; + return; + } else { + DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code); + } +} + +VulkanVertexShader::~VulkanVertexShader() { + if (module_) { + vulkan_->Delete().QueueDeleteShaderModule(module_); + } +} + +std::string VulkanVertexShader::GetShaderString(DebugShaderStringType type) const { + switch (type) { + case SHADER_STRING_SOURCE_CODE: + return source_; + case SHADER_STRING_SHORT_DESC: + return VertexShaderDesc(id_); + default: + return "N/A"; + } +} + +static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY) { + const Vec3 trans(0, 0, gstate_c.vpZOffset * 0.5f + 0.5f); + const Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); + in.translateAndScale(trans, scale); +} + +static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { + in.translateAndScale(Vec3(0.0f, 0.0f, 0.5f), Vec3(1.0f, 1.0f, 0.5f)); +} + + +ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) + : vulkan_(vulkan), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { + codeBuffer_ = new char[16384]; + uboAlignment_ = vulkan_->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment; + memset(&ub_base, 0, sizeof(ub_base)); + memset(&ub_lights, 0, sizeof(ub_lights)); + memset(&ub_bones, 0, sizeof(ub_bones)); + + ILOG("sizeof(ub_base): %d", (int)sizeof(ub_base)); + ILOG("sizeof(ub_lights): %d", (int)sizeof(ub_lights)); + ILOG("sizeof(ub_bones): %d", (int)sizeof(ub_bones)); +} + +ShaderManagerVulkan::~ShaderManagerVulkan() { + ClearShaders(); + delete[] codeBuffer_; +} + +uint32_t ShaderManagerVulkan::PushBaseBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_base, sizeof(ub_base), uboAlignment_, buf); +} + +uint32_t ShaderManagerVulkan::PushLightBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_lights, sizeof(ub_lights), uboAlignment_, buf); +} + +// TODO: Only push half the bone buffer if we only have four bones. +uint32_t ShaderManagerVulkan::PushBoneBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_bones, sizeof(ub_bones), uboAlignment_, buf); +} + +void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { + if (dirtyUniforms & DIRTY_TEXENV) { + Uint8x3ToFloat4(ub_base.texEnvColor, gstate.texenvcolor); + } + if (dirtyUniforms & DIRTY_ALPHACOLORREF) { + Uint8x3ToInt4_Alpha(ub_base.alphaColorRef, gstate.getColorTestRef(), gstate.getAlphaTestRef() & gstate.getAlphaTestMask()); + } + if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { + Uint8x3ToInt4_Alpha(ub_base.colorTestMask, gstate.getColorTestMask(), gstate.getAlphaTestMask()); + } + if (dirtyUniforms & DIRTY_FOGCOLOR) { + Uint8x3ToFloat4(ub_base.fogColor, gstate.fogcolor); + } + if (dirtyUniforms & DIRTY_SHADERBLEND) { + Uint8x3ToFloat4(ub_base.blendFixA, gstate.getFixA()); + Uint8x3ToFloat4(ub_base.blendFixB, gstate.getFixB()); + } + if (dirtyUniforms & DIRTY_TEXCLAMP) { + const float invW = 1.0f / (float)gstate_c.curTextureWidth; + const float invH = 1.0f / (float)gstate_c.curTextureHeight; + const int w = gstate.getTextureWidth(0); + const int h = gstate.getTextureHeight(0); + const float widthFactor = (float)w * invW; + const float heightFactor = (float)h * invH; + + // First wrap xy, then half texel xy (for clamp.) + const float texclamp[4] = { + widthFactor, + heightFactor, + invW * 0.5f, + invH * 0.5f, + }; + const float texclampoff[2] = { + gstate_c.curTextureXOffset * invW, + gstate_c.curTextureYOffset * invH, + }; + CopyFloat4(ub_base.texClamp, texclamp); + CopyFloat2(ub_base.texClampOffset, texclampoff); + } + + if (dirtyUniforms & DIRTY_PROJMATRIX) { + Matrix4x4 flippedMatrix; + memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); + + const bool invertedY = gstate_c.vpHeight < 0; + if (invertedY) { + flippedMatrix[1] = -flippedMatrix[1]; + flippedMatrix[5] = -flippedMatrix[5]; + flippedMatrix[9] = -flippedMatrix[9]; + flippedMatrix[13] = -flippedMatrix[13]; + } + const bool invertedX = gstate_c.vpWidth < 0; + if (invertedX) { + flippedMatrix[0] = -flippedMatrix[0]; + flippedMatrix[4] = -flippedMatrix[4]; + flippedMatrix[8] = -flippedMatrix[8]; + flippedMatrix[12] = -flippedMatrix[12]; + } + ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); + CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); + } + + if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { + Matrix4x4 proj_through; + proj_through.setOrthoVulkan(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); + CopyMatrix4x4(ub_base.proj_through, proj_through.getReadPtr()); + } + + // Transform + if (dirtyUniforms & DIRTY_WORLDMATRIX) { + ConvertMatrix4x3To4x4(ub_base.world, gstate.worldMatrix); + } + if (dirtyUniforms & DIRTY_VIEWMATRIX) { + ConvertMatrix4x3To4x4(ub_base.view, gstate.viewMatrix); + } + if (dirtyUniforms & DIRTY_TEXMATRIX) { + ConvertMatrix4x3To4x4(ub_base.tex, gstate.tgenMatrix); + } + + // Combined two small uniforms + if (dirtyUniforms & (DIRTY_FOGCOEF | DIRTY_STENCILREPLACEVALUE)) { + float fogcoef_stencil[3] = { + getFloat24(gstate.fog1), + getFloat24(gstate.fog2), + (float)gstate.getStencilTestRef() + }; + if (my_isinf(fogcoef_stencil[1])) { + // not really sure what a sensible value might be. + fogcoef_stencil[1] = fogcoef_stencil[1] < 0.0f ? -10000.0f : 10000.0f; + } else if (my_isnan(fogcoef_stencil[1])) { + // Workaround for https://github.com/hrydgard/ppsspp/issues/5384#issuecomment-38365988 + // Just put the fog far away at a large finite distance. + // Infinities and NaNs are rather unpredictable in shaders on many GPUs + // so it's best to just make it a sane calculation. + fogcoef_stencil[0] = 100000.0f; + fogcoef_stencil[1] = 1.0f; + } +#ifndef MOBILE_DEVICE + else if (my_isnanorinf(fogcoef_stencil[1]) || my_isnanorinf(fogcoef_stencil[0])) { + ERROR_LOG_REPORT_ONCE(fognan, G3D, "Unhandled fog NaN/INF combo: %f %f", fogcoef_stencil[0], fogcoef_stencil[1]); + } +#endif + CopyFloat3(ub_base.fogCoef_stencil, fogcoef_stencil); + } + + // Texturing + if (dirtyUniforms & DIRTY_UVSCALEOFFSET) { + const float invW = 1.0f / (float)gstate_c.curTextureWidth; + const float invH = 1.0f / (float)gstate_c.curTextureHeight; + const int w = gstate.getTextureWidth(0); + const int h = gstate.getTextureHeight(0); + const float widthFactor = (float)w * invW; + const float heightFactor = (float)h * invH; + + static const float rescale[4] = { 1.0f, 2 * 127.5f / 128.f, 2 * 32767.5f / 32768.f, 1.0f }; + const float factor = rescale[(gstate.vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT]; + + float uvscaleoff[4]; + + switch (gstate.getUVGenMode()) { + case GE_TEXMAP_TEXTURE_COORDS: + // Not sure what GE_TEXMAP_UNKNOWN is, but seen in Riviera. Treating the same as GE_TEXMAP_TEXTURE_COORDS works. + case GE_TEXMAP_UNKNOWN: + uvscaleoff[0] = gstate_c.uv.uScale * factor * widthFactor; + uvscaleoff[1] = gstate_c.uv.vScale * factor * heightFactor; + uvscaleoff[2] = gstate_c.uv.uOff * widthFactor; + uvscaleoff[3] = gstate_c.uv.vOff * heightFactor; + break; + + // These two work the same whether or not we prescale UV. + + case GE_TEXMAP_TEXTURE_MATRIX: + // We cannot bake the UV coord scale factor in here, as we apply a matrix multiplication + // before this is applied, and the matrix multiplication may contain translation. In this case + // the translation will be scaled which breaks faces in Hexyz Force for example. + // So I've gone back to applying the scale factor in the shader. + uvscaleoff[0] = widthFactor; + uvscaleoff[1] = heightFactor; + uvscaleoff[2] = 0.0f; + uvscaleoff[3] = 0.0f; + break; + + case GE_TEXMAP_ENVIRONMENT_MAP: + // In this mode we only use uvscaleoff to scale to the texture size. + uvscaleoff[0] = widthFactor; + uvscaleoff[1] = heightFactor; + uvscaleoff[2] = 0.0f; + uvscaleoff[3] = 0.0f; + break; + + default: + ERROR_LOG_REPORT(G3D, "Unexpected UV gen mode: %d", gstate.getUVGenMode()); + } + CopyFloat4(ub_base.uvScaleOffset, uvscaleoff); + } + + if (dirtyUniforms & DIRTY_DEPTHRANGE) { + float viewZScale = gstate.getViewportZScale(); + float viewZCenter = gstate.getViewportZCenter(); + float viewZInvScale; + + // 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; + + if (viewZScale != 0.0) { + viewZInvScale = 1.0f / viewZScale; + } else { + viewZInvScale = 0.0; + } + + float data[4] = { viewZScale, viewZCenter, viewZCenter, viewZInvScale }; + CopyFloat4(ub_base.depthRange, data); + } +} + +void ShaderManagerVulkan::LightUpdateUniforms(int dirtyUniforms) { + // Lighting + if (dirtyUniforms & DIRTY_AMBIENT) { + Uint8x3ToFloat4_AlphaUint8(ub_lights.ambientColor, gstate.ambientcolor, gstate.getAmbientA()); + } + if (dirtyUniforms & DIRTY_MATAMBIENTALPHA) { + // Note - this one is not in lighting but in transformCommon as it has uses beyond lighting + Uint8x3ToFloat4_AlphaUint8(ub_base.matAmbient, gstate.materialambient, gstate.getMaterialAmbientA()); + } + if (dirtyUniforms & DIRTY_MATDIFFUSE) { + Uint8x3ToFloat4(ub_lights.materialDiffuse, gstate.materialdiffuse); + } + if (dirtyUniforms & DIRTY_MATEMISSIVE) { + Uint8x3ToFloat4(ub_lights.materialEmissive, gstate.materialemissive); + } + if (dirtyUniforms & DIRTY_MATSPECULAR) { + Uint8x3ToFloat4_Alpha(ub_lights.materialSpecular, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); + } + + for (int i = 0; i < 4; i++) { + if (dirtyUniforms & (DIRTY_LIGHT0 << i)) { + if (gstate.isDirectionalLight(i)) { + // Prenormalize + float x = getFloat24(gstate.lpos[i * 3 + 0]); + float y = getFloat24(gstate.lpos[i * 3 + 1]); + float z = getFloat24(gstate.lpos[i * 3 + 2]); + float len = sqrtf(x*x + y*y + z*z); + if (len == 0.0f) + len = 1.0f; + else + len = 1.0f / len; + float vec[3] = { x * len, y * len, z * len }; + CopyFloat3To4(ub_lights.lpos[i], vec); + } else { + ExpandFloat24x3ToFloat4(ub_lights.lpos[i], &gstate.lpos[i * 3]); + } + ExpandFloat24x3ToFloat4(ub_lights.ldir[i], &gstate.ldir[i * 3]); + ExpandFloat24x3ToFloat4(ub_lights.latt[i], &gstate.latt[i * 3]); + CopyFloat1To4(ub_lights.lightAngle[i], getFloat24(gstate.lcutoff[i])); + CopyFloat1To4(ub_lights.lightSpotCoef[i], getFloat24(gstate.lconv[i])); + Uint8x3ToFloat4(ub_lights.lightAmbient[i], gstate.lcolor[i * 3]); + Uint8x3ToFloat4(ub_lights.lightDiffuse[i], gstate.lcolor[i * 3 + 1]); + Uint8x3ToFloat4(ub_lights.lightSpecular[i], gstate.lcolor[i * 3 + 2]); + } + } +} + +void ShaderManagerVulkan::BoneUpdateUniforms(int dirtyUniforms) { + for (int i = 0; i < 8; i++) { + if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { + ConvertMatrix4x3To4x4(ub_bones.bones[i], gstate.boneMatrix + 12 * i); + } + } +} + +void ShaderManagerVulkan::Clear() { + for (auto iter = fsCache_.begin(); iter != fsCache_.end(); ++iter) { + delete iter->second; + } + for (auto iter = vsCache_.begin(); iter != vsCache_.end(); ++iter) { + delete iter->second; + } + fsCache_.clear(); + vsCache_.clear(); + lastFSID_.clear(); + lastVSID_.clear(); +} + +void ShaderManagerVulkan::ClearShaders() { + Clear(); + DirtyShader(); + DirtyUniform(0xFFFFFFFF); +} + +void ShaderManagerVulkan::DirtyShader() { + // Forget the last shader ID + lastFSID_.clear(); + lastVSID_.clear(); + lastVShader_ = nullptr; + lastFShader_ = nullptr; +} + +void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays + lastVShader_ = nullptr; + lastFShader_ = nullptr; +} + +uint32_t ShaderManagerVulkan::UpdateUniforms() { + uint32_t dirty = globalDirty_; + if (globalDirty_) { + BaseUpdateUniforms(dirty); + LightUpdateUniforms(dirty); + BoneUpdateUniforms(dirty); + } + globalDirty_ = 0; + return dirty; +} + +void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform) { + ShaderID VSID; + ShaderID FSID; + ComputeVertexShaderID(&VSID, vertType, useHWTransform); + ComputeFragmentShaderID(&FSID); + + // Just update uniforms if this is the same shader as last time. + if (lastVShader_ != nullptr && lastFShader_ != nullptr && VSID == lastVSID_ && FSID == lastFSID_) { + *vshader = lastVShader_; + *fshader = lastFShader_; + // Already all set, no need to look up in shader maps. + return; + } + + VSCache::iterator vsIter = vsCache_.find(VSID); + VulkanVertexShader *vs; + if (vsIter == vsCache_.end()) { + // Vertex shader not in cache. Let's compile it. + bool usesLighting; + GenerateVulkanGLSLVertexShader(VSID, codeBuffer_, &usesLighting); + vs = new VulkanVertexShader(vulkan_, VSID, codeBuffer_, vertType, useHWTransform, usesLighting); + vsCache_[VSID] = vs; + } else { + vs = vsIter->second; + } + lastVSID_ = VSID; + + FSCache::iterator fsIter = fsCache_.find(FSID); + VulkanFragmentShader *fs; + if (fsIter == fsCache_.end()) { + // Fragment shader not in cache. Let's compile it. + GenerateVulkanGLSLFragmentShader(FSID, codeBuffer_); + fs = new VulkanFragmentShader(vulkan_, FSID, codeBuffer_, useHWTransform); + fsCache_[FSID] = fs; + } else { + fs = fsIter->second; + } + + lastFSID_ = FSID; + + lastVShader_ = vs; + lastFShader_ = fs; + + *vshader = vs; + *fshader = fs; +} + +std::vector ShaderManagerVulkan::DebugGetShaderIDs(DebugShaderType type) { + std::string id; + std::vector ids; + switch (type) { + case SHADER_TYPE_VERTEX: + { + for (auto iter : vsCache_) { + iter.first.ToString(&id); + ids.push_back(id); + } + break; + } + case SHADER_TYPE_FRAGMENT: + { + for (auto iter : fsCache_) { + iter.first.ToString(&id); + ids.push_back(id); + } + break; + } + default: + break; + } + return ids; +} + +std::string ShaderManagerVulkan::DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + ShaderID shaderId; + shaderId.FromString(id); + switch (type) { + case SHADER_TYPE_VERTEX: + { + auto iter = vsCache_.find(shaderId); + if (iter == vsCache_.end()) { + return ""; + } + return iter->second->GetShaderString(stringType); + } + + case SHADER_TYPE_FRAGMENT: + { + auto iter = fsCache_.find(shaderId); + if (iter == fsCache_.end()) { + return ""; + } + return iter->second->GetShaderString(stringType); + } + default: + return "N/A"; + } +} diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h new file mode 100644 index 0000000000..ad7b3c5ef5 --- /dev/null +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -0,0 +1,288 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "base/basictypes.h" +#include "Globals.h" +#include "GPU/Common/ShaderCommon.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/VulkanUtil.h" +#include "math/lin/matrix4x4.h" + +void ConvertProjMatrixToVulkan(Matrix4x4 & in); + +// Pretty much full. Will need more bits for more fine grained dirty tracking for lights. +enum { + DIRTY_PROJMATRIX = (1 << 0), + DIRTY_PROJTHROUGHMATRIX = (1 << 1), + DIRTY_FOGCOLOR = (1 << 2), + DIRTY_FOGCOEF = (1 << 3), + DIRTY_TEXENV = (1 << 4), + DIRTY_ALPHACOLORREF = (1 << 5), + DIRTY_STENCILREPLACEVALUE = (1 << 6), + + DIRTY_ALPHACOLORMASK = (1 << 7), + DIRTY_LIGHT0 = (1 << 8), + DIRTY_LIGHT1 = (1 << 9), + DIRTY_LIGHT2 = (1 << 10), + DIRTY_LIGHT3 = (1 << 11), + + DIRTY_MATDIFFUSE = (1 << 12), + DIRTY_MATSPECULAR = (1 << 13), + DIRTY_MATEMISSIVE = (1 << 14), + DIRTY_AMBIENT = (1 << 15), + DIRTY_MATAMBIENTALPHA = (1 << 16), + DIRTY_SHADERBLEND = (1 << 17), // Used only for in-shader blending. + DIRTY_UVSCALEOFFSET = (1 << 18), // this will be dirtied ALL THE TIME... maybe we'll need to do "last value with this shader compares" + DIRTY_TEXCLAMP = (1 << 19), + + DIRTY_DEPTHRANGE = (1 << 20), + + DIRTY_WORLDMATRIX = (1 << 21), + DIRTY_VIEWMATRIX = (1 << 22), + DIRTY_TEXMATRIX = (1 << 23), + DIRTY_BONEMATRIX0 = (1 << 24), + DIRTY_BONEMATRIX1 = (1 << 25), + DIRTY_BONEMATRIX2 = (1 << 26), + DIRTY_BONEMATRIX3 = (1 << 27), + DIRTY_BONEMATRIX4 = (1 << 28), + DIRTY_BONEMATRIX5 = (1 << 29), + DIRTY_BONEMATRIX6 = (1 << 30), + DIRTY_BONEMATRIX7 = (1 << 31), + + DIRTY_BASE_UNIFORMS = + DIRTY_WORLDMATRIX | DIRTY_PROJTHROUGHMATRIX | DIRTY_VIEWMATRIX | DIRTY_TEXMATRIX | DIRTY_ALPHACOLORREF | + DIRTY_PROJMATRIX | DIRTY_FOGCOLOR | DIRTY_FOGCOEF | DIRTY_TEXENV | DIRTY_STENCILREPLACEVALUE | + DIRTY_ALPHACOLORMASK | DIRTY_SHADERBLEND | DIRTY_UVSCALEOFFSET | DIRTY_TEXCLAMP | DIRTY_DEPTHRANGE | DIRTY_MATAMBIENTALPHA, + DIRTY_LIGHT_UNIFORMS = + DIRTY_LIGHT0 | DIRTY_LIGHT1 | DIRTY_LIGHT2 | DIRTY_LIGHT3 | + DIRTY_MATDIFFUSE | DIRTY_MATSPECULAR | DIRTY_MATEMISSIVE | DIRTY_AMBIENT, + DIRTY_BONE_UNIFORMS = 0xFF000000, + + DIRTY_ALL = 0xFFFFFFFF +}; + +// TODO: Split into two structs, one for software transform and one for hardware transform, to save space. +// 512 bytes. Probably can't get to 256 (nVidia's UBO alignment). +struct UB_VS_FS_Base { + float proj[16]; + float proj_through[16]; + float view[16]; + float world[16]; + float tex[16]; // not that common, may want to break out + float uvScaleOffset[4]; + float depthRange[4]; + float fogCoef_stencil[4]; + float matAmbient[4]; + // Fragment data + float fogColor[4]; + float texEnvColor[4]; + int alphaColorRef[4]; + int colorTestMask[4]; + float blendFixA[4]; + float blendFixB[4]; + float texClamp[4]; + float texClampOffset[4]; +}; + +static const char *ub_baseStr = +R"( mat4 proj_mtx; + mat4 proj_through_mtx; + mat4 view_mtx; + mat4 world_mtx; + mat4 tex_mtx; + vec4 uvscaleoffset; + vec4 depthRange; + vec3 fogcoef_stencilreplace; + vec4 matambientalpha; + vec3 fogcolor; + vec3 texenv; + ivec4 alphacolorref; + ivec4 alphacolormask; + vec3 blendFixA; + vec3 blendFixB; + vec4 texclamp; + vec2 texclampoff; +)"; + +// 576 bytes. Can we get down to 512? +struct UB_VS_Lights { + float ambientColor[4]; + float materialDiffuse[4]; + float materialSpecular[4]; + float materialEmissive[4]; + float lpos[4][4]; + float ldir[4][4]; + float latt[4][4]; + float lightAngle[4][4]; // TODO: Merge with lightSpotCoef, use .xy + float lightSpotCoef[4][4]; + float lightAmbient[4][4]; + float lightDiffuse[4][4]; + float lightSpecular[4][4]; +}; + +static const char *ub_vs_lightsStr = +R"( vec4 globalAmbient; + vec3 matdiffuse; + vec4 matspecular; + vec3 matemissive; + vec3 pos[4]; + vec3 dir[4]; + vec3 att[4]; + float angle[4]; + float spotCoef[4]; + vec3 ambient[4]; + vec3 diffuse[4]; + vec3 specular[4]; +)"; + +// With some cleverness, we could get away with uploading just half this when only the four first +// bones are being used. This is 512b, 256b would be great. +// Could also move to 4x3 matrices - would let us fit 5 bones into 256b. +struct UB_VS_Bones { + float bones[8][16]; +}; + +static const char *ub_vs_bonesStr = +R"( mat4 m[8]; +)"; + +class VulkanContext; +class VulkanPushBuffer; + +class VulkanFragmentShader { +public: + VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform); + ~VulkanFragmentShader(); + + const std::string &source() const { return source_; } + + bool Failed() const { return failed_; } + bool UseHWTransform() const { return useHWTransform_; } + + std::string GetShaderString(DebugShaderStringType type) const; + VkShaderModule GetModule() const { return module_; } + +protected: + VkShaderModule module_; + + VulkanContext *vulkan_; + std::string source_; + bool failed_; + bool useHWTransform_; + ShaderID id_; +}; + +class VulkanVertexShader { +public: + VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform, bool usesLighting); + ~VulkanVertexShader(); + + const std::string &source() const { return source_; } + + bool Failed() const { return failed_; } + bool UseHWTransform() const { return useHWTransform_; } + bool HasBones() const { + return id_.Bit(VS_BIT_ENABLE_BONES); + } + bool HasLights() const { + return usesLighting_; + } + + std::string GetShaderString(DebugShaderStringType type) const; + VkShaderModule GetModule() const { return module_; } + +protected: + VkShaderModule module_; + + VulkanContext *vulkan_; + std::string source_; + bool failed_; + bool useHWTransform_; + bool usesLighting_; + ShaderID id_; +}; + +class VulkanPushBuffer; + +class ShaderManagerVulkan { +public: + ShaderManagerVulkan(VulkanContext *vulkan); + ~ShaderManagerVulkan(); + + void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform); + void ClearShaders(); + void DirtyShader(); + void DirtyLastShader(); + + int GetNumVertexShaders() const { return (int)vsCache_.size(); } + int GetNumFragmentShaders() const { return (int)fsCache_.size(); } + + std::vector DebugGetShaderIDs(DebugShaderType type); + std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + + uint32_t UpdateUniforms(); + + void DirtyUniform(u32 what) { + globalDirty_ |= what; + } + + // TODO: Avoid copying these buffers if same as last draw, can still point to it assuming we're still in the same pushbuffer. + // Applies dirty changes and copies the buffer. + bool IsBaseDirty() { return true; } + bool IsLightDirty() { return true; } + bool IsBoneDirty() { return true; } + + uint32_t PushBaseBuffer(VulkanPushBuffer *dest, VkBuffer *buf); + uint32_t PushLightBuffer(VulkanPushBuffer *dest, VkBuffer *buf); + uint32_t PushBoneBuffer(VulkanPushBuffer *dest, VkBuffer *buf); + +private: + void BaseUpdateUniforms(int dirtyUniforms); + void LightUpdateUniforms(int dirtyUniforms); + void BoneUpdateUniforms(int dirtyUniforms); + + void Clear(); + + VulkanContext *vulkan_; + + typedef std::map FSCache; + FSCache fsCache_; + + typedef std::map VSCache; + VSCache vsCache_; + + char *codeBuffer_; + + uint32_t globalDirty_; + uint32_t uboAlignment_; + // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. + UB_VS_FS_Base ub_base; + UB_VS_Lights ub_lights; + UB_VS_Bones ub_bones; + + VulkanFragmentShader *lastFShader_; + VulkanVertexShader *lastVShader_; + + ShaderID lastFSID_; + ShaderID lastVSID_; +}; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp new file mode 100644 index 0000000000..05f40f5dc0 --- /dev/null +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -0,0 +1,316 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "Common/Vulkan/VulkanLoader.h" + +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/Common/GPUStateUtils.h" +#include "Core/System.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +//#include "GPU/Vulkan/StateMappingVulkan.h" +#include "GPU/Vulkan/GPU_Vulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +//#include "GPU/Vulkan/PixelShaderGeneratorVulkan.h" + +// These tables all fit into u8s. +static const VkBlendFactor vkBlendFactorLookup[(size_t)BlendFactor::COUNT] = { + VK_BLEND_FACTOR_ZERO, + VK_BLEND_FACTOR_ONE, + VK_BLEND_FACTOR_SRC_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, + VK_BLEND_FACTOR_DST_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_FACTOR_DST_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, + VK_BLEND_FACTOR_CONSTANT_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, + VK_BLEND_FACTOR_CONSTANT_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, + VK_BLEND_FACTOR_SRC1_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, + VK_BLEND_FACTOR_MAX_ENUM, +}; + +static const VkBlendOp vkBlendEqLookup[(size_t)BlendEq::COUNT] = { + VK_BLEND_OP_ADD, + VK_BLEND_OP_SUBTRACT, + VK_BLEND_OP_REVERSE_SUBTRACT, + VK_BLEND_OP_MIN, + VK_BLEND_OP_MAX, +}; + +static const VkCullModeFlagBits cullingMode[] = { + VK_CULL_MODE_BACK_BIT, + VK_CULL_MODE_FRONT_BIT, +}; + +static const VkCompareOp compareOps[] = { + VK_COMPARE_OP_NEVER, + VK_COMPARE_OP_ALWAYS, + VK_COMPARE_OP_EQUAL, + VK_COMPARE_OP_NOT_EQUAL, + VK_COMPARE_OP_LESS, + VK_COMPARE_OP_LESS_OR_EQUAL, + VK_COMPARE_OP_GREATER, + VK_COMPARE_OP_GREATER_OR_EQUAL, +}; + +static const VkStencilOp stencilOps[] = { + VK_STENCIL_OP_KEEP, + VK_STENCIL_OP_ZERO, + VK_STENCIL_OP_REPLACE, + VK_STENCIL_OP_INVERT, + VK_STENCIL_OP_INCREMENT_AND_CLAMP, + VK_STENCIL_OP_DECREMENT_AND_CLAMP, + VK_STENCIL_OP_KEEP, // reserved + VK_STENCIL_OP_KEEP, // reserved +}; + +const VkPrimitiveTopology primToVulkan[8] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // Vulkan doesn't do quads. We could do strips with restart-index though. We could also do RECT primitives in the geometry shader. +}; + + +bool ApplyShaderBlending() { + return false; +} + +void ResetShaderBlending() { + // +} + +// TODO: Do this more progressively. No need to compute the entire state if the entire state hasn't changed. +// In Vulkan, we simply collect all the state together into a "pipeline key" - we don't actually set any state here +// (the caller is responsible for setting the little dynamic state that is supported, dynState). +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerVulkan *shaderManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState) { + memset(&key, 0, sizeof(key)); + memset(&dynState, 0, sizeof(dynState)); + // Unfortunately, this isn't implemented yet. + gstate_c.allowShaderBlend = false; + + // Set blend - unless we need to do it in the shader. + GenericBlendState blendState; + ConvertBlendState(blendState, gstate_c.allowShaderBlend); + + bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE; + + ViewportAndScissor vpAndScissor; + ConvertViewportAndScissor(useBufferedRendering, + fbManager.GetRenderWidth(), fbManager.GetRenderHeight(), + fbManager.GetTargetBufferWidth(), fbManager.GetTargetBufferHeight(), + vpAndScissor); + + if (blendState.applyShaderBlending) { + if (ApplyShaderBlending()) { + // We may still want to do something about stencil -> alpha. + ApplyStencilReplaceAndLogicOp(blendState.replaceAlphaWithStencil, blendState); + } else { + // Until next time, force it off. + ResetShaderBlending(); + gstate_c.allowShaderBlend = false; + } + } else if (blendState.resetShaderBlending) { + ResetShaderBlending(); + } + + if (blendState.enabled) { + key.blendEnable = true; + key.blendOpColor = vkBlendEqLookup[(size_t)blendState.eqColor]; + key.blendOpAlpha = vkBlendEqLookup[(size_t)blendState.eqAlpha]; + key.srcColor = vkBlendFactorLookup[(size_t)blendState.srcColor]; + key.srcAlpha = vkBlendFactorLookup[(size_t)blendState.srcAlpha]; + key.destColor = vkBlendFactorLookup[(size_t)blendState.dstColor]; + key.destAlpha = vkBlendFactorLookup[(size_t)blendState.dstAlpha]; + if (blendState.dirtyShaderBlend) { + shaderManager->DirtyUniform(DIRTY_SHADERBLEND); + } + dynState.useBlendColor = blendState.useBlendColor; + if (blendState.useBlendColor) { + dynState.blendColor = blendState.blendColor; + } + } else { + key.blendEnable = false; + dynState.useBlendColor = false; + } + + dynState.useStencil = false; + + // Set ColorMask/Stencil/Depth + if (gstate.isModeClear()) { + key.cullMode = VK_CULL_MODE_NONE; + + key.depthTestEnable = true; + key.depthCompareOp = VK_COMPARE_OP_ALWAYS; + key.depthWriteEnable = gstate.isClearModeDepthMask(); + if (gstate.isClearModeDepthMask()) { + fbManager.SetDepthUpdated(); + } + + // Color Test + bool colorMask = gstate.isClearModeColorMask(); + bool alphaMask = gstate.isClearModeAlphaMask(); + key.colorWriteMask = (colorMask ? (VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT) : 0) | (alphaMask ? VK_COLOR_COMPONENT_A_BIT : 0); + + GenericStencilFuncState stencilState; + ConvertStencilFuncState(stencilState); + + // Stencil Test + if (stencilState.enabled) { + key.stencilTestEnable = true; + key.stencilCompareOp = compareOps[stencilState.testFunc]; + key.stencilPassOp = stencilOps[stencilState.zPass]; + key.stencilFailOp = stencilOps[stencilState.sFail]; + key.stencilDepthFailOp = stencilOps[stencilState.zFail]; + dynState.useStencil = true; + dynState.stencilRef = stencilState.testRef; + dynState.stencilCompareMask = stencilState.testMask; + dynState.stencilWriteMask = stencilState.writeMask; + } else { + key.stencilTestEnable = false; + dynState.useStencil = false; + } + } else { + // Set cull + bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); + key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; + + // Depth Test + if (gstate.isDepthTestEnabled()) { + key.depthTestEnable = true; + key.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; + key.depthWriteEnable = gstate.isDepthWriteEnabled(); + if (gstate.isDepthWriteEnabled()) { + // framebufferManager_->SetDepthUpdated(); + } + } else { + key.depthTestEnable = false; + key.depthWriteEnable = false; + key.depthCompareOp = VK_COMPARE_OP_ALWAYS; + } + + // PSP color/alpha mask is per bit but we can only support per byte. + // But let's do that, at least. And let's try a threshold. + bool rmask = (gstate.pmskc & 0xFF) < 128; + bool gmask = ((gstate.pmskc >> 8) & 0xFF) < 128; + bool bmask = ((gstate.pmskc >> 16) & 0xFF) < 128; + bool amask = (gstate.pmska & 0xFF) < 128; + + u8 abits = (gstate.pmska >> 0) & 0xFF; +#ifndef MOBILE_DEVICE + u8 rbits = (gstate.pmskc >> 0) & 0xFF; + u8 gbits = (gstate.pmskc >> 8) & 0xFF; + u8 bbits = (gstate.pmskc >> 16) & 0xFF; + if ((rbits != 0 && rbits != 0xFF) || (gbits != 0 && gbits != 0xFF) || (bbits != 0 && bbits != 0xFF)) { + WARN_LOG_REPORT_ONCE(rgbmask, G3D, "Unsupported RGB mask: r=%02x g=%02x b=%02x", rbits, gbits, bbits); + } + if (abits != 0 && abits != 0xFF) { + // The stencil part of the mask is supported. + WARN_LOG_REPORT_ONCE(amask, G3D, "Unsupported alpha/stencil mask: %02x", abits); + } +#endif + + // Let's not write to alpha if stencil isn't enabled. + if (!gstate.isStencilTestEnabled()) { + amask = false; + } else { + // If the stencil type is set to KEEP, we shouldn't write to the stencil/alpha channel. + if (ReplaceAlphaWithStencilType() == STENCIL_VALUE_KEEP) { + amask = false; + } + } + + key.colorWriteMask = (rmask ? VK_COLOR_COMPONENT_R_BIT : 0) | (gmask ? VK_COLOR_COMPONENT_G_BIT : 0) | (bmask ? VK_COLOR_COMPONENT_B_BIT : 0) | (amask ? VK_COLOR_COMPONENT_A_BIT : 0); + + // Stencil Test + if (gstate.isStencilTestEnabled()) { + key.stencilTestEnable = true; + key.stencilCompareOp = compareOps[gstate.getStencilTestFunction()]; + dynState.stencilRef = gstate.getStencilTestRef(); + dynState.stencilCompareMask = gstate.getStencilTestMask(); + key.stencilFailOp = stencilOps[gstate.getStencilOpSFail()]; // stencil fail + key.stencilDepthFailOp = stencilOps[gstate.getStencilOpZFail()]; // depth fail + key.stencilPassOp = stencilOps[gstate.getStencilOpZPass()]; // depth pass + dynState.stencilWriteMask = ~abits; + } else { + key.stencilTestEnable = false; + } + } + + key.topology = primToVulkan[prim]; + + VkViewport &vp = dynState.viewport; + vp.x = vpAndScissor.viewportX; + vp.y = vpAndScissor.viewportY; + vp.width = vpAndScissor.viewportW; + vp.height = vpAndScissor.viewportH; + vp.minDepth = vpAndScissor.depthRangeMin; + vp.maxDepth = vpAndScissor.depthRangeMax; + if (vpAndScissor.dirtyProj) { + shaderManager->DirtyUniform(DIRTY_PROJMATRIX); + } + + VkRect2D &scissor = dynState.scissor; + scissor.offset.x = vpAndScissor.scissorX; + scissor.offset.y = vpAndScissor.scissorY; + scissor.extent.width = vpAndScissor.scissorW; + scissor.extent.height = vpAndScissor.scissorH; + + float depthMin = vpAndScissor.depthRangeMin; + float depthMax = vpAndScissor.depthRangeMax; + + if (depthMin < 0.0f) depthMin = 0.0f; + if (depthMax > 1.0f) depthMax = 1.0f; + if (vpAndScissor.dirtyDepth) { + shaderManager->DirtyUniform(DIRTY_DEPTHRANGE); + } +} + +//void DrawEngineVulkan::ApplyDrawStateLate() { + /* + // At this point, we know if the vertices are full alpha or not. + // TODO: Set the nearest/linear here (since we correctly know if alpha/color tests are needed)? + if (!gstate.isModeClear()) { + // TODO: Test texture? + + textureCache_->ApplyTexture(); + + if (fboTexNeedBind_) { + // Note that this is positions, not UVs, that we need the copy from. + framebufferManager_->BindFramebufferColor(1, nullptr, BINDFBCOLOR_MAY_COPY); + // If we are rendering at a higher resolution, linear is probably best for the dest color. + pD3Ddevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + pD3Ddevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + fboTexBound_ = true; + fboTexNeedBind_ = false; + } + } + */ +//} diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h new file mode 100644 index 0000000000..e4b67a3b57 --- /dev/null +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -0,0 +1,63 @@ +#pragma once + +#include "Common/Vulkan/VulkanLoader.h" + +#include + +class FramebufferManagerVulkan; + +struct VulkanDynamicState { + VkViewport viewport; + VkRect2D scissor; + bool useBlendColor; + uint32_t blendColor; + bool useStencil; + uint8_t stencilRef; + uint8_t stencilWriteMask; + uint8_t stencilCompareMask; +}; + +// Let's pack this tight using bitfields. +// If an enable flag is set to 0, all the data fields for that section should +// also be set to 0. +// ~54 bits. +// Can't use enums unfortunately, they end up signed and breaking values above half their ranges. +struct VulkanPipelineRasterStateKey { + // Blend + unsigned int blendEnable : 1; + unsigned int srcColor : 5; // VkBlendFactor + unsigned int destColor : 5; // VkBlendFactor + unsigned int srcAlpha : 5; // VkBlendFactor + unsigned int destAlpha : 5; // VkBlendFactor + // bool useBlendConstant : 1; // sacrifice a bit to cheaply check if we need to update the blend color + unsigned int blendOpColor : 3; // VkBlendOp + unsigned int blendOpAlpha : 3; // VkBlendOp + unsigned int logicOpEnable : 1; + unsigned int logicOp : 4; // VkLogicOp + unsigned int colorWriteMask : 4; + + // Depth/Stencil + unsigned int depthTestEnable : 1; + unsigned int depthWriteEnable : 1; + unsigned int depthCompareOp : 3; // VkCompareOp + unsigned int stencilTestEnable : 1; + unsigned int stencilCompareOp : 3; // VkCompareOp + unsigned int stencilPassOp : 4; // VkStencilOp + unsigned int stencilFailOp : 4; // VkStencilOp + unsigned int stencilDepthFailOp : 4; // VkStencilOp + + // We'll use dynamic state for writemask, reference and comparemask to start with, + // and viewport/scissor. + + // Rasterizer + unsigned int cullMode : 2; // VkCullModeFlagBits + unsigned int topology : 4; // VkPrimitiveTopology + + bool operator < (const VulkanPipelineRasterStateKey &other) const { + size_t size = sizeof(VulkanPipelineRasterStateKey); + return memcmp(this, &other, size) < 0; + } +}; + +class ShaderManagerVulkan; +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerVulkan *shaderManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp new file mode 100644 index 0000000000..b21c252491 --- /dev/null +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -0,0 +1,1820 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include + +#include "ext/xxhash.h" +#include "i18n/i18n.h" +#include "math/math_util.h" +#include "profiler/profiler.h" +#include "Common/ColorConv.h" +#include "Core/Config.h" +#include "Core/Host.h" +#include "Core/MemMap.h" +#include "Core/Reporting.h" +#include "Core/System.h" + +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanImage.h" +#include "Common/Vulkan/VulkanMemory.h" + +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Common/TextureDecoder.h" +#include "UI/OnScreenDisplay.h" + +#ifdef _M_SSE +#include +#endif + +// If a texture hasn't been seen for this many frames, get rid of it. +#define TEXTURE_KILL_AGE 200 +#define TEXTURE_KILL_AGE_LOWMEM 60 +// Not used in lowmem mode. +#define TEXTURE_SECOND_KILL_AGE 100 + +// Try to be prime to other decimation intervals. +#define TEXCACHE_DECIMATION_INTERVAL 13 + +// Changes more frequent than this will be considered "frequent" and prevent texture scaling. +#define TEXCACHE_FRAME_CHANGE_FREQUENT 6 +// Note: only used when hash backoff is disabled. +#define TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST 33 + +#define TEXCACHE_NAME_CACHE_SIZE 16 + +#define TEXCACHE_MAX_TEXELS_SCALED (256*256) // Per frame + +#define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in GL +#define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024 + +// TODO: Except for color swizzle, exact matches are available. +// So we can get rid of the conversion functions entirely. +#define VULKAN_4444_FORMAT VK_FORMAT_R4G4B4A4_UNORM_PACK16 +#define VULKAN_1555_FORMAT VK_FORMAT_R5G5B5A1_UNORM_PACK16 +#define VULKAN_565_FORMAT VK_FORMAT_R5G6B5_UNORM_PACK16 +#define VULKAN_8888_FORMAT VK_FORMAT_R8G8B8A8_UNORM + +// Hack! +extern int g_iNumVideos; + +SamplerCache::~SamplerCache() { + for (auto iter : cache_) { + vulkan_->Delete().QueueDeleteSampler(iter.second); + } +} + +CachedTextureVulkan::~CachedTextureVulkan() { + delete texture_; +} + +VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { + auto iter = cache_.find(key); + if (iter != cache_.end()) { + return iter->second; + } + + VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + samp.addressModeU = key.sClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeV = key.tClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; + samp.compareOp = VK_COMPARE_OP_ALWAYS; + samp.flags = 0; + samp.magFilter = key.magFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + samp.mipmapMode = key.mipFilt ? VK_SAMPLER_MIPMAP_MODE_LINEAR : 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 = key.maxLevel; + samp.minLod = 0.0f; + samp.mipLodBias = 0.0f; + + VkSampler sampler; + VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler); + assert(res == VK_SUCCESS); + cache_[key] = sampler; + return sampler; +} + +TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) + : vulkan_(vulkan), samplerCache_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), + clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0), + clutAlphaLinear_(false) { + timesInvalidatedAllThisFrame_ = 0; + lastBoundTexture = nullptr; + decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; + + SetupTextureDecoder(); + + nextTexture_ = nullptr; +} + +TextureCacheVulkan::~TextureCacheVulkan() { + Clear(true); +} + +void TextureCacheVulkan::DownloadFramebufferForClut(u32 clutAddr, u32 bytes) { + +} + +static u32 EstimateTexMemoryUsage(const TextureCacheVulkan::TexCacheEntry *entry) { + const u16 dim = entry->dim; + const u8 dimW = ((dim >> 0) & 0xf); + const u8 dimH = ((dim >> 8) & 0xf); + + u32 pixelSize = 2; + switch (entry->format) { + case GE_TFMT_CLUT4: + case GE_TFMT_CLUT8: + case GE_TFMT_CLUT16: + case GE_TFMT_CLUT32: + // We assume cluts always point to 8888 for simplicity. + pixelSize = 4; + break; + case GE_TFMT_4444: + case GE_TFMT_5551: + case GE_TFMT_5650: + break; + + case GE_TFMT_8888: + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + default: + pixelSize = 4; + break; + } + + // This in other words multiplies by w and h. + return pixelSize << (dimW + dimH); +} + +void TextureCacheVulkan::Clear(bool delete_them) { + lastBoundTexture = nullptr; + if (delete_them) { + for (TexCache::iterator iter = cache.begin(); iter != cache.end(); ++iter) { + DEBUG_LOG(G3D, "Deleting texture %p", iter->second.vkTex); + delete iter->second.vkTex; + } + for (TexCache::iterator iter = secondCache.begin(); iter != secondCache.end(); ++iter) { + DEBUG_LOG(G3D, "Deleting texture %p", iter->second.vkTex); + delete iter->second.vkTex; + } + } + if (cache.size() + secondCache.size()) { + INFO_LOG(G3D, "Texture cached cleared from %i textures", (int)(cache.size() + secondCache.size())); + cache.clear(); + secondCache.clear(); + cacheSizeEstimate_ = 0; + secondCacheSizeEstimate_ = 0; + } + fbTexInfo_.clear(); +} + +void TextureCacheVulkan::DeleteTexture(TexCache::iterator it) { + delete it->second.vkTex; + auto fbInfo = fbTexInfo_.find(it->second.addr); + if (fbInfo != fbTexInfo_.end()) { + fbTexInfo_.erase(fbInfo); + } + + cacheSizeEstimate_ -= EstimateTexMemoryUsage(&it->second); + cache.erase(it); +} + +// Removes old textures. +void TextureCacheVulkan::Decimate() { + if (--decimationCounter_ <= 0) { + decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; + } else { + return; + } + + if (cacheSizeEstimate_ >= TEXCACHE_MIN_PRESSURE) { + const u32 had = cacheSizeEstimate_; + + lastBoundTexture = nullptr; + int killAge = lowMemoryMode_ ? TEXTURE_KILL_AGE_LOWMEM : TEXTURE_KILL_AGE; + for (TexCache::iterator iter = cache.begin(); iter != cache.end(); ) { + if (iter->second.lastFrame + killAge < gpuStats.numFlips) { + DeleteTexture(iter++); + } else { + ++iter; + } + } + + VERBOSE_LOG(G3D, "Decimated texture cache, saved %d estimated bytes - now %d bytes", had - cacheSizeEstimate_, cacheSizeEstimate_); + } + + if (g_Config.bTextureSecondaryCache && secondCacheSizeEstimate_ >= TEXCACHE_SECOND_MIN_PRESSURE) { + const u32 had = secondCacheSizeEstimate_; + + for (TexCache::iterator iter = secondCache.begin(); iter != secondCache.end(); ) { + // In low memory mode, we kill them all. + if (lowMemoryMode_ || iter->second.lastFrame + TEXTURE_SECOND_KILL_AGE < gpuStats.numFlips) { + delete iter->second.vkTex; + secondCacheSizeEstimate_ -= EstimateTexMemoryUsage(&iter->second); + secondCache.erase(iter++); + } else { + ++iter; + } + } + + VERBOSE_LOG(G3D, "Decimated second texture cache, saved %d estimated bytes - now %d bytes", had - secondCacheSizeEstimate_, secondCacheSizeEstimate_); + } +} + +void TextureCacheVulkan::Invalidate(u32 addr, int size, GPUInvalidationType type) { + // If we're hashing every use, without backoff, then this isn't needed. + if (!g_Config.bTextureBackoffCache) { + return; + } + + addr &= 0x3FFFFFFF; + const u32 addr_end = addr + size; + + // They could invalidate inside the texture, let's just give a bit of leeway. + const int LARGEST_TEXTURE_SIZE = 512 * 512 * 4; + const u64 startKey = (u64)(addr - LARGEST_TEXTURE_SIZE) << 32; + u64 endKey = (u64)(addr + size + LARGEST_TEXTURE_SIZE) << 32; + if (endKey < startKey) { + endKey = (u64)-1; + } + + for (TexCache::iterator iter = cache.lower_bound(startKey), end = cache.upper_bound(endKey); iter != end; ++iter) { + u32 texAddr = iter->second.addr; + u32 texEnd = iter->second.addr + iter->second.sizeInRAM; + + if (texAddr < addr_end && addr < texEnd) { + if (iter->second.GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + iter->second.SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + if (type != GPU_INVALIDATE_ALL) { + gpuStats.numTextureInvalidations++; + // Start it over from 0 (unless it's safe.) + iter->second.numFrames = type == GPU_INVALIDATE_SAFE ? 256 : 0; + if (type == GPU_INVALIDATE_SAFE) { + u32 diff = gpuStats.numFlips - iter->second.lastFrame; + // We still need to mark if the texture is frequently changing, even if it's safely changing. + if (diff < TEXCACHE_FRAME_CHANGE_FREQUENT) { + iter->second.status |= TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + iter->second.framesUntilNextFullHash = 0; + } else if (!iter->second.framebuffer) { + iter->second.invalidHint++; + } + } + } +} + +void TextureCacheVulkan::InvalidateAll(GPUInvalidationType /*unused*/) { + // If we're hashing every use, without backoff, then this isn't needed. + if (!g_Config.bTextureBackoffCache) { + return; + } + + if (timesInvalidatedAllThisFrame_ > 5) { + return; + } + timesInvalidatedAllThisFrame_++; + + for (TexCache::iterator iter = cache.begin(), end = cache.end(); iter != end; ++iter) { + if (iter->second.GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + iter->second.SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + if (!iter->second.framebuffer) { + iter->second.invalidHint++; + } + } +} + +void TextureCacheVulkan::ClearNextFrame() { + clearCacheNextFrame_ = true; +} + + +void TextureCacheVulkan::AttachFramebufferValid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo) { + const bool hasInvalidFramebuffer = entry->framebuffer == nullptr || entry->invalidHint == -1; + const bool hasOlderFramebuffer = entry->framebuffer != nullptr && entry->framebuffer->last_frame_render < framebuffer->last_frame_render; + bool hasFartherFramebuffer = false; + if (!hasInvalidFramebuffer && !hasOlderFramebuffer) { + // If it's valid, but the offset is greater, then we still win. + if (fbTexInfo_[entry->addr].yOffset == fbInfo.yOffset) + hasFartherFramebuffer = fbTexInfo_[entry->addr].xOffset > fbInfo.xOffset; + else + hasFartherFramebuffer = fbTexInfo_[entry->addr].yOffset > fbInfo.yOffset; + } + if (hasInvalidFramebuffer || hasOlderFramebuffer || hasFartherFramebuffer) { + if (entry->framebuffer == nullptr) { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + } + entry->framebuffer = framebuffer; + entry->invalidHint = 0; + entry->status &= ~TextureCacheVulkan::TexCacheEntry::STATUS_DEPALETTIZE; + entry->maxLevel = 0; + fbTexInfo_[entry->addr] = fbInfo; + framebuffer->last_frame_attached = gpuStats.numFlips; + host->GPUNotifyTextureAttachment(entry->addr); + } else if (entry->framebuffer == framebuffer) { + framebuffer->last_frame_attached = gpuStats.numFlips; + } +} + +void TextureCacheVulkan::AttachFramebufferInvalid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo) { + if (entry->framebuffer == nullptr || entry->framebuffer == framebuffer) { + if (entry->framebuffer == nullptr) { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + } + entry->framebuffer = framebuffer; + entry->invalidHint = -1; + entry->status &= ~TextureCacheVulkan::TexCacheEntry::STATUS_DEPALETTIZE; + entry->maxLevel = 0; + fbTexInfo_[entry->addr] = fbInfo; + host->GPUNotifyTextureAttachment(entry->addr); + } +} + +bool TextureCacheVulkan::AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset) { + static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; + + AttachedFramebufferInfo fbInfo = { 0 }; + + const u64 mirrorMask = 0x00600000; + // Must be in VRAM so | 0x04000000 it is. Also, ignore memory mirrors. + const u32 addr = (address | 0x04000000) & 0x3FFFFFFF & ~mirrorMask; + const u32 texaddr = ((entry->addr + texaddrOffset) & ~mirrorMask); + const bool noOffset = texaddr == addr; + const bool exactMatch = noOffset && entry->format < 4; + const u32 h = 1 << ((entry->dim >> 8) & 0xf); + // 512 on a 272 framebuffer is sane, so let's be lenient. + const u32 minSubareaHeight = h / 4; + + // If they match exactly, it's non-CLUT and from the top left. + if (exactMatch) { + // Apply to non-buffered and buffered mode only. + if (!(g_Config.iRenderingMode == FB_NON_BUFFERED_MODE || g_Config.iRenderingMode == FB_BUFFERED_MODE)) + return false; + + DEBUG_LOG(G3D, "Render to texture detected at %08x!", address); + if (framebuffer->fb_stride != entry->bufw) { + WARN_LOG_REPORT_ONCE(diffStrides1, G3D, "Render to texture with different strides %d != %d", entry->bufw, framebuffer->fb_stride); + } + if (entry->format != (GETextureFormat)framebuffer->format) { + WARN_LOG_REPORT_ONCE(diffFormat1, G3D, "Render to texture with different formats %d != %d", entry->format, framebuffer->format); + // Let's avoid using it when we know the format is wrong. May be a video/etc. updating memory. + // However, some games use a different format to clear the buffer. + if (framebuffer->last_frame_attached + 1 < gpuStats.numFlips) { + DetachFramebuffer(entry, address, framebuffer); + } + } else { + AttachFramebufferValid(entry, framebuffer, fbInfo); + return true; + } + } else { + // Apply to buffered mode only. + if (!(g_Config.iRenderingMode == FB_BUFFERED_MODE)) + return false; + + const bool clutFormat = + (framebuffer->format == GE_FORMAT_8888 && entry->format == GE_TFMT_CLUT32) || + (framebuffer->format != GE_FORMAT_8888 && entry->format == GE_TFMT_CLUT16); + + const u32 bitOffset = (texaddr - addr) * 8; + const u32 pixelOffset = bitOffset / std::max(1U, (u32)textureBitsPerPixel[entry->format]); + fbInfo.yOffset = entry->bufw == 0 ? 0 : pixelOffset / entry->bufw; + fbInfo.xOffset = entry->bufw == 0 ? 0 : pixelOffset % entry->bufw; + + if (framebuffer->fb_stride != entry->bufw) { + if (noOffset) { + WARN_LOG_REPORT_ONCE(diffStrides2, G3D, "Render to texture using CLUT with different strides %d != %d", entry->bufw, framebuffer->fb_stride); + } else { + // Assume any render-to-tex with different bufw + offset is a render from ram. + DetachFramebuffer(entry, address, framebuffer); + return false; + } + } + + if (fbInfo.yOffset + minSubareaHeight >= framebuffer->height) { + // Can't be inside the framebuffer then, ram. Detach to be safe. + DetachFramebuffer(entry, address, framebuffer); + return false; + } + // Trying to play it safe. Below 0x04110000 is almost always framebuffers. + // TODO: Maybe we can reduce this check and find a better way above 0x04110000? + if (fbInfo.yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000) { + WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible render to texture at %08x +%dx%d / %dx%d", address, fbInfo.xOffset, fbInfo.yOffset, framebuffer->width, framebuffer->height); + DetachFramebuffer(entry, address, framebuffer); + return false; + } + + // Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture. + // 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture. + if (clutFormat) { + if (!noOffset) { + WARN_LOG_REPORT_ONCE(subareaClut, G3D, "Render to texture using CLUT with offset at %08x +%dx%d", address, fbInfo.xOffset, fbInfo.yOffset); + } + AttachFramebufferValid(entry, framebuffer, fbInfo); + entry->status |= TexCacheEntry::STATUS_DEPALETTIZE; + // We'll validate it compiles later. + return true; + } else if (entry->format == GE_TFMT_CLUT8 || entry->format == GE_TFMT_CLUT4) { + ERROR_LOG_REPORT_ONCE(fourEightBit, G3D, "4 and 8-bit CLUT format not supported for framebuffers"); + } + + // This is either normal or we failed to generate a shader to depalettize + if (framebuffer->format == entry->format || clutFormat) { + if (framebuffer->format != entry->format) { + WARN_LOG_REPORT_ONCE(diffFormat2, G3D, "Render to texture with different formats %d != %d at %08x", entry->format, framebuffer->format, address); + AttachFramebufferValid(entry, framebuffer, fbInfo); + return true; + } else { + WARN_LOG_REPORT_ONCE(subarea, G3D, "Render to area containing texture at %08x +%dx%d", address, fbInfo.xOffset, fbInfo.yOffset); + // If "AttachFramebufferValid" , God of War Ghost of Sparta/Chains of Olympus will be missing special effect. + AttachFramebufferInvalid(entry, framebuffer, fbInfo); + return true; + } + } else { + WARN_LOG_REPORT_ONCE(diffFormat2, G3D, "Render to texture with incompatible formats %d != %d at %08x", entry->format, framebuffer->format, address); + } + } + + return false; +} + +inline void TextureCacheVulkan::DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) { + if (entry->framebuffer == framebuffer) { + cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + entry->framebuffer = 0; + host->GPUNotifyTextureAttachment(entry->addr); + } +} + +void *TextureCacheVulkan::ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw) { + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + int length = bufw * h; + void *buf = NULL; + switch (gstate.getClutPaletteFormat()) { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + tmpTexBuf16.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u16 *clut = GetCurrentClut(); + if (!gstate.isTextureSwizzled()) { + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf16.data(), (const u8 *)texptr, length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf16.data(), (const u16_le *)texptr, length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf16.data(), (const u32_le *)texptr, length, clut); + break; + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + UnswizzleFromMem(texptr, bufw, h, bytesPerIndex); + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf16.data(), (u8 *)tmpTexBuf32.data(), length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf16.data(), (u16 *)tmpTexBuf32.data(), length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf16.data(), (u32 *)tmpTexBuf32.data(), length, clut); + break; + } + } + buf = tmpTexBuf16.data(); + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u32 *clut = GetCurrentClut(); + if (!gstate.isTextureSwizzled()) { + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf32.data(), (const u8 *)texptr, length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf32.data(), (const u16_le *)texptr, length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf32.data(), (const u32_le *)texptr, length, clut); + break; + } + buf = tmpTexBuf32.data(); + } else { + UnswizzleFromMem(texptr, bufw, h, bytesPerIndex); + // Since we had to unswizzle to tmpTexBuf32, let's output to tmpTexBuf16. + tmpTexBuf16.resize(std::max(bufw, w) * h * 2); + u32 *dest32 = (u32 *)tmpTexBuf16.data(); + switch (bytesPerIndex) { + case 1: + DeIndexTexture(dest32, (u8 *)tmpTexBuf32.data(), length, clut); + buf = dest32; + break; + + case 2: + DeIndexTexture(dest32, (u16 *)tmpTexBuf32.data(), length, clut); + buf = dest32; + break; + + case 4: + // TODO: If a game actually uses this mode, check if using dest32 or tmpTexBuf32 is faster. + DeIndexTexture(tmpTexBuf32.data(), tmpTexBuf32.data(), length, clut); + buf = tmpTexBuf32.data(); + break; + } + } + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unhandled clut texture mode %d!!!", (gstate.clutformat & 3)); + break; + } + + return buf; +} + +VkFormat getClutDestFormatVulkan(GEPaletteFormat format) { + switch (format) { + case GE_CMODE_16BIT_ABGR4444: + return VULKAN_4444_FORMAT; + case GE_CMODE_16BIT_ABGR5551: + return VULKAN_1555_FORMAT; + case GE_CMODE_16BIT_BGR5650: + return VULKAN_565_FORMAT; + case GE_CMODE_32BIT_ABGR8888: + return VULKAN_8888_FORMAT; + } + return VK_FORMAT_UNDEFINED; +} + +static const u8 texByteAlignMap[] = { 2, 2, 2, 4 }; + +static const VkFilter MagFiltVK[2] = { + VK_FILTER_NEAREST, + VK_FILTER_LINEAR +}; + +void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, SamplerCacheKey &key) { + // TODO: Make GetSamplingParams write SamplerCacheKey directly + int minFilt; + int magFilt; + bool sClamp; + bool tClamp; + float lodBias; + GetSamplingParams(minFilt, magFilt, sClamp, tClamp, lodBias, entry.maxLevel); + key.minFilt = minFilt & 1; + key.mipEnable = (minFilt >> 2) & 1; + key.mipFilt = (minFilt >> 1) & 1; + key.magFilt = magFilt & 1; + key.sClamp = sClamp; + key.tClamp = tClamp; + key.maxLevel = entry.vkTex->texture_->GetNumMips() - 1; + /* + if (entry.maxLevel != 0) { + if (force || entry.lodBias != lodBias) { + if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + GETexLevelMode mode = gstate.getTexLevelMode(); + switch (mode) { + case GE_TEXLEVEL_MODE_AUTO: + // TODO + break; + case GE_TEXLEVEL_MODE_CONST: + // Sigh, LOD_BIAS is not even in ES 3.0.. + break; + case GE_TEXLEVEL_MODE_SLOPE: + // TODO + break; + } + } + entry.lodBias = lodBias; + } + } + */ + + if (entry.framebuffer) { + WARN_LOG_REPORT_ONCE(wrongFramebufAttach, G3D, "Framebuffer still attached in UpdateSamplingParams()?"); + } +} + +void TextureCacheVulkan::SetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight, SamplerCacheKey &key) { + int minFilt; + int magFilt; + bool sClamp; + bool tClamp; + float lodBias; + GetSamplingParams(minFilt, magFilt, sClamp, tClamp, lodBias, 0); + + key.minFilt = minFilt & 1; + key.mipFilt = 0; + key.magFilt = magFilt & 1; + key.sClamp = sClamp; + key.tClamp = tClamp; + + // Often the framebuffer will not match the texture size. We'll wrap/clamp in the shader in that case. + // This happens whether we have OES_texture_npot or not. + int w = gstate.getTextureWidth(0); + int h = gstate.getTextureHeight(0); + if (w != bufferWidth || h != bufferHeight) { + key.sClamp = true; + key.tClamp = true; + } +} + +static void ConvertColors(void *dstBuf, const void *srcBuf, VkFormat dstFmt, int numPixels) { + const u32 *src = (const u32 *)srcBuf; + u32 *dst = (u32 *)dstBuf; + switch (dstFmt) { + case VULKAN_4444_FORMAT: + ConvertRGBA4444ToABGR4444((u16 *)dst, (const u16 *)src, numPixels); + break; + // Final Fantasy 2 uses this heavily in animated textures. + case VULKAN_1555_FORMAT: + ConvertRGBA5551ToABGR1555((u16 *)dst, (const u16 *)src, numPixels); + break; + case VULKAN_565_FORMAT: + ConvertRGB565ToBGR565((u16 *)dst, (const u16 *)src, numPixels); + break; + default: + // No need to convert RGBA8888, right order already + if (dst != src) + memcpy(dst, src, numPixels * sizeof(u32)); + break; + } +} + +void TextureCacheVulkan::StartFrame() { + lastBoundTexture = nullptr; + timesInvalidatedAllThisFrame_ = 0; + + if (texelsScaledThisFrame_) { + // INFO_LOG(G3D, "Scaled %i texels", texelsScaledThisFrame_); + } + texelsScaledThisFrame_ = 0; + if (clearCacheNextFrame_) { + Clear(true); + clearCacheNextFrame_ = false; + } else { + Decimate(); + } +} + +static inline u32 MiniHash(const u32 *ptr) { + return ptr[0]; +} + +static inline u32 QuickTexHash(u32 addr, int bufw, int w, int h, GETextureFormat format, TextureCacheVulkan::TexCacheEntry *entry) { + if (h == 512 && entry->maxSeenV < 512 && entry->maxSeenV != 0) { + h = (int)entry->maxSeenV; + } + + const u32 sizeInRAM = (textureBitsPerPixel[format] * bufw * h) / 8; + const u32 *checkp = (const u32 *)Memory::GetPointer(addr); + + return DoQuickTexHash(checkp, sizeInRAM); +} + +void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple) { + const u32 clutBaseBytes = clutFormat == GE_CMODE_32BIT_ABGR8888 ? (clutBase * sizeof(u32)) : (clutBase * sizeof(u16)); + // Technically, these extra bytes weren't loaded, but hopefully it was loaded earlier. + // If not, we're going to hash random data, which hopefully doesn't cause a performance issue. + // + // TODO: Actually, this seems like a hack. The game can upload part of a CLUT and reference other data. + // clutTotalBytes_ is the last amount uploaded. We should hash clutMaxBytes_, but this will often hash + // unrelated old entries for small palettes. + // Adding clutBaseBytes may just be mitigating this for some usage patterns. + const u32 clutExtendedBytes = std::min(clutTotalBytes_ + clutBaseBytes, clutMaxBytes_); + + clutHash_ = DoReliableHash32((const char *)clutBufRaw_, clutExtendedBytes, 0xC0108888); + + // Avoid a copy when we don't need to convert colors. + if (clutFormat != GE_CMODE_32BIT_ABGR8888) { + const int numColors = clutFormat == GE_CMODE_32BIT_ABGR8888 ? (clutMaxBytes_ / sizeof(u32)) : (clutMaxBytes_ / sizeof(u16)); + ConvertColors(clutBufConverted_, clutBufRaw_, getClutDestFormatVulkan(clutFormat), numColors); + clutBuf_ = clutBufConverted_; + } else { + clutBuf_ = clutBufRaw_; + } + + // Special optimization: fonts typically draw clut4 with just alpha values in a single color. + clutAlphaLinear_ = false; + clutAlphaLinearColor_ = 0; + if (clutFormat == GE_CMODE_16BIT_ABGR4444 && clutIndexIsSimple) { + const u16_le *clut = GetCurrentClut(); + clutAlphaLinear_ = true; + clutAlphaLinearColor_ = clut[15] & 0xFFF0; + for (int i = 0; i < 16; ++i) { + u16 step = clutAlphaLinearColor_ | i; + if (clut[i] != step) { + clutAlphaLinear_ = false; + break; + } + } + } + + clutLastFormat_ = gstate.clutformat; +} + +template +inline const T *TextureCacheVulkan::GetCurrentClut() { + return (const T *)clutBuf_; +} + +inline u32 TextureCacheVulkan::GetCurrentClutHash() { + return clutHash_; +} + +// #define DEBUG_TEXTURES + +#ifdef DEBUG_TEXTURES +bool SetDebugTexture() { + static const int highlightFrames = 30; + + static int numTextures = 0; + static int lastFrames = 0; + static int mostTextures = 1; + + if (lastFrames != gpuStats.numFlips) { + mostTextures = std::max(mostTextures, numTextures); + numTextures = 0; + lastFrames = gpuStats.numFlips; + } + + static GLuint solidTexture = 0; + + bool changed = false; + if (((gpuStats.numFlips / highlightFrames) % mostTextures) == numTextures) { + if (gpuStats.numFlips % highlightFrames == 0) { + NOTICE_LOG(G3D, "Highlighting texture # %d / %d", numTextures, mostTextures); + } + static const u32 solidTextureData[] = { 0x99AA99FF }; + + if (solidTexture == 0) { + glGenTextures(1, &solidTexture); + glBindTexture(GL_TEXTURE_2D, solidTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, solidTextureData); + } else { + glBindTexture(GL_TEXTURE_2D, solidTexture); + } + changed = true; + } + + ++numTextures; + return changed; +} +#endif + +void TextureCacheVulkan::SetTextureFramebuffer(TexCacheEntry *entry, VirtualFramebuffer *framebuffer) { + _dbg_assert_msg_(G3D, framebuffer != nullptr, "Framebuffer must not be null."); + + framebuffer->usageFlags |= FB_USAGE_TEXTURE; + bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE; + if (useBufferedRendering) { + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + DepalShaderVulkan *depal = nullptr; + if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { + // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); + } + if (depal) { + const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); + const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; + + TexCacheEntry::Status alphaStatus = CheckAlpha(clutBuf_, getClutDestFormatVulkan(clutFormat), clutTotalColors, clutTotalColors, 1); + gstate_c.textureFullAlpha = alphaStatus == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = alphaStatus == TexCacheEntry::STATUS_ALPHA_SIMPLE; + } else { + entry->status &= ~TexCacheEntry::STATUS_DEPALETTIZE; + + gstate_c.textureFullAlpha = gstate.getTextureFormat() == GE_TFMT_5650; + gstate_c.textureSimpleAlpha = gstate_c.textureFullAlpha; + } + + // Keep the framebuffer alive. + framebuffer->last_frame_used = gpuStats.numFlips; + + // We need to force it, since we may have set it on a texture before attaching. + gstate_c.curTextureWidth = framebuffer->bufferWidth; + gstate_c.curTextureHeight = framebuffer->bufferHeight; + gstate_c.curTextureXOffset = fbTexInfo_[entry->addr].xOffset; + gstate_c.curTextureYOffset = fbTexInfo_[entry->addr].yOffset; + gstate_c.needShaderTexClamp = gstate_c.curTextureWidth != (u32)gstate.getTextureWidth(0) || gstate_c.curTextureHeight != (u32)gstate.getTextureHeight(0); + if (gstate_c.curTextureXOffset != 0 || gstate_c.curTextureYOffset != 0) { + gstate_c.needShaderTexClamp = true; + } + + nextTexture_ = entry; + } else { + if (framebuffer->fbo_vk) { + delete framebuffer->fbo_vk; + framebuffer->fbo_vk = 0; + } + gstate_c.needShaderTexClamp = false; + } +} + +void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler) { + if (nextTexture_ == nullptr) { + imageView = VK_NULL_HANDLE; + sampler = VK_NULL_HANDLE; + return; + } + VkCommandBuffer cmd = nullptr; + if (nextTexture_->framebuffer) { + ApplyTextureFramebuffer(cmd, nextTexture_, nextTexture_->framebuffer, imageView, sampler); + } else { + // If the texture is >= 512 pixels tall... + if (nextTexture_->dim >= 0x900) { + // Texture scale/offset and gen modes don't apply in through. + // So we can optimize how much of the texture we look at. + if (gstate.isModeThrough()) { + if (nextTexture_->maxSeenV == 0 && gstate_c.vertBounds.maxV > 0) { + // Let's not hash less than 272, we might use more later and have to rehash. 272 is very common. + nextTexture_->maxSeenV = std::max((u16)272, gstate_c.vertBounds.maxV); + } else if (gstate_c.vertBounds.maxV > nextTexture_->maxSeenV) { + // The max height changed, so we're better off hashing the entire thing. + nextTexture_->maxSeenV = 512; + nextTexture_->status |= TexCacheEntry::STATUS_FREE_CHANGE; + } + } else { + // Otherwise, we need to reset to ensure we use the whole thing. + // Can't tell how much is used. + // TODO: We could tell for texcoord UV gen, and apply scale to max? + nextTexture_->maxSeenV = 512; + } + } + + imageView = nextTexture_->vkTex->texture_->GetImageView(); + + SamplerCacheKey key; + UpdateSamplingParams(*nextTexture_, key); + sampler = samplerCache_.GetOrCreateSampler(key); + + lastBoundTexture = nextTexture_->vkTex; + } + + nextTexture_ = nullptr; +} + +void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEntry *entry, VirtualFramebuffer *framebuffer, VkImageView &imageView, VkSampler &sampler) { + DepalShaderVulkan *depal = nullptr; + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { + // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); + } + if (depal) { + // VulkanTexture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBuf_); + VulkanFBO *depalFBO = framebufferManager_->GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, VK_FBO_8888); + + //depalFBO->BeginPass(cmd); + + struct Pos { + Pos(float x_, float y_, float z_) : x(x_), y(y_), z(z_) { + } + float x; + float y; + float z; + }; + struct UV { + UV(float u_, float v_) : u(u_), v(v_) { + } + float u; + float v; + }; + + Pos pos[4] = { + { -1, -1, -1 }, + { 1, -1, -1 }, + { 1, 1, -1 }, + { -1, 1, -1 }, + }; + UV uv[4] = { + { 0, 0 }, + { 1, 0 }, + { 1, 1 }, + { 0, 1 }, + }; + static const int indices[4] = { 0, 1, 3, 2 }; + + // If min is not < max, then we don't have values (wasn't set during decode.) + if (gstate_c.vertBounds.minV < gstate_c.vertBounds.maxV) { + const float invWidth = 1.0f / (float)framebuffer->bufferWidth; + const float invHeight = 1.0f / (float)framebuffer->bufferHeight; + // Inverse of half = double. + const float invHalfWidth = invWidth * 2.0f; + const float invHalfHeight = invHeight * 2.0f; + + const int u1 = gstate_c.vertBounds.minU + gstate_c.curTextureXOffset; + const int v1 = gstate_c.vertBounds.minV + gstate_c.curTextureYOffset; + const int u2 = gstate_c.vertBounds.maxU + gstate_c.curTextureXOffset; + const int v2 = gstate_c.vertBounds.maxV + gstate_c.curTextureYOffset; + + const float left = u1 * invHalfWidth - 1.0f; + const float right = u2 * invHalfWidth - 1.0f; + const float top = v1 * invHalfHeight - 1.0f; + const float bottom = v2 * invHalfHeight - 1.0f; + // Points are: BL, BR, TR, TL. + pos[0] = Pos(left, bottom, -1.0f); + pos[1] = Pos(right, bottom, -1.0f); + pos[2] = Pos(right, top, -1.0f); + pos[3] = Pos(left, top, -1.0f); + + // And also the UVs, same order. + const float uvleft = u1 * invWidth; + const float uvright = u2 * invWidth; + const float uvtop = v1 * invHeight; + const float uvbottom = v2 * invHeight; + uv[0] = UV(uvleft, uvbottom); + uv[1] = UV(uvright, uvbottom); + uv[2] = UV(uvright, uvtop); + uv[3] = UV(uvleft, uvtop); + } + + shaderManager_->DirtyLastShader(); + + /* + glUseProgram(depal->program); + + // Restore will rebind all of the state below. + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + transformDraw_->BindBuffer(pos, sizeof(pos), uv, sizeof(uv)); + transformDraw_->BindElementBuffer(indices, sizeof(indices)); + } else { + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + glEnableVertexAttribArray(depal->a_position); + glEnableVertexAttribArray(depal->a_texcoord0); + + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, clutTexture); + glActiveTexture(GL_TEXTURE0); + + framebufferManager_->BindFramebufferColor(GL_TEXTURE0, gstate.getFrameBufRawAddress(), framebuffer, BINDFBCOLOR_SKIP_COPY); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + glstate.blend.force(false); + glstate.colorMask.force(true, true, true, true); + glstate.scissorTest.force(false); + glstate.cullFace.force(false); + glstate.depthTest.force(false); + glstate.stencilTest.force(false); +#if !defined(USING_GLES2) + glstate.colorLogicOp.force(false); +#endif + glViewport(0, 0, framebuffer->renderWidth, framebuffer->renderHeight); + + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + glVertexAttribPointer(depal->a_position, 3, GL_FLOAT, GL_FALSE, 12, 0); + glVertexAttribPointer(depal->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, (void *)sizeof(pos)); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, 0); + } else { + glVertexAttribPointer(depal->a_position, 3, GL_FLOAT, GL_FALSE, 12, pos); + glVertexAttribPointer(depal->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, uv); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, indices); + } + glDisableVertexAttribArray(depal->a_position); + glDisableVertexAttribArray(depal->a_texcoord0); + */ + //depalFBO->EndPass(cmd); + //depalFBO->TransitionToTexture(cmd); + //imageView = depalFBO->GetColorImageView(); + } + + /* + imageView = depalFBO->GetColorImageView(); + + SamplerCacheKey samplerKey; + framebufferManager_->RebindFramebuffer(); + SetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight, samplerKey); + sampler = GetOrCreateSampler(samplerKey); + */ + + SamplerCacheKey key; + UpdateSamplingParams(*nextTexture_, key); + key.mipEnable = false; + sampler = samplerCache_.GetOrCreateSampler(key); + + lastBoundTexture = nullptr; +} + +bool TextureCacheVulkan::SetOffsetTexture(u32 offset) { + if (g_Config.iRenderingMode != FB_BUFFERED_MODE) { + return false; + } + u32 texaddr = gstate.getTextureAddress(0); + if (!Memory::IsValidAddress(texaddr) || !Memory::IsValidAddress(texaddr + offset)) { + return false; + } + + const u16 dim = gstate.getTextureDimension(0); + u64 cachekey = ((u64)(texaddr & 0x3FFFFFFF) << 32) | dim; + TexCache::iterator iter = cache.find(cachekey); + if (iter == cache.end()) { + return false; + } + TexCacheEntry *entry = &iter->second; + + bool success = false; + for (size_t i = 0, n = fbCache_.size(); i < n; ++i) { + auto framebuffer = fbCache_[i]; + if (AttachFramebuffer(entry, framebuffer->fb_address, framebuffer, offset)) { + success = true; + } + } + + if (success && entry->framebuffer) { + // This will not apply the texture immediately. + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return true; + } + + return false; +} + +void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { +#ifdef DEBUG_TEXTURES + if (SetDebugTexture()) { + // A different texture was bound, let's rebind next time. + lastBoundTexture = nullptr; + return; + } +#endif + + u32 texaddr = gstate.getTextureAddress(0); + if (!Memory::IsValidAddress(texaddr)) { + // Bind a null texture and return. + lastBoundTexture = nullptr; + return; + } + + const u16 dim = gstate.getTextureDimension(0); + int w = gstate.getTextureWidth(0); + int h = gstate.getTextureHeight(0); + if (texaddr == 0x04000000 && w == 2 && h == 2) { + // Nonsense bootup texture. Discard. + } + + GETextureFormat format = gstate.getTextureFormat(); + if (format >= 11) { + ERROR_LOG_REPORT(G3D, "Unknown texture format %i", format); + // TODO: Better assumption? + format = GE_TFMT_5650; + } + bool hasClut = gstate.isTextureFormatIndexed(); + + // Ignore uncached/kernel when caching. + u64 cachekey = ((u64)(texaddr & 0x3FFFFFFF) << 32) | dim; + u32 cluthash; + if (hasClut) { + if (clutLastFormat_ != gstate.clutformat) { + // We update here because the clut format can be specified after the load. + UpdateCurrentClut(gstate.getClutPaletteFormat(), gstate.getClutIndexStartPos(), gstate.isClutIndexSimple()); + } + cluthash = GetCurrentClutHash() ^ gstate.clutformat; + cachekey ^= cluthash; + } else { + cluthash = 0; + } + + int bufw = GetTextureBufw(0, texaddr, format); + u8 maxLevel = gstate.getTextureMaxLevel(); + + u32 texhash = MiniHash((const u32 *)Memory::GetPointerUnchecked(texaddr)); + u32 fullhash = 0; + + TexCache::iterator iter = cache.find(cachekey); + TexCacheEntry *entry = NULL; + gstate_c.needShaderTexClamp = false; + gstate_c.skipDrawReason &= ~SKIPDRAW_BAD_FB_TEXTURE; + bool replaceImages = false; + + if (iter != cache.end()) { + entry = &iter->second; + // Validate the texture still matches the cache entry. + bool match = entry->Matches(dim, format, maxLevel); + const char *reason = "different params"; + + // Check for FBO - slow! + if (entry->framebuffer) { + if (match) { + if (hasClut && clutRenderAddress_ != 0xFFFFFFFF) { + WARN_LOG_REPORT_ONCE(clutAndTexRender, G3D, "Using rendered texture with rendered CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat()); + } + + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return; + } else { + // Make sure we re-evaluate framebuffers. + DetachFramebuffer(entry, texaddr, entry->framebuffer); + reason = "detached framebuf"; + match = false; + } + } + + bool rehash = entry->GetHashStatus() == TexCacheEntry::STATUS_UNRELIABLE; + bool doDelete = true; + + // First let's see if another texture with the same address had a hashfail. + if (entry->status & TexCacheEntry::STATUS_CLUT_RECHECK) { + // Always rehash in this case, if one changed the rest all probably did. + rehash = true; + entry->status &= ~TexCacheEntry::STATUS_CLUT_RECHECK; + } else if ((gstate_c.textureChanged & TEXCHANGE_UPDATED) == 0) { + // Okay, just some parameter change - the data didn't change, no need to rehash. + rehash = false; + } + + if (match) { + if (entry->lastFrame != gpuStats.numFlips) { + u32 diff = gpuStats.numFlips - entry->lastFrame; + entry->numFrames++; + + if (entry->framesUntilNextFullHash < diff) { + // Exponential backoff up to 512 frames. Textures are often reused. + if (entry->numFrames > 32) { + // Also, try to add some "randomness" to avoid rehashing several textures the same frame. + entry->framesUntilNextFullHash = std::min(512, entry->numFrames) + (entry->textureName & 15); + } else { + entry->framesUntilNextFullHash = entry->numFrames; + } + rehash = true; + } else { + entry->framesUntilNextFullHash -= diff; + } + } + + // If it's not huge or has been invalidated many times, recheck the whole texture. + if (entry->invalidHint > 180 || (entry->invalidHint > 15 && (dim >> 8) < 9 && (dim & 0xF) < 9)) { + entry->invalidHint = 0; + rehash = true; + } + + bool hashFail = false; + if (texhash != entry->hash) { + fullhash = QuickTexHash(texaddr, bufw, w, h, format, entry); + hashFail = true; + rehash = false; + } + + if (rehash && entry->GetHashStatus() != TexCacheEntry::STATUS_RELIABLE) { + fullhash = QuickTexHash(texaddr, bufw, w, h, format, entry); + if (fullhash != entry->fullhash) { + hashFail = true; + } else { + if (g_Config.bTextureBackoffCache) { + if (entry->GetHashStatus() != TexCacheEntry::STATUS_HASHING && entry->numFrames > TexCacheEntry::FRAMES_REGAIN_TRUST) { + // Reset to STATUS_HASHING. + entry->SetHashStatus(TexCacheEntry::STATUS_HASHING); + entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } else if (entry->numFrames > TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST) { + entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + } + + if (hashFail) { + match = false; + reason = "hash fail"; + entry->status |= TexCacheEntry::STATUS_UNRELIABLE; + if (entry->numFrames < TEXCACHE_FRAME_CHANGE_FREQUENT) { + if (entry->status & TexCacheEntry::STATUS_FREE_CHANGE) { + entry->status &= ~TexCacheEntry::STATUS_FREE_CHANGE; + } else { + entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + entry->numFrames = 0; + + // Don't give up just yet. Let's try the secondary cache if it's been invalidated before. + // If it's failed a bunch of times, then the second cache is just wasting time and VRAM. + if (g_Config.bTextureSecondaryCache) { + if (entry->numInvalidated > 2 && entry->numInvalidated < 128 && !lowMemoryMode_) { + u64 secondKey = fullhash | (u64)cluthash << 32; + TexCache::iterator secondIter = secondCache.find(secondKey); + if (secondIter != secondCache.end()) { + TexCacheEntry *secondEntry = &secondIter->second; + if (secondEntry->Matches(dim, format, maxLevel)) { + // Reset the numInvalidated value lower, we got a match. + if (entry->numInvalidated > 8) { + --entry->numInvalidated; + } + entry = secondEntry; + match = true; + } + } else { + secondKey = entry->fullhash | ((u64)entry->cluthash << 32); + secondCacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + secondCache[secondKey] = *entry; + doDelete = false; + } + } + } + } + } + + if (match && (entry->status & TexCacheEntry::STATUS_TO_SCALE) && g_Config.iTexScalingLevel != 1 && texelsScaledThisFrame_ < TEXCACHE_MAX_TEXELS_SCALED) { + if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) { + // INFO_LOG(G3D, "Reloading texture to do the scaling we skipped.."); + match = false; + reason = "scaling"; + } + } + + if (match) { + // TODO: Mark the entry reliable if it's been safe for long enough? + //got one! + entry->lastFrame = gpuStats.numFlips; + if (entry->vkTex != lastBoundTexture) { + gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; + } + nextTexture_ = entry; + VERBOSE_LOG(G3D, "Texture at %08x Found in Cache, applying", texaddr); + return; //Done! + } else { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + entry->numInvalidated++; + gpuStats.numTextureInvalidations++; + DEBUG_LOG(G3D, "Texture different or overwritten, reloading at %08x: %s", texaddr, reason); + if (doDelete) { + if (entry->maxLevel == maxLevel && entry->dim == gstate.getTextureDimension(0) && entry->format == format && g_Config.iTexScalingLevel == 1) { + // Actually, if size and number of levels match, let's try to avoid deleting and recreating. + // Instead, let's use glTexSubImage to replace the images. + replaceImages = true; + } else { + if (entry->vkTex == lastBoundTexture) { + lastBoundTexture = nullptr; + } + delete entry->vkTex; + entry->vkTex = nullptr; + } + } + // Clear the reliable bit if set. + if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + entry->SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + + // Also, mark any textures with the same address but different clut. They need rechecking. + if (cluthash != 0) { + const u64 cachekeyMin = (u64)(texaddr & 0x3FFFFFFF) << 32; + const u64 cachekeyMax = cachekeyMin + (1ULL << 32); + for (auto it = cache.lower_bound(cachekeyMin), end = cache.upper_bound(cachekeyMax); it != end; ++it) { + if (it->second.cluthash != cluthash) { + it->second.status |= TexCacheEntry::STATUS_CLUT_RECHECK; + } + } + } + } + } else { + VERBOSE_LOG(G3D, "No texture in cache, decoding..."); + TexCacheEntry entryNew = { 0 }; + cache[cachekey] = entryNew; + + if (hasClut && clutRenderAddress_ != 0xFFFFFFFF) { + WARN_LOG_REPORT_ONCE(clutUseRender, G3D, "Using texture with rendered CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat()); + } + + entry = &cache[cachekey]; + if (g_Config.bTextureBackoffCache) { + entry->status = TexCacheEntry::STATUS_HASHING; + } else { + entry->status = TexCacheEntry::STATUS_UNRELIABLE; + } + } + + if ((bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && texaddr >= PSP_GetKernelMemoryEnd()) { + ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff); + // Proceeding here can cause a crash. + nextTexture_ = nullptr; + return; + } + + // We have to decode it, let's setup the cache entry first. + entry->addr = texaddr; + entry->hash = texhash; + entry->format = format; + entry->lastFrame = gpuStats.numFlips; + entry->framebuffer = 0; + entry->maxLevel = maxLevel; + entry->lodBias = 0.0f; + + entry->dim = gstate.getTextureDimension(0); + entry->bufw = bufw; + + // This would overestimate the size in many case so we underestimate instead + // to avoid excessive clearing caused by cache invalidations. + entry->sizeInRAM = (textureBitsPerPixel[format] * bufw * h / 2) / 8; + + entry->fullhash = fullhash == 0 ? QuickTexHash(texaddr, bufw, w, h, format, entry) : fullhash; + entry->cluthash = cluthash; + + entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK; + + gstate_c.curTextureWidth = w; + gstate_c.curTextureHeight = h; + + // For the estimate, we assume cluts always point to 8888 for simplicity. + cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + + // Before we go reading the texture from memory, let's check for render-to-texture. + for (size_t i = 0, n = fbCache_.size(); i < n; ++i) { + auto framebuffer = fbCache_[i]; + AttachFramebuffer(entry, framebuffer->fb_address, framebuffer); + } + + // If we ended up with a framebuffer, attach it - no texture decoding needed. + if (entry->framebuffer) { + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return; + } + + // Adjust maxLevel to actually present levels.. + bool badMipSizes = false; + for (u32 i = 0; i <= maxLevel; i++) { + // If encountering levels pointing to nothing, adjust max level. + u32 levelTexaddr = gstate.getTextureAddress(i); + if (!Memory::IsValidAddress(levelTexaddr)) { + maxLevel = i - 1; + break; + } + + if (i > 0 && gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + int tw = gstate.getTextureWidth(i); + int th = gstate.getTextureHeight(i); + if (tw != 1 && tw != (gstate.getTextureWidth(i - 1) >> 1)) + badMipSizes = true; + else if (th != 1 && th != (gstate.getTextureHeight(i - 1) >> 1)) + badMipSizes = true; + } + } + + // In addition, simply don't load more than level 0 if g_Config.bMipMap is false. + if (!g_Config.bMipMap || badMipSizes) { + maxLevel = 0; + } + + // Disable mipmapping. Something is wrong. + // maxLevel = 0; + + // If GLES3 is available, we can preallocate the storage, which makes texture loading more efficient. + VkFormat dstFmt = GetDestFormat(format, gstate.getClutPaletteFormat()); + + int scaleFactor; + // Auto-texture scale upto 5x rendering resolution + if (g_Config.iTexScalingLevel == 0) { + scaleFactor = g_Config.iInternalResolution; + if (scaleFactor == 0) { + scaleFactor = (PSP_CoreParameter().renderWidth + 479) / 480; + } + + // Mobile devices don't get the higher scale factors, too expensive. Very rough way to decide though... + if (!gstate_c.Supports(GPU_IS_MOBILE)) { + bool supportNpot = gstate_c.Supports(GPU_SUPPORTS_OES_TEXTURE_NPOT); + scaleFactor = std::min(supportNpot ? 5 : 4, scaleFactor); + if (!supportNpot && scaleFactor == 3) { + scaleFactor = 2; + } + } else { + scaleFactor = std::min(gstate_c.Supports(GPU_SUPPORTS_OES_TEXTURE_NPOT) ? 3 : 2, scaleFactor); + } + } else { + scaleFactor = g_Config.iTexScalingLevel; + } + + // Rachet down scale factor in low-memory mode. + if (lowMemoryMode_) { + // Keep it even, though, just in case of npot troubles. + scaleFactor = scaleFactor > 4 ? 4 : (scaleFactor > 2 ? 2 : 1); + } + + // Don't scale the PPGe texture. + if (entry->addr > 0x05000000 && entry->addr < 0x08800000) + scaleFactor = 1; + if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0) { + // Remember for later that we /wanted/ to scale this texture. + entry->status |= TexCacheEntry::STATUS_TO_SCALE; + scaleFactor = 1; + } + + if (scaleFactor != 1) { + if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED) { + entry->status |= TexCacheEntry::STATUS_TO_SCALE; + scaleFactor = 1; + } else { + entry->status &= ~TexCacheEntry::STATUS_TO_SCALE; + texelsScaledThisFrame_ += w * h; + } + } + + // Ready or not, here I go... + if (replaceImages) { + if (!entry->vkTex) { + Crash(); + } + } else { + entry->vkTex = new CachedTextureVulkan(); + entry->vkTex->texture_ = new VulkanTexture(vulkan_); + VulkanTexture *image = entry->vkTex->texture_; + image->CreateDirect(w, h, maxLevel + 1, dstFmt); + } + lastBoundTexture = entry->vkTex; + + // Upload the texture data. + for (int i = 0; i <= maxLevel; i++) { + int mipWidth = gstate.getTextureWidth(i); + int mipHeight = gstate.getTextureHeight(i); + int bpp = dstFmt == VULKAN_8888_FORMAT ? 4 : 2; + int stride = (mipWidth * bpp + 15) & ~15; + int size = stride * mipHeight; + uint32_t bufferOffset; + VkBuffer texBuf; + void *data = uploadBuffer->Push(size, &bufferOffset, &texBuf); + LoadTextureLevel(*entry, (uint8_t *)data, stride, i, replaceImages, scaleFactor, dstFmt); + entry->vkTex->texture_->UploadMip(i, mipWidth, mipHeight, texBuf, bufferOffset, stride / bpp); + } + + gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; + + nextTexture_ = entry; +} + +VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const { + switch (format) { + case GE_TFMT_CLUT4: + case GE_TFMT_CLUT8: + case GE_TFMT_CLUT16: + case GE_TFMT_CLUT32: + return getClutDestFormatVulkan(clutFormat); + case GE_TFMT_4444: + return VULKAN_4444_FORMAT; + case GE_TFMT_5551: + return VULKAN_1555_FORMAT; + case GE_TFMT_5650: + return VULKAN_565_FORMAT; + case GE_TFMT_8888: + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + default: + return VULKAN_8888_FORMAT; + } +} + +void *TextureCacheVulkan::DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufwout) { + void *finalBuf = NULL; + + u32 texaddr = gstate.getTextureAddress(level); + bool swizzled = gstate.isTextureSwizzled(); + if ((texaddr & 0x00600000) != 0 && Memory::IsVRAMAddress(texaddr)) { + // This means it's in a mirror, possibly a swizzled mirror. Let's report. + WARN_LOG_REPORT_ONCE(texmirror, G3D, "Decoding texture from VRAM mirror at %08x swizzle=%d", texaddr, swizzled ? 1 : 0); + if ((texaddr & 0x00200000) == 0x00200000) { + // Technically 2 and 6 are slightly different, but this is better than nothing probably. + swizzled = !swizzled; + } + // Note that (texaddr & 0x00600000) == 0x00600000 is very likely to be depth texturing. + } + + int bufw = GetTextureBufw(level, texaddr, format); + if (bufwout) + *bufwout = bufw; + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + const u8 *texptr = Memory::GetPointer(texaddr); + + switch (format) { + case GE_TFMT_CLUT4: + { + const bool mipmapShareClut = gstate.isClutSharedForMipmaps(); + const int clutSharingOffset = mipmapShareClut ? 0 : level * 16; + + switch (clutformat) { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + tmpTexBuf16.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u16 *clut = GetCurrentClut() + clutSharingOffset; + texByteAlign = 2; + if (!swizzled) { + if (clutAlphaLinear_ && mipmapShareClut) { + DeIndexTexture4Optimal(tmpTexBuf16.data(), texptr, bufw * h, clutAlphaLinearColor_); + } else { + DeIndexTexture4(tmpTexBuf16.data(), texptr, bufw * h, clut); + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + UnswizzleFromMem(texptr, bufw, h, 0); + if (clutAlphaLinear_ && mipmapShareClut) { + DeIndexTexture4Optimal(tmpTexBuf16.data(), (const u8 *)tmpTexBuf32.data(), bufw * h, clutAlphaLinearColor_); + } else { + DeIndexTexture4(tmpTexBuf16.data(), (const u8 *)tmpTexBuf32.data(), bufw * h, clut); + } + } + finalBuf = tmpTexBuf16.data(); + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u32 *clut = GetCurrentClut() + clutSharingOffset; + if (!swizzled) { + DeIndexTexture4(tmpTexBuf32.data(), texptr, bufw * h, clut); + finalBuf = tmpTexBuf32.data(); + } else { + UnswizzleFromMem(texptr, bufw, h, 0); + // Let's reuse tmpTexBuf16, just need double the space. + tmpTexBuf16.resize(std::max(bufw, w) * h * 2); + DeIndexTexture4((u32 *)tmpTexBuf16.data(), (u8 *)tmpTexBuf32.data(), bufw * h, clut); + finalBuf = tmpTexBuf16.data(); + } + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unknown CLUT4 texture mode %d", gstate.getClutPaletteFormat()); + return NULL; + } + } + break; + + case GE_TFMT_CLUT8: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 1, dstFmt, bufw); + break; + + case GE_TFMT_CLUT16: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 2, dstFmt, bufw); + break; + + case GE_TFMT_CLUT32: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 4, dstFmt, bufw); + break; + + case GE_TFMT_4444: + case GE_TFMT_5551: + case GE_TFMT_5650: + texByteAlign = 2; + + if (!swizzled) { + int len = std::max(bufw, w) * h; + tmpTexBuf16.resize(len); + tmpTexBufRearrange.resize(len); + finalBuf = tmpTexBuf16.data(); + ConvertColors(finalBuf, texptr, dstFmt, bufw * h); + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + finalBuf = UnswizzleFromMem(texptr, bufw, h, 2); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_8888: + if (!swizzled) { + // Special case: if we don't need to deal with packing, we don't need to copy. + if (scaleFactor == 1 || w == bufw) { + finalBuf = (void *)texptr; + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, texptr, dstFmt, bufw * h); + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + finalBuf = UnswizzleFromMem(texptr, bufw, h, 4); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_DXT1: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT1Block *src = (DXT1Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT1Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + w = (w + 3) & ~3; + } + break; + + case GE_TFMT_DXT3: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT3Block *src = (DXT3Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT3Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + w = (w + 3) & ~3; + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_DXT5: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT5Block *src = (DXT5Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT5Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + w = (w + 3) & ~3; + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unknown Texture Format %d!!!", format); + return NULL; + } + + if (!finalBuf) { + ERROR_LOG_REPORT(G3D, "NO finalbuf! Will crash!"); + } + + return finalBuf; +} + +TextureCacheVulkan::TexCacheEntry::Status TextureCacheVulkan::CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h) { + CheckAlphaResult res; + switch (dstFmt) { + case VULKAN_4444_FORMAT: + res = CheckAlphaABGR4444Basic(pixelData, stride, w, h); + break; + case VULKAN_1555_FORMAT: + res = CheckAlphaABGR1555Basic(pixelData, stride, w, h); + break; + case VULKAN_565_FORMAT: + // Never has any alpha. + res = CHECKALPHA_FULL; + break; + default: + res = CheckAlphaRGBA8888Basic(pixelData, stride, w, h); + break; + } + + return (TexCacheEntry::Status)res; +} + +void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, uint8_t *writePtr, int rowPitch, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt) { + CachedTextureVulkan *tex = entry.vkTex; + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + u32 *pixelData; + int decPitch; + int rowBytes; + { + PROFILE_THIS_SCOPE("decodetex"); + + u32 texByteAlign = 1; + GETextureFormat tfmt = (GETextureFormat)entry.format; + GEPaletteFormat clutformat = gstate.getClutPaletteFormat(); + int bufw; + void *finalBuf = DecodeTextureLevel(tfmt, clutformat, level, texByteAlign, dstFmt, scaleFactor, &bufw); + if (finalBuf == NULL) { + return; + } + decPitch = bufw * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); + rowBytes = w * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); + gpuStats.numTexturesDecoded++; + + pixelData = (u32 *)finalBuf; + if (scaleFactor > 1) { + u32 fmt = dstFmt; + scaler.Scale(pixelData, fmt, w, h, scaleFactor); + dstFmt = (VkFormat)fmt; + } + + if ((entry.status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) { + TexCacheEntry::Status alphaStatus = CheckAlpha(pixelData, dstFmt, bufw, w, h); + entry.SetAlphaStatus(alphaStatus, level); + } else { + entry.SetAlphaStatus(TexCacheEntry::STATUS_ALPHA_UNKNOWN); + } + } + + if (replaceImages) { + // TODO: No support for texture shadows + // DebugBreak(); + } + + PROFILE_THIS_SCOPE("loadtex"); + for (int y = 0; y < h; y++) { + memcpy(writePtr + rowPitch * y, (const uint8_t *)pixelData + decPitch * y, rowBytes); + // uncomment to make all textures white for debugging + //memset(writePtr + rowPitch * y, 0xff, rowBytes); + } + + /* + if (!lowMemoryMode_) { + GLenum err = glGetError(); + if (err == GL_OUT_OF_MEMORY) { + WARN_LOG_REPORT(G3D, "Texture cache ran out of GPU memory; switching to low memory mode"); + lowMemoryMode_ = true; + decimationCounter_ = 0; + Decimate(); + // TODO: We need to stall the GPU here and wipe things out of memory. + + // Try again, now that we've cleared out textures in lowMemoryMode_. + glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); + + I18NCategory *err = GetI18NCategory("Error"); + if (scaleFactor > 1) { + osm.Show(err->T("Warning: Video memory FULL, reducing upscaling and switching to slow caching mode"), 2.0f); + } else { + osm.Show(err->T("Warning: Video memory FULL, switching to slow caching mode"), 2.0f); + } + } else if (err != GL_NO_ERROR) { + // We checked the err anyway, might as well log if there is one. + WARN_LOG(G3D, "Got an error in texture upload: %08x", err); + } + }*/ +} diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h new file mode 100644 index 0000000000..8a4998aa32 --- /dev/null +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -0,0 +1,184 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "Globals.h" +#include "GPU/GPUInterface.h" +#include "GPU/GPUState.h" +#include "Common/Vulkan/VulkanContext.h" +#include "GPU/Vulkan/TextureScalerVulkan.h" +#include "GPU/Common/TextureCacheCommon.h" + +struct VirtualFramebuffer; +class FramebufferManagerVulkan; +class DepalShaderCacheVulkan; +class ShaderManagerVulkan; +class DrawEngineVulkan; + +class VulkanContext; +class VulkanTexture; +class VulkanPushBuffer; + +struct SamplerCacheKey { + SamplerCacheKey() : fullKey(0) {} + + union { + u32 fullKey; + struct { + bool mipEnable : 1; + bool minFilt : 1; + bool mipFilt : 1; + bool magFilt : 1; + bool sClamp : 1; + bool tClamp : 1; + int lodBias : 4; + int maxLevel : 4; + }; + }; + + bool operator < (const SamplerCacheKey &other) const { + return fullKey < other.fullKey; + } +}; + +class CachedTextureVulkan { +public: + CachedTextureVulkan() : texture_(nullptr) { + } + ~CachedTextureVulkan(); + + // TODO: Switch away from VulkanImage to some kind of smart suballocating texture pool. + VulkanTexture *texture_; +}; + +class SamplerCache { +public: + SamplerCache(VulkanContext *vulkan) : vulkan_(vulkan) {} + ~SamplerCache(); + VkSampler GetOrCreateSampler(const SamplerCacheKey &key); + +private: + VulkanContext *vulkan_; + std::map cache_; +}; + + +class TextureCacheVulkan : public TextureCacheCommon { +public: + TextureCacheVulkan(VulkanContext *vulkan); + ~TextureCacheVulkan(); + + void SetTexture(VulkanPushBuffer *uploadBuffer); + virtual bool SetOffsetTexture(u32 offset) override; + + void Clear(bool delete_them); + void StartFrame(); + void Invalidate(u32 addr, int size, GPUInvalidationType type); + void InvalidateAll(GPUInvalidationType type); + void ClearNextFrame(); + + void SetFramebufferManager(FramebufferManagerVulkan *fbManager) { + framebufferManager_ = fbManager; + } + void SetDepalShaderCache(DepalShaderCacheVulkan *dpCache) { + depalShaderCache_ = dpCache; + } + void SetShaderManager(ShaderManagerVulkan *sm) { + shaderManager_ = sm; + } + void SetTransformDrawEngine(DrawEngineVulkan *td) { + transformDraw_ = td; + } + + size_t NumLoadedTextures() const { + return cache.size(); + } + + void ForgetLastTexture() { + lastBoundTexture = nullptr; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + } + + void ApplyTexture(VkImageView &imageView, VkSampler &sampler); + +protected: + void DownloadFramebufferForClut(u32 clutAddr, u32 bytes); + +private: + void Decimate(); // Run this once per frame to get rid of old textures. + void DeleteTexture(TexCache::iterator it); + void *ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw); + void UpdateSamplingParams(TexCacheEntry &entry, SamplerCacheKey &key); + void LoadTextureLevel(TexCacheEntry &entry, uint8_t *writePtr, int rowPitch, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt); + VkFormat GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const; + void *DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufw = 0); + TexCacheEntry::Status CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h); + template + const T *GetCurrentClut(); + u32 GetCurrentClutHash(); + void UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple); + bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override; + void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override; + void SetTextureFramebuffer(TexCacheEntry *entry, VirtualFramebuffer *framebuffer); + void ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEntry *entry, VirtualFramebuffer *framebuffer, VkImageView &image, VkSampler &sampler); + void SetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight, SamplerCacheKey &key); + + VulkanContext *vulkan_; + + TexCache secondCache; + std::vector nameCache_; + u32 cacheSizeEstimate_; + u32 secondCacheSizeEstimate_; + + // Separate to keep main texture cache size down. + struct AttachedFramebufferInfo { + u32 xOffset; + u32 yOffset; + }; + std::map fbTexInfo_; + void AttachFramebufferValid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo); + void AttachFramebufferInvalid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo); + + bool clearCacheNextFrame_; + bool lowMemoryMode_; + + SamplerCache samplerCache_; + + TextureScalerVulkan scaler; + + u32 *clutBuf_; + u32 clutHash_; + // True if the clut is just alpha values in the same order (RGBA4444-bit only.) + bool clutAlphaLinear_; + u16 clutAlphaLinearColor_; + + CachedTextureVulkan *lastBoundTexture; + + int decimationCounter_; + int texelsScaledThisFrame_; + int timesInvalidatedAllThisFrame_; + + FramebufferManagerVulkan *framebufferManager_; + DepalShaderCacheVulkan *depalShaderCache_; + ShaderManagerVulkan *shaderManager_; + DrawEngineVulkan *transformDraw_; +}; + +VkFormat getClutDestFormatVulkan(GEPaletteFormat format); diff --git a/GPU/Vulkan/TextureScalerVulkan.cpp b/GPU/Vulkan/TextureScalerVulkan.cpp new file mode 100644 index 0000000000..267538846c --- /dev/null +++ b/GPU/Vulkan/TextureScalerVulkan.cpp @@ -0,0 +1,62 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#if _MSC_VER == 1700 +// Has to be included before TextureScaler.h, else we get those std::bind errors in VS2012.. +#include "../native/base/basictypes.h" +#endif + +#include +#include "gfx/gl_common.h" + +#include "GPU/Common/TextureScalerCommon.h" +#include "GPU/Vulkan/TextureScalerVulkan.h" +#include "Common/ColorConv.h" +#include "Common/Log.h" +#include "Common/ThreadPools.h" + +int TextureScalerVulkan::BytesPerPixel(u32 format) { + return (format == GL_UNSIGNED_BYTE) ? 4 : 2; +} + +u32 TextureScalerVulkan::Get8888Format() { + return GL_UNSIGNED_BYTE; +} + +void TextureScalerVulkan::ConvertTo8888(u32 format, u32* source, u32* &dest, int width, int height) { + switch (format) { + case GL_UNSIGNED_BYTE: + dest = source; // already fine + break; + + case GL_UNSIGNED_SHORT_4_4_4_4: + GlobalThreadPool::Loop(std::bind(&convert4444_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + case GL_UNSIGNED_SHORT_5_6_5: + GlobalThreadPool::Loop(std::bind(&convert565_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + case GL_UNSIGNED_SHORT_5_5_5_1: + GlobalThreadPool::Loop(std::bind(&convert5551_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + default: + dest = source; + ERROR_LOG(G3D, "iXBRZTexScaling: unsupported texture format"); + } +} diff --git a/GPU/Vulkan/TextureScalerVulkan.h b/GPU/Vulkan/TextureScalerVulkan.h new file mode 100644 index 0000000000..abb4dc4960 --- /dev/null +++ b/GPU/Vulkan/TextureScalerVulkan.h @@ -0,0 +1,27 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/CommonTypes.h" +#include "GPU/Common/TextureScalerCommon.h" + +class TextureScalerVulkan : public TextureScaler { + void ConvertTo8888(u32 format, u32* source, u32* &dest, int width, int height) override; + int BytesPerPixel(u32 format) override; + u32 Get8888Format() override; +}; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp new file mode 100644 index 0000000000..6417060276 --- /dev/null +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -0,0 +1,512 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include +#include + +#include "gfx_es2/gpu_features.h" + +#if defined(_WIN32) && defined(_DEBUG) +#include "Common/CommonWindows.h" +#endif + +#include "base/stringutil.h" +#include "Common/Vulkan/VulkanLoader.h" +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" + +static const char *vulkan_glsl_preamble = +"#version 400\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n\n"; + +// "Varying" layout - must match fragment shader +// color0 = 0 +// color1 = 1 +// texcoord = 2 +// fog = 3 + + + + +// SDL 1.2 on Apple does not have support for OpenGL 3 and hence needs +// special treatment in the shader generator. +#ifdef __APPLE__ +#define FORCE_OPENGL_2_0 +#endif + +#undef WRITE + +#define WRITE p+=sprintf + +static const char * const boneWeightDecl[9] = { + "#ERROR#", + "layout(location = 3) in float w1;\n", + "layout(location = 3) in vec2 w1;\n", + "layout(location = 3) in vec3 w1;\n", + "layout(location = 3) in vec4 w1;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in float w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec2 w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec3 w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec4 w2;\n", +}; + +enum DoLightComputation { + LIGHT_OFF, + LIGHT_SHADE, + LIGHT_FULL, +}; + +// Depth range and viewport +// +// After the multiplication with the projection matrix, we have a 4D vector in clip space. +// In OpenGL, Z is from -1 to 1, while in D3D, Z is from 0 to 1. +// PSP appears to use the OpenGL convention. As Z is from -1 to 1, and the viewport is represented +// by a center and a scale, to find the final Z value, all we need to do is to multiply by ZScale and +// add ZCenter - these are properly scaled to directly give a Z value in [0, 65535]. +// +// z = vec.z * ViewportZScale + ViewportZCenter; +// +// That will give us the final value between 0 and 65535, which we can simply floor to simulate +// the limited precision of the PSP's depth buffer. Then we convert it back: +// z = floor(z); +// +// vec.z = (z - ViewportZCenter) / ViewportZScale; +// +// Now, the regular machinery will take over and do the calculation again. +// +// All this above is for full transform mode. +// In through mode, the Z coordinate just goes straight through and there is no perspective division. +// We simulate this of course with pretty much an identity matrix. Rounding Z becomes very easy. +// +// TODO: Skip all this if we can actually get a 16-bit depth buffer along with stencil, which +// is a bit of a rare configuration, although quite common on mobile. + +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer, bool *usesLighting) { + char *p = buffer; + + // #define USE_FOR_LOOP + + WRITE(p, "%s", vulkan_glsl_preamble); + + bool highpFog = false; + bool highpTexcoord = false; + + bool isModeThrough = id.Bit(VS_BIT_IS_THROUGH); + bool lmode = id.Bit(VS_BIT_LMODE) && !isModeThrough; // TODO: Different expression than in shaderIDgen + bool doTexture = id.Bit(VS_BIT_DO_TEXTURE); + bool doTextureProjection = id.Bit(VS_BIT_DO_TEXTURE_PROJ); + + GETexMapMode uvGenMode = static_cast(id.Bits(VS_BIT_UVGEN_MODE, 2)); + + // this is only valid for some settings of uvGenMode + GETexProjMapMode uvProjMode = static_cast(id.Bits(VS_BIT_UVPROJ_MODE, 2)); + bool doShadeMapping = uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP; + bool doFlatShading = id.Bit(VS_BIT_FLATSHADE); + + bool useHWTransform = id.Bit(VS_BIT_USE_HW_TRANSFORM); + bool hasColor = id.Bit(VS_BIT_HAS_COLOR) || !useHWTransform; + bool hasNormal = id.Bit(VS_BIT_HAS_NORMAL) && useHWTransform; + bool hasTexcoord = id.Bit(VS_BIT_HAS_TEXCOORD) || !useHWTransform; + bool enableFog = id.Bit(VS_BIT_ENABLE_FOG); + bool throughmode = id.Bit(VS_BIT_IS_THROUGH); + bool flipNormal = id.Bit(VS_BIT_NORM_REVERSE); + int ls0 = id.Bits(VS_BIT_LS0, 2); + int ls1 = id.Bits(VS_BIT_LS1, 2); + bool enableBones = id.Bit(VS_BIT_ENABLE_BONES); + bool enableLighting = id.Bit(VS_BIT_LIGHTING_ENABLE); + int matUpdate = id.Bits(VS_BIT_MATERIAL_UPDATE, 3); + + // The uniforms are passed in as three "clumps" that may or may not be present. + // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts + // are present and what parts aren't, but we will not be ultra detailed about it. + *usesLighting = enableLighting || doShadeMapping; + WRITE(p, "\n"); + WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s} base;\n", ub_baseStr); + if (enableLighting || doShadeMapping) + WRITE(p, "layout (std140, set = 0, binding = 3) uniform lightVars {\n%s} light;\n", ub_vs_lightsStr); + if (enableBones) + WRITE(p, "layout (std140, set = 0, binding = 4) uniform boneVars {\n%s} bone;\n", ub_vs_bonesStr); + + const char *shading = doFlatShading ? "flat " : ""; + + DoLightComputation doLight[4] = { LIGHT_OFF, LIGHT_OFF, LIGHT_OFF, LIGHT_OFF }; + if (useHWTransform) { + int shadeLight0 = doShadeMapping ? ls0 : -1; + int shadeLight1 = doShadeMapping ? ls1 : -1; + for (int i = 0; i < 4; i++) { + if (i == shadeLight0 || i == shadeLight1) + doLight[i] = LIGHT_SHADE; + if (id.Bit(VS_BIT_LIGHTING_ENABLE) && id.Bit(VS_BIT_LIGHT0_ENABLE + i)) + doLight[i] = LIGHT_FULL; + } + } + + int numBoneWeights = 0; + int boneWeightScale = id.Bits(VS_BIT_WEIGHT_FMTSCALE, 2); + if (enableBones) { + numBoneWeights = 1 + id.Bits(VS_BIT_BONES, 3); + WRITE(p, "%s", boneWeightDecl[numBoneWeights]); + } + int texFmtScale = id.Bits(VS_BIT_TEXCOORD_FMTSCALE, 2); + + if (useHWTransform) + WRITE(p, "layout (location = %d) in vec3 position;\n", PspAttributeLocation::POSITION); + else + // we pass the fog coord in w + WRITE(p, "layout (location = %d) in vec4 position;\n", PspAttributeLocation::POSITION); + + if (useHWTransform && hasNormal) + WRITE(p, "layout (location = %d) in vec3 normal;\n", PspAttributeLocation::NORMAL); + + if (doTexture && hasTexcoord) { + if (!useHWTransform && doTextureProjection && !throughmode) + WRITE(p, "layout (location = %d) in vec3 texcoord;\n", PspAttributeLocation::TEXCOORD); + else + WRITE(p, "layout (location = %d) in vec2 texcoord;\n", PspAttributeLocation::TEXCOORD); + } + if (hasColor) { + WRITE(p, "layout (location = %d) in vec4 color0;\n", PspAttributeLocation::COLOR0); + if (lmode && !useHWTransform) // only software transform supplies color1 as vertex data + WRITE(p, "layout (location = %d) in vec3 color1;\n", PspAttributeLocation::COLOR1); + } + + bool prescale = false; + + WRITE(p, "layout (location = 1) %sout vec4 v_color0;\n", shading); + if (lmode) { + WRITE(p, "layout (location = 2) %sout vec3 v_color1;\n", shading); + } + + if (doTexture) { + if (doTextureProjection) { + WRITE(p, "layout (location = 0) out vec3 v_texcoord;\n"); + } else { + WRITE(p, "layout (location = 0) out vec2 v_texcoord;\n"); + } + } + + if (enableFog) { + // See the fragment shader generator + WRITE(p, "layout (location = 3) out float v_fogdepth;\n"); + } + + // See comment above this function (GenerateVertexShader). + if (!isModeThrough && gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + // Apply the projection and viewport to get the Z buffer value, floor to integer, undo the viewport and projection. + WRITE(p, "\nvec4 depthRoundZVP(vec4 v) {\n"); + WRITE(p, " float z = v.z / v.w;\n"); + WRITE(p, " z = z * base.depthRange.x + base.depthRange.y;\n"); + WRITE(p, " z = floor(z);\n"); + WRITE(p, " z = (z - base.depthRange.z) * base.depthRange.w;\n"); + WRITE(p, " return vec4(v.x, v.y, z * v.w, v.w);\n"); + WRITE(p, "}\n\n"); + } + + WRITE(p, "void main() {\n"); + + if (!useHWTransform) { + // Simple pass-through of vertex data to fragment shader + if (doTexture) { + if (throughmode && doTextureProjection) { + WRITE(p, " v_texcoord = vec3(texcoord, 1.0);\n"); + } else { + WRITE(p, " v_texcoord = texcoord;\n"); + } + } + if (hasColor) { + WRITE(p, " v_color0 = color0;\n"); + if (lmode) + WRITE(p, " v_color1 = color1;\n"); + } else { + WRITE(p, " v_color0 = base.matambientalpha;\n"); + if (lmode) + WRITE(p, " v_color1 = vec3(0.0);\n"); + } + if (enableFog) { + WRITE(p, " v_fogdepth = position.w;\n"); + } + if (isModeThrough) { + WRITE(p, " gl_Position = base.proj_through_mtx * vec4(position.xyz, 1.0);\n"); + } else { + // The viewport is used in this case, so need to compensate for that. + if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + WRITE(p, " gl_Position = depthRoundZVP(base.proj_mtx * vec4(position.xyz, 1.0));\n"); + } else { + WRITE(p, " gl_Position = base.proj_mtx * vec4(position.xyz, 1.0);\n"); + } + } + } else { + // Step 1: World Transform / Skinning + if (!enableBones) { + // No skinning, just standard T&L. + WRITE(p, " vec3 worldpos = (base.world_mtx * vec4(position.xyz, 1.0)).xyz;\n"); + if (hasNormal) + WRITE(p, " mediump vec3 worldnormal = normalize((base.world_mtx * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); + else + WRITE(p, " mediump vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n"); + } else { + static const char *rescale[4] = { "", " * 1.9921875", " * 1.999969482421875", "" }; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; + const char *factor = rescale[boneWeightScale]; + + static const char * const boneWeightAttr[8] = { + "w1.x", "w1.y", "w1.z", "w1.w", + "w2.x", "w2.y", "w2.z", "w2.w", + }; + + WRITE(p, " mat4 skinMatrix = w1.x * bone.m[0];\n"); + if (numBoneWeights > 1) { + for (int i = 1; i < numBoneWeights; i++) { + WRITE(p, " skinMatrix += %s * bone.m[%i];\n", boneWeightAttr[i], i); + } + } + + WRITE(p, ";\n"); + + // Trying to simplify this results in bugs in LBP... + WRITE(p, " vec3 skinnedpos = (skinMatrix * vec4(position, 1.0)).xyz %s;\n", factor); + WRITE(p, " vec3 worldpos = (base.world_mtx * vec4(skinnedpos, 1.0)).xyz;\n"); + + if (hasNormal) { + WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(%snormal, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); + } else { + WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(0.0, 0.0, %s1.0, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); + } + WRITE(p, " mediump vec3 worldnormal = normalize((base.world_mtx * vec4(skinnednormal, 0.0)).xyz);\n"); + } + + WRITE(p, " vec4 viewPos = base.view_mtx * vec4(worldpos, 1.0);\n"); + + // Final view and projection transforms. + if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + WRITE(p, " gl_Position = depthRoundZVP(base.proj_mtx * viewPos);\n"); + } else { + WRITE(p, " gl_Position = base.proj_mtx * viewPos;\n"); + } + + // TODO: Declare variables for dots for shade mapping if needed. + + const char *ambientStr = ((matUpdate & 1) && hasColor) ? "color0" : "base.matambientalpha"; + const char *diffuseStr = ((matUpdate & 2) && hasColor) ? "color0.rgb" : "light.matdiffuse"; + const char *specularStr = ((matUpdate & 4) && hasColor) ? "color0.rgb" : "light.matspecular.rgb"; + + bool diffuseIsZero = true; + bool specularIsZero = true; + bool distanceNeeded = false; + + if (enableLighting) { + WRITE(p, " vec4 lightSum0 = light.globalAmbient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); + + for (int i = 0; i < 4; i++) { + GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); + GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); + if (doLight[i] != LIGHT_FULL) + continue; + diffuseIsZero = false; + if (comp != GE_LIGHTCOMP_ONLYDIFFUSE) + specularIsZero = false; + if (type != GE_LIGHTTYPE_DIRECTIONAL) + distanceNeeded = true; + } + + if (!specularIsZero) { + WRITE(p, " vec3 lightSum1 = vec3(0.0);\n"); + } + if (!diffuseIsZero) { + WRITE(p, " vec3 toLight;\n"); + WRITE(p, " vec3 diffuse;\n"); + } + if (distanceNeeded) { + WRITE(p, " float distance;\n"); + WRITE(p, " float lightScale;\n"); + } + } + + // Calculate lights if needed. If shade mapping is enabled, lights may need to be + // at least partially calculated. + for (int i = 0; i < 4; i++) { + if (doLight[i] != LIGHT_FULL) + continue; + + GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); + GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); + + if (type == GE_LIGHTTYPE_DIRECTIONAL) { + // We prenormalize light positions for directional lights. + WRITE(p, " toLight = light.pos[%i];\n", i); + } else { + WRITE(p, " toLight = light.pos[%i] - worldpos;\n", i); + WRITE(p, " distance = length(toLight);\n"); + WRITE(p, " toLight /= distance;\n"); + } + + bool doSpecular = comp != GE_LIGHTCOMP_ONLYDIFFUSE; + bool poweredDiffuse = comp == GE_LIGHTCOMP_BOTHWITHPOWDIFFUSE; + + WRITE(p, " mediump float dot%i = max(dot(toLight, worldnormal), 0.0);\n", i); + if (poweredDiffuse) { + // pow(0.0, 0.0) may be undefined, but the PSP seems to treat it as 1.0. + // Seen in Tales of the World: Radiant Mythology (#2424.) + WRITE(p, " if (dot%i == 0.0 && light.matspecular.a == 0.0) {\n", i); + WRITE(p, " dot%i = 1.0;\n", i); + WRITE(p, " } else {\n"); + WRITE(p, " dot%i = pow(dot%i, light.matspecular.a);\n", i, i); + WRITE(p, " }\n"); + } + + const char *timesLightScale = " * lightScale"; + + // Attenuation + switch (type) { + case GE_LIGHTTYPE_DIRECTIONAL: + timesLightScale = ""; + break; + case GE_LIGHTTYPE_POINT: + WRITE(p, " lightScale = clamp(1.0 / dot(light.att[%i], vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i); + break; + case GE_LIGHTTYPE_SPOT: + case GE_LIGHTTYPE_UNKNOWN: + WRITE(p, " float angle%i = dot(normalize(light.dir[%i]), toLight);\n", i, i); + WRITE(p, " if (angle[%i] >= light.angle[%i]) {\n", i, i); + WRITE(p, " lightScale = clamp(1.0 / dot(light.att[%i], vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle[%i], light.spotCoef[%i]);\n", i, i, i); + WRITE(p, " } else {\n"); + WRITE(p, " lightScale = 0.0;\n"); + WRITE(p, " }\n"); + break; + default: + // ILLEGAL + break; + } + + WRITE(p, " diffuse = (light.diffuse[%i] * %s) * dot%i;\n", i, diffuseStr, i); + if (doSpecular) { + WRITE(p, " dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); + WRITE(p, " if (dot%i > 0.0)\n", i); + WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot%i, light.matspecular.a) %s);\n", i, specularStr, i, timesLightScale); + } + WRITE(p, " lightSum0.rgb += (light.ambient[%i] * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); + } + + if (enableLighting) { + // Sum up ambient, emissive here. + if (lmode) { + WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); + // v_color1 only exists when lmode = 1. + if (specularIsZero) { + WRITE(p, " v_color1 = vec3(0.0);\n"); + } else { + WRITE(p, " v_color1 = clamp(lightSum1, 0.0, 1.0);\n"); + } + } else { + if (specularIsZero) { + WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); + } else { + WRITE(p, " v_color0 = clamp(clamp(lightSum0, 0.0, 1.0) + vec4(lightSum1, 0.0), 0.0, 1.0);\n"); + } + } + } else { + // Lighting doesn't affect color. + if (hasColor) { + WRITE(p, " v_color0 = color0;\n"); + } else { + WRITE(p, " v_color0 = base.matambientalpha;\n"); + } + if (lmode) { + WRITE(p, " v_color1 = vec3(0.0);\n"); + } + } + + // Step 3: UV generation + if (doTexture) { + switch (uvGenMode) { + case GE_TEXMAP_TEXTURE_COORDS: // Scale-offset. Easy. + case GE_TEXMAP_UNKNOWN: // Not sure what this is, but Riviera uses it. Treating as coords works. + if (prescale) { + if (hasTexcoord) { + WRITE(p, " v_texcoord = texcoord;\n"); + } else { + WRITE(p, " v_texcoord = vec2(0.0);\n"); + } + } else { + if (hasTexcoord) { + WRITE(p, " v_texcoord = texcoord * base.uvscaleoffset.xy + base.uvscaleoffset.zw;\n"); + } else { + WRITE(p, " v_texcoord = base.uvscaleoffset.zw;\n"); + } + } + break; + + case GE_TEXMAP_TEXTURE_MATRIX: // Projection mapping. + { + std::string temp_tc; + switch (uvProjMode) { + case GE_PROJMAP_POSITION: // Use model space XYZ as source + temp_tc = "vec4(position.xyz, 1.0)"; + break; + case GE_PROJMAP_UV: // Use unscaled UV as source + { + // prescale is false here. + if (hasTexcoord) { + static const char *rescaleuv[4] = { "", " * 1.9921875", " * 1.999969482421875", "" }; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; + const char *factor = rescaleuv[texFmtScale]; + temp_tc = StringFromFormat("vec4(texcoord.xy %s, 0.0, 1.0)", factor); + } else { + temp_tc = "vec4(0.0, 0.0, 0.0, 1.0)"; + } + } + break; + case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized transformed normal as source + if (hasNormal) + temp_tc = flipNormal ? "vec4(normalize(-normal), 1.0)" : "vec4(normalize(normal), 1.0)"; + else + temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; + break; + case GE_PROJMAP_NORMAL: // Use non-normalized transformed normal as source + if (hasNormal) + temp_tc = flipNormal ? "vec4(-normal, 1.0)" : "vec4(normal, 1.0)"; + else + temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; + break; + } + // Transform by texture matrix. XYZ as we are doing projection mapping. + WRITE(p, " v_texcoord = (base.tex_mtx * %s).xyz * vec3(base.uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); + } + break; + + case GE_TEXMAP_ENVIRONMENT_MAP: // Shade mapping - use dots from light sources. + WRITE(p, " v_texcoord = base.uvscaleoffset.xy * vec2(1.0 + dot(normalize(light.pos[%i]), worldnormal), 1.0 + dot(normalize(light.pos[%i]), worldnormal)) * 0.5;\n", ls0, ls1); + break; + + default: + // ILLEGAL + break; + } + } + + // Compute fogdepth + if (enableFog) + WRITE(p, " v_fogdepth = (viewPos.z + base.fogcoef_stencilreplace.x) * base.fogcoef_stencilreplace.y;\n"); + } + WRITE(p, "}\n"); + return true; +} diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.h b/GPU/Vulkan/VertexShaderGeneratorVulkan.h new file mode 100644 index 0000000000..4f3a97bb32 --- /dev/null +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.h @@ -0,0 +1,5 @@ +#pragma once + +#include "GPU/Common/ShaderId.h" + +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer, bool *usesLighting); \ No newline at end of file diff --git a/GPU/Vulkan/VulkanUtil.cpp b/GPU/Vulkan/VulkanUtil.cpp new file mode 100644 index 0000000000..a8a39ccdd9 --- /dev/null +++ b/GPU/Vulkan/VulkanUtil.cpp @@ -0,0 +1,45 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/Vulkan/VulkanUtil.h" + +VulkanFBO::VulkanFBO() : color_(nullptr), depthStencil_(nullptr) {} + +VulkanFBO::~VulkanFBO() { + delete color_; + delete depthStencil_; +} + +void VulkanFBO::Create(VulkanContext *vulkan, VkRenderPass rp_compatible, int width, int height, VkFormat color_Format) { + color_ = new VulkanTexture(vulkan); + VkImageCreateFlags flags = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + color_->CreateDirect(width, height, 1, VK_FORMAT_R8G8B8A8_UNORM, flags | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + depthStencil_->CreateDirect(width, height, 1, VK_FORMAT_D24_UNORM_S8_UINT, flags | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + + VkImageView views[2] = { color_->GetImageView(), depthStencil_->GetImageView() }; + + VkFramebufferCreateInfo fb = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; + fb.pAttachments = views; + fb.attachmentCount = 2; + fb.flags = 0; + fb.renderPass = rp_compatible; + fb.width = width; + fb.height = height; + fb.layers = 1; + + vkCreateFramebuffer(vulkan->GetDevice(), &fb, nullptr, &framebuffer_); +} diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h new file mode 100644 index 0000000000..61a4160359 --- /dev/null +++ b/GPU/Vulkan/VulkanUtil.h @@ -0,0 +1,48 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/Vulkan/VulkanLoader.h" +#include "Common/Vulkan/VulkanImage.h" + +// Vulkan doesn't really have the concept of an FBO that owns the images, +// but it does have the concept of a framebuffer as a set of attachments. +// VulkanFBO is an approximation of the FBO concept the other backends use +// to make things as similar as possible without being suboptimal. +// +class VulkanFBO { +public: + VulkanFBO(); + ~VulkanFBO(); + + // Depth-format is chosen automatically depending on hardware support. + // Color format will be 32-bit RGBA. + void Create(VulkanContext *vulkan, VkRenderPass rp_compatible, int width, int height, VkFormat colorFormat); + + VulkanTexture *GetColor() { return color_; } + VulkanTexture *GetDepthStencil() { return depthStencil_; } + + VkFramebuffer GetFramebuffer() { return framebuffer_; } + +private: + VulkanTexture *color_; + VulkanTexture *depthStencil_; + + // This point specifically to color and depth. + VkFramebuffer framebuffer_; +}; \ No newline at end of file diff --git a/Qt/Common.pro b/Qt/Common.pro index 3a9b41a5ec..6aa505554d 100644 --- a/Qt/Common.pro +++ b/Qt/Common.pro @@ -72,4 +72,5 @@ HEADERS += $$P/Common/ChunkFile.h \ $$P/Common/Crypto/*.h INCLUDEPATH += $$P/ext/native +INCLUDEPATH += $$P/ext diff --git a/Qt/Settings.pri b/Qt/Settings.pri index be855dfa00..83405099dc 100644 --- a/Qt/Settings.pri +++ b/Qt/Settings.pri @@ -1,5 +1,5 @@ VERSION = 1.2.2.0 -DEFINES += USING_QT_UI USE_FFMPEG +DEFINES += USING_QT_UI USE_FFMPEG NO_VULKAN exists( /usr/include/snappy-c.h ) { DEFINES += SHARED_SNAPPY diff --git a/UI/DevScreens.cpp b/UI/DevScreens.cpp index 38afafa231..e25c8ad982 100644 --- a/UI/DevScreens.cpp +++ b/UI/DevScreens.cpp @@ -466,6 +466,14 @@ void SystemInfoScreen::CreateViews() { eglExtensions->Add(new TextView(exts[i]))->SetFocusable(true); } } + } else if (g_Config.iGPUBackend == GPU_BACKEND_VULKAN) { + tabHolder->AddTab("Vulkan Features", oglExtensionsScroll); + + oglExtensions->Add(new ItemHeader("Vulkan Features")); + std::vector features = thin3d->GetFeatureList(); + for (auto &feature : features) { + oglExtensions->Add(new TextView(feature))->SetFocusable(true); + } } } diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index a3fc172948..dc20fe1c32 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -66,6 +66,10 @@ #include "UI/InstallZipScreen.h" #include "UI/ProfilerDraw.h" +#ifdef _WIN32 +#include "Windows/MainWindow.h" +#endif + EmuScreen::EmuScreen(const std::string &filename) : bootPending_(true), gamePath_(filename), invalid_(true), quit_(false), pauseTrigger_(false), saveStatePreviewShownTime_(0.0), saveStatePreview_(nullptr) { memset(axisState_, 0, sizeof(axisState_)); @@ -99,14 +103,36 @@ void EmuScreen::bootGame(const std::string &filename) { CoreParameter coreParam; coreParam.cpuCore = g_Config.bJit ? CPU_JIT : CPU_INTERPRETER; coreParam.gpuCore = GPU_GLES; - if (GetGPUBackend() == GPUBackend::DIRECT3D9) { + switch (GetGPUBackend()) { + case GPUBackend::OPENGL: + coreParam.gpuCore = GPU_GLES; + break; + case GPUBackend::DIRECT3D9: coreParam.gpuCore = GPU_DIRECTX9; + break; + case GPUBackend::DIRECT3D11: + coreParam.gpuCore = GPU_DIRECTX11; + break; + case GPUBackend::VULKAN: + coreParam.gpuCore = GPU_VULKAN; + if (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) { +#ifdef _WIN32 + if (IDYES == MessageBox(MainWindow::GetHWND(), L"The Vulkan backend is not yet compatible with buffered rendering. Switch to non-buffered (WARNING: This will cause glitches with the other backends unless you switch back)", L"Vulkan Experimental Support", MB_ICONINFORMATION | MB_YESNO)) { + g_Config.iRenderingMode = FB_NON_BUFFERED_MODE; + } else { + errorMessage_ = "Non-buffered rendering required for Vulkan"; + return; + } +#endif + } + break; } if (g_Config.bSoftwareRendering) { coreParam.gpuCore = GPU_SOFTWARE; } // Preserve the existing graphics context. coreParam.graphicsContext = PSP_CoreParameter().graphicsContext; + coreParam.thin3d = screenManager()->getThin3DContext(); coreParam.enableSound = g_Config.bEnableSound; coreParam.fileToStart = filename; coreParam.mountIso = ""; @@ -691,7 +717,7 @@ void EmuScreen::update(InputState &input) { UIScreen::update(input); - // Simply forcibily update to the current screen size every frame. Doesn't cost much. + // Simply forcibly update to the current screen size every frame. Doesn't cost much. // If bounds is set to be smaller than the actual pixel resolution of the display, respect that. // TODO: Should be able to use g_dpi_scale here instead. Might want to store the dpi scale in the UI context too. const Bounds &bounds = screenManager()->getUIContext()->GetBounds(); @@ -897,6 +923,7 @@ void EmuScreen::render() { while (coreState == CORE_RUNNING) { PSP_RunLoopFor(blockTicks); } + // Hopefully coreState is now CORE_NEXTFRAME if (coreState == CORE_NEXTFRAME) { // set back to running for the next frame @@ -956,6 +983,7 @@ void EmuScreen::render() { } // We have no use for backbuffer depth or stencil, so let tiled renderers discard them after tiling. + /* if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { GLenum attachments[2] = { GL_DEPTH, GL_STENCIL }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments); @@ -969,6 +997,7 @@ void EmuScreen::render() { } #endif } + */ } void EmuScreen::deviceLost() { diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index 9891ae6d63..afccb8c55f 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -135,10 +135,18 @@ void GameSettingsScreen::CreateViews() { tabHolder->AddTab(ms->T("Graphics"), graphicsSettingsScroll); graphicsSettings->Add(new ItemHeader(gr->T("Rendering Mode"))); -#if defined(_WIN32) - static const char *renderingBackend[] = { "OpenGL", "Direct3D9" }; + static const char *renderingBackend[] = { "OpenGL", "Direct3D 9", "Direct3D 11", "Vulkan (experimental)" }; PopupMultiChoice *renderingBackendChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iGPUBackend, gr->T("Backend"), renderingBackend, GPU_BACKEND_OPENGL, ARRAY_SIZE(renderingBackend), gr->GetName(), screenManager())); renderingBackendChoice->OnChoice.Handle(this, &GameSettingsScreen::OnRenderingBackend); +#if !defined(_WIN32) + renderingBackendChoice->HideChoice(1); // D3D9 + renderingBackendChoice->HideChoice(2); // D3D11 +#else + renderingBackendChoice->HideChoice(2); // D3D11 +#endif +#if !defined(ANDROID) && !defined(_WIN32) + // TODO: Add dynamic runtime check for Vulkan support on Android + renderingBackendChoice->HideChoice(3); #endif static const char *renderingMode[] = { "Non-Buffered Rendering", "Buffered Rendering", "Read Framebuffers To Memory (CPU)", "Read Framebuffers To Memory (GPU)"}; PopupMultiChoice *renderingModeChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iRenderingMode, gr->T("Mode"), renderingMode, 0, ARRAY_SIZE(renderingMode), gr->GetName(), screenManager())); diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index d481fb3429..90d5044df5 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -698,13 +698,20 @@ void NativeRender(GraphicsContext *graphicsContext) { // Apply the UIContext bounds as a 2D transformation matrix. Matrix4x4 ortho; - if (GetGPUBackend() == GPUBackend::DIRECT3D9) { + switch (GetGPUBackend()) { + case GPUBackend::VULKAN: + ortho.setOrthoD3D(0.0f, xres, 0, yres, -1.0f, 1.0f); + break; + case GPUBackend::DIRECT3D9: + case GPUBackend::DIRECT3D11: ortho.setOrthoD3D(0.0f, xres, yres, 0.0f, -1.0f, 1.0f); Matrix4x4 translation; translation.setTranslation(Vec3(-0.5f, -0.5f, 0.0f)); ortho = translation * ortho; - } else { + break; + case GPUBackend::OPENGL: ortho.setOrtho(0.0f, xres, yres, 0.0f, -1.0f, 1.0f); + break; } ui_draw2d.SetDrawMatrix(ortho); @@ -715,7 +722,9 @@ void NativeRender(GraphicsContext *graphicsContext) { screenManager->getUIContext()->Text()->OncePerFrame(); } - DrawDownloadsOverlay(*screenManager->getUIContext()); + // At this point, the vulkan context has been "ended" already, no more drawing can be done in this frame. + // TODO: Integrate the download overlay with the screen system + // DrawDownloadsOverlay(*screenManager->getUIContext()); if (g_TakeScreenshot) { TakeScreenshot(); diff --git a/UI/UI.vcxproj b/UI/UI.vcxproj index 5886b99bfb..596eba30a8 100644 --- a/UI/UI.vcxproj +++ b/UI/UI.vcxproj @@ -104,7 +104,6 @@ StaticLibrary false v140_xp - false Unicode @@ -212,6 +211,7 @@ true false MultiThreaded + true Windows @@ -227,4 +227,4 @@ - \ No newline at end of file + diff --git a/Windows/EmuThread.cpp b/Windows/EmuThread.cpp index 753b8cf5f7..abe0797908 100644 --- a/Windows/EmuThread.cpp +++ b/Windows/EmuThread.cpp @@ -128,6 +128,7 @@ unsigned int WINAPI TheThread(void *) I18NCategory *err = GetI18NCategory("Error"); Reporting::ReportMessage("Graphics init error: %s", error_string.c_str()); + const char *defaultErrorVulkan = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to OpenGL?\n\nError message:"; const char *defaultErrorOpenGL = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to DirectX 9?\n\nError message:"; const char *defaultErrorDirect3D9 = "Failed initializing graphics. Try upgrading your graphics drivers and directx 9 runtime.\n\nWould you like to try switching to OpenGL?\n\nError message:"; const char *genericError; @@ -137,6 +138,10 @@ unsigned int WINAPI TheThread(void *) nextBackend = GPU_BACKEND_OPENGL; genericError = err->T("GenericDirect3D9Error", defaultErrorDirect3D9); break; + case GPU_BACKEND_VULKAN: + nextBackend = GPU_BACKEND_OPENGL; + genericError = err->T("GenericVulkanError", defaultErrorDirect3D9); + break; case GPU_BACKEND_OPENGL: default: nextBackend = GPU_BACKEND_DIRECT3D9; diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp new file mode 100644 index 0000000000..88cb6173c5 --- /dev/null +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -0,0 +1,223 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + + +// Initializing a Vulkan context is quite a complex task! +// That's not really a strange thing though - you really do have control over everything, +// and everything needs to be specified. There are no nebulous defaults. + +// We create a swapchain, and two framebuffers that we can point to two of the images +// we got from the swap chain. These will be used as backbuffers. +// +// We also create a depth buffer. The swap chain will not allocate one for us so we need +// to manage the memory for it ourselves. +// The depth buffer will not really be used unless we do "non-buffered" rendering, which will happen +// directly to one of the backbuffers. +// +// Render pass usage +// +// In normal buffered rendering mode, we do not begin the "UI" render pass until after we have rendered +// a frame of PSP graphics. The render pass that we will use then will be the simple "uiPass" that does not +// bother attaching the depth buffer, and discards all input (no need to even bother clearing as we will +// draw over the whole backbuffer anyway). +// +// However, in non-buffered, we will have to use the depth buffer, and we must begin the rendering pass +// before we start rendering PSP graphics, and end it only after we have completed rendering the UI on top. +// We will also use clearing. +// +// So it all turns into a single rendering pass, which might be good for performance on some GPUs, but it +// will complicate things a little. +// +// In a first iteration, we will not distinguish between these two cases - we will always create a depth buffer +// and use the same render pass configuration (clear to black). However, we can later change this so we switch +// to a non-clearing render pass in buffered mode, which might be a tiny bit faster. + +#include +#include +#include + +#include "Common/Vulkan/VulkanLoader.h" +#include "Common/Vulkan/VulkanContext.h" + +#include "thin3d/thin3d.h" +#include "util/text/parsers.h" +#include "Windows/GPU/WindowsVulkanContext.h" + +extern const char *PPSSPP_GIT_VERSION; + +#ifdef _DEBUG +static const bool g_validate_ = true; +#else +static const bool g_validate_ = false; +#endif + +static VulkanContext *g_Vulkan; + +struct VulkanLogOptions { + bool breakOnWarning; + bool breakOnError; + bool msgBoxOnError; +}; +static VulkanLogOptions g_LogOptions; + +const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { + switch (type) { + case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "PhysicalDevice"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "CommandBuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "DeviceMemory"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "BufferView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "ImageView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "ShaderModule"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "PipelineLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "DescriptorSet"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "DescriptorSetLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "DescriptorPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; + case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "QueryPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "RenderPass"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "PipelineCache"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "SurfaceKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "SwapChainKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; + default: return ""; + } +} + +static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { + const VulkanLogOptions *options = (const VulkanLogOptions *)pUserData; + std::ostringstream message; + + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + message << "ERROR: "; + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + message << "WARNING: "; + } else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { + message << "PERFORMANCE WARNING: "; + } else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + message << "INFO: "; + } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + message << "DEBUG: "; + } + message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; + + // Getting some bizarre false positives for mapping image memory. + // https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 + if (msgCode == 6 && (!memcmp(pMsg, "Cannot map", 10) || !memcmp(pMsg, "Cannot sub", 10))) + return false; + +#ifdef _WIN32 + OutputDebugStringA(message.str().c_str()); + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + if (options->breakOnError) { + DebugBreak(); + } + if (options->msgBoxOnError) { + MessageBoxA(NULL, message.str().c_str(), "Alert", MB_OK); + } + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + if (options->breakOnWarning) { + DebugBreak(); + } + } +#else + std::cout << message; +#endif + + // false indicates that layer should not bail-out of an + // API call that had validation failures. This may mean that the + // app dies inside the driver due to invalid parameter(s). + // That's what would happen without validation layers, so we'll + // keep that behavior here. + return false; +} + +bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_message) { + *error_message = "N/A"; + + if (g_Vulkan) { + *error_message = "Already initialized"; + return false; + } + + init_glslang(); + + g_LogOptions.breakOnError = true; + g_LogOptions.breakOnWarning = true; + g_LogOptions.msgBoxOnError = false; + + Version gitVer(PPSSPP_GIT_VERSION); + g_Vulkan = new VulkanContext("PPSSPP", gitVer.ToInteger(), (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); + if (g_Vulkan->CreateDevice(0) != VK_SUCCESS) { + *error_message = g_Vulkan->InitError(); + return false; + } + if (g_validate_) { + int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); + } + g_Vulkan->InitSurfaceWin32(hInst, hWnd); + g_Vulkan->InitObjects(true); + + _CrtCheckMemory(); + + return true; +} + +void WindowsVulkanContext::Shutdown() { + g_Vulkan->WaitUntilQueueIdle(); + g_Vulkan->DestroyObjects(); + g_Vulkan->DestroyDevice(); + g_Vulkan->DestroyDebugMsgCallback(); + delete g_Vulkan; + g_Vulkan = nullptr; + + finalize_glslang(); +} + +Thin3DContext *WindowsVulkanContext::CreateThin3DContext() { + return T3DCreateVulkanContext(g_Vulkan); +} + +void WindowsVulkanContext::SwapBuffers() { +} + +void WindowsVulkanContext::Resize() { + /* + g_Vulkan->DestroyObjects(); + + g_Vulkan->WaitUntilQueueIdle(); + + g_Vulkan->InitObjects(g_Vulkan) + */ +} + +void WindowsVulkanContext::SwapInterval(int interval) { +} + +void *WindowsVulkanContext::GetAPIContext() { + return g_Vulkan; +} diff --git a/Windows/GPU/WindowsVulkanContext.h b/Windows/GPU/WindowsVulkanContext.h new file mode 100644 index 0000000000..0aad7d92c3 --- /dev/null +++ b/Windows/GPU/WindowsVulkanContext.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/GraphicsContext.h" +#include "Windows/GPU/WindowsGraphicsContext.h" +#include "thin3d/thin3d.h" + +class WindowsVulkanContext : public WindowsGraphicsContext { +public: + bool Init(HINSTANCE hInst, HWND window, std::string *error_message) override; + void Shutdown() override; + void SwapInterval(int interval) override; + void SwapBuffers() override; + void Resize() override; + + void *GetAPIContext(); + + Thin3DContext *CreateThin3DContext() override; +}; + diff --git a/Windows/MainWindowMenu.cpp b/Windows/MainWindowMenu.cpp index b2cd04a898..a78d3b784f 100644 --- a/Windows/MainWindowMenu.cpp +++ b/Windows/MainWindowMenu.cpp @@ -701,6 +701,12 @@ namespace MainWindow { PostMessage(MainWindow::GetHWND(), WM_CLOSE, 0, 0); break; + case ID_OPTIONS_VULKAN: + g_Config.iGPUBackend = GPU_BACKEND_VULKAN; + g_Config.bRestartRequired = true; + PostMessage(MainWindow::GetHWND(), WM_CLOSE, 0, 0); + break; + case ID_OPTIONS_NONBUFFEREDRENDERING: setRenderingMode(FB_NON_BUFFERED_MODE); break; case ID_OPTIONS_BUFFEREDRENDERING: setRenderingMode(FB_BUFFERED_MODE); break; case ID_OPTIONS_READFBOTOMEMORYCPU: setRenderingMode(FB_READFBOMEMORY_CPU); break; @@ -1144,14 +1150,31 @@ namespace MainWindow { CheckMenuItem(menu, savestateSlot[i], MF_BYCOMMAND | ((i == g_Config.iCurrentStateSlot) ? MF_CHECKED : MF_UNCHECKED)); } - if (g_Config.iGPUBackend == GPU_BACKEND_DIRECT3D9) { + switch (g_Config.iGPUBackend) { + case GPU_BACKEND_DIRECT3D9: EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_GRAYED); - CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_CHECKED); EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_ENABLED); - } else { - EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_GRAYED); - CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_CHECKED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_ENABLED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_CHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_UNCHECKED); + break; + case GPU_BACKEND_OPENGL: EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_GRAYED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_ENABLED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_CHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_UNCHECKED); + break; + case GPU_BACKEND_VULKAN: + EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_GRAYED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_CHECKED); + break; } UpdateDynamicMenuCheckmarks(menu); diff --git a/Windows/PPSSPP.sln b/Windows/PPSSPP.sln index 225c2a10bf..6454a20c83 100644 --- a/Windows/PPSSPP.sln +++ b/Windows/PPSSPP.sln @@ -38,6 +38,7 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "native", "..\ext\native\native.vcxproj", "{C4DF647E-80EA-4111-A0A8-218B1B711E18}" ProjectSection(ProjectDependencies) = postProject {F761046E-6C38-4428-A5F1-38391A37BB34} = {F761046E-6C38-4428-A5F1-38391A37BB34} + {EDFA2E87-8AC1-4853-95D4-D7594FF81947} = {EDFA2E87-8AC1-4853-95D4-D7594FF81947} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PPSSPPHeadless", "..\headless\Headless.vcxproj", "{EE9BD869-CAA3-447D-8328-294D90DE2C1F}" diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index c24357d995..4a61e38dd2 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -39,7 +39,6 @@ Application Unicode - false v140_xp @@ -125,7 +124,7 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h;Common/DbgNew.h MultiThreadedDebug StreamingSIMDExtensions2 @@ -135,7 +134,7 @@ Disabled - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;dxerr.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true Windows MachineX86 @@ -161,7 +160,7 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h;Common/DbgNew.h MultiThreadedDebug false @@ -175,11 +174,10 @@ Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb - Windows - MachineX64 true NotSet /ignore:4049 /ignore:4217 %(AdditionalOptions) + Windows ../Windows/git-version-gen.cmd @@ -201,14 +199,14 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h stdafx.h true false - dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) $(OutDir)$(TargetName)$(TargetExt) %(AdditionalLibraryDirectories) true @@ -246,13 +244,13 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h true false - dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) %(AdditionalLibraryDirectories) true Windows @@ -260,6 +258,7 @@ true MachineX64 /ignore:4049 /ignore:4217 %(AdditionalOptions) + true ../Windows/git-version-gen.cmd @@ -319,6 +318,7 @@ + $(IntDir)%(Filename)2.obj @@ -374,6 +374,7 @@ + @@ -422,6 +423,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} @@ -449,4 +453,4 @@ - \ No newline at end of file + diff --git a/Windows/PPSSPP.vcxproj.filters b/Windows/PPSSPP.vcxproj.filters index 4bf680c53f..a981fe75cb 100644 --- a/Windows/PPSSPP.vcxproj.filters +++ b/Windows/PPSSPP.vcxproj.filters @@ -152,6 +152,7 @@ Windows\System + @@ -278,6 +279,7 @@ Windows\System + diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index ad9107db8d..9121e630b4 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -43,6 +43,7 @@ #include "Windows/WindowsHost.h" #include "Windows/MainWindow.h" #include "Windows/GPU/WindowsGLContext.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "Windows/GPU/D3D9Context.h" #include "Windows/Debugger/DebuggerShared.h" @@ -68,7 +69,9 @@ static BOOL PostDialogMessage(Dialog *dialog, UINT message, WPARAM wParam = 0, L } WindowsHost::WindowsHost(HINSTANCE hInstance, HWND mainWindow, HWND displayWindow) - : gfx_(nullptr), hInstance_(hInstance), mainWindow_(mainWindow), displayWindow_(displayWindow) + : gfx_(nullptr), hInstance_(hInstance), + mainWindow_(mainWindow), + displayWindow_(displayWindow) { mouseDeltaX = 0; mouseDeltaY = 0; @@ -110,6 +113,9 @@ bool WindowsHost::InitGraphics(std::string *error_message, GraphicsContext **ctx case GPU_BACKEND_DIRECT3D9: graphicsContext = new D3D9Context(); break; + case GPU_BACKEND_VULKAN: + graphicsContext = new WindowsVulkanContext(); + break; default: return false; } diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 9f2f7040b3..01baf572a8 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -481,6 +481,7 @@ BEGIN BEGIN MENUITEM "Direct3D9" ID_OPTIONS_DIRECT3D9 MENUITEM "OpenGL" ID_OPTIONS_OPENGL + MENUITEM "Vulkan" ID_OPTIONS_VULKAN END POPUP "Rendering Mode" diff --git a/Windows/resource.h b/Windows/resource.h index 675dcd39bd..bdb6137da2 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -323,6 +323,7 @@ #define ID_EMULATION_ROTATION_H_R 40158 #define ID_EMULATION_ROTATION_V_R 40159 #define ID_OPTIONS_DISPLAY_LAYOUT 40160 +#define ID_OPTIONS_VULKAN 40161 // Dummy option to let the buffered rendering hotkey cycle through all the options. #define ID_OPTIONS_BUFFEREDRENDERINGDUMMY 40500 diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 365b03b47f..3e8e1ddc40 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -124,9 +124,29 @@ EGL_FILES := \ $(SRC)/Common/GL/GLInterface/EGLAndroid.cpp \ $(SRC)/Common/GL/GLInterface/GLInterface.cpp +VULKAN_FILES := \ + $(SRC)/Common/Vulkan/VulkanLoader.cpp \ + $(SRC)/Common/Vulkan/VulkanContext.cpp \ + $(SRC)/Common/Vulkan/VulkanImage.cpp \ + $(SRC)/Common/Vulkan/VulkanMemory.cpp \ + $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ + $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ + $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ + $(SRC)/GPU/Vulkan/GPU_Vulkan.cpp \ + $(SRC)/GPU/Vulkan/PipelineManagerVulkan.cpp \ + $(SRC)/GPU/Vulkan/ShaderManagerVulkan.cpp \ + $(SRC)/GPU/Vulkan/StateMappingVulkan.cpp \ + $(SRC)/GPU/Vulkan/TextureCacheVulkan.cpp \ + $(SRC)/GPU/Vulkan/TextureScalerVulkan.cpp \ + $(SRC)/GPU/Vulkan/DepalettizeShaderVulkan.cpp \ + $(SRC)/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp \ + $(SRC)/GPU/Vulkan/VulkanUtil.cpp +#endif + EXEC_AND_LIB_FILES := \ $(ARCH_FILES) \ $(EGL_FILES) \ + $(VULKAN_FILES) \ TestRunner.cpp \ $(SRC)/Core/MIPS/MIPS.cpp.arm \ $(SRC)/Core/MIPS/MIPSAnalyst.cpp \ @@ -492,6 +512,7 @@ endif $(call import-module,libzip) $(call import-module,native) +$(call import-module,glslang) ifeq ($(ANDROID_NDK_PROFILER),1) $(call import-module,android-ndk-profiler) diff --git a/android/jni/Locals.mk b/android/jni/Locals.mk index 327f81c1b4..bc8dea52b8 100644 --- a/android/jni/Locals.mk +++ b/android/jni/Locals.mk @@ -8,13 +8,14 @@ LOCAL_CPPFLAGS := -fno-exceptions -std=gnu++11 -fno-rtti -Wno-reorder -Wno-liter LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/../../Common \ $(LOCAL_PATH)/../.. \ + $(LOCAL_PATH)/../../ext \ $(LOCAL_PATH)/$(NATIVE)/base \ $(LOCAL_PATH)/$(NATIVE)/ext \ $(LOCAL_PATH)/$(NATIVE)/ext/libzip \ $(LOCAL_PATH)/$(NATIVE) \ $(LOCAL_PATH) -LOCAL_STATIC_LIBRARIES := native libzip +LOCAL_STATIC_LIBRARIES := native libzip glslang LOCAL_LDLIBS := -lz -landroid -lGLESv2 -lOpenSLES -lEGL -ldl -llog # ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index aa66e7923b..853fb3673c 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -4,6 +4,9 @@ // It calls a set of methods defined in NativeApp.h. These should be implemented // by your game or app. + +#include +#include #include #include #include @@ -30,8 +33,12 @@ #include "gfx/gl_common.h" #include "gfx_es2/gpu_features.h" +#include "thin3d/thin3d.h" +#include "Core/Config.cpp" #include "Common/GraphicsContext.h" #include "Common/GL/GLInterfaceBase.h" +#include "Common/Vulkan/VulkanLoader.h" +#include "Common/Vulkan/VulkanContext.h" #include "UI/GameInfoCache.h" #include "app-android.h" @@ -56,7 +63,12 @@ struct FrameCommand { std::string params; }; -class AndroidEGLGraphicsContext : public GraphicsContext { +class AndroidGraphicsContext : public GraphicsContext { +public: + virtual bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) = 0; +}; + +class AndroidEGLGraphicsContext : public AndroidGraphicsContext { public: AndroidEGLGraphicsContext() : wnd_(nullptr), gl(nullptr) {} bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion); @@ -137,6 +149,157 @@ public: }; +static const bool g_validate_ = true; +static VulkanContext *g_Vulkan; + +class AndroidVulkanContext : public AndroidGraphicsContext { +public: + AndroidVulkanContext() {} + bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) override; + void Shutdown() override; + void SwapInterval(int interval) override; + void SwapBuffers() override; + void Resize() override; + + void *GetAPIContext() { return g_Vulkan; } + + Thin3DContext *CreateThin3DContext() override { + return T3DCreateVulkanContext(g_Vulkan); + } +}; + +struct VulkanLogOptions { + bool breakOnWarning; + bool breakOnError; + bool msgBoxOnError; +}; +static VulkanLogOptions g_LogOptions; + +const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { + switch (type) { + case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "PhysicalDevice"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "CommandBuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "DeviceMemory"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "BufferView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "ImageView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "ShaderModule"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "PipelineLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "DescriptorSet"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "DescriptorSetLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "DescriptorPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; + case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "QueryPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "RenderPass"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "PipelineCache"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "SurfaceKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "SwapChainKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; + default: return "Unknown"; + } +} + +static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { + const VulkanLogOptions *options = (const VulkanLogOptions *)pUserData; + int loglevel = ANDROID_LOG_INFO; + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + loglevel = ANDROID_LOG_ERROR; + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } + + __android_log_print(loglevel, APP_NAME, "[%s] %s Code %d : %s", pLayerPrefix, ObjTypeToString(objType), msgCode, pMsg); + + // false indicates that layer should not bail-out of an + // API call that had validation failures. This may mean that the + // app dies inside the driver due to invalid parameter(s). + // That's what would happen without validation layers, so we'll + // keep that behavior here. + return false; +} + +bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) { + if (g_Vulkan) { + return false; + } + + init_glslang(); + + g_LogOptions.breakOnError = true; + g_LogOptions.breakOnWarning = true; + g_LogOptions.msgBoxOnError = false; + + ILOG("Creating vulkan context"); + Version gitVer(PPSSPP_GIT_VERSION); + g_Vulkan = new VulkanContext("PPSSPP", gitVer.ToInteger(), VULKAN_FLAG_PRESENT_MAILBOX | VULKAN_FLAG_PRESENT_FIFO_RELAXED); + if (!g_Vulkan->GetInstance()) { + ELOG("Failed to create vulkan context"); + return false; + } + + ILOG("Creating vulkan device"); + if (g_Vulkan->CreateDevice(0) != VK_SUCCESS) { + return false; + } + int width = desiredBackbufferSizeX; + int height = desiredBackbufferSizeY; + if (!width || !height) { + width = pixel_xres; + height = pixel_yres; + } + ILOG("InitSurfaceAndroid: width=%d height=%d", width, height); + g_Vulkan->InitSurfaceAndroid(wnd, width, height); + if (g_validate_) { + int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); + } + g_Vulkan->InitObjects(true); + + return true; +} + +void AndroidVulkanContext::Shutdown() { + g_Vulkan->WaitUntilQueueIdle(); + g_Vulkan->DestroyObjects(); + g_Vulkan->DestroyDebugMsgCallback(); + g_Vulkan->DestroyDevice(); + delete g_Vulkan; + g_Vulkan = nullptr; + + finalize_glslang(); +} + +void AndroidVulkanContext::SwapBuffers() { +} + +void AndroidVulkanContext::Resize() { + /* + g_Vulkan->DestroyObjects(); + + g_Vulkan->WaitUntilQueueIdle(); + + g_Vulkan->InitObjects(g_Vulkan) + */ +} + +void AndroidVulkanContext::SwapInterval(int interval) { +} + static recursive_mutex frameCommandLock; static std::queue frameCommands; @@ -827,8 +990,16 @@ extern "C" bool JNICALL Java_org_ppsspp_ppsspp_NativeActivity_runEGLRenderLoop(J ELOG("Error: Surface is null."); return false; } + + bool vulkan = g_Config.iGPUBackend == GPU_BACKEND_VULKAN; + + AndroidGraphicsContext *graphicsContext; + if (vulkan) { + graphicsContext = new AndroidVulkanContext(); + } else { + graphicsContext = new AndroidEGLGraphicsContext(); + } - AndroidEGLGraphicsContext *graphicsContext = new AndroidEGLGraphicsContext(); if (!graphicsContext->Init(wnd, desiredBackbufferSizeX, desiredBackbufferSizeY, backbuffer_format, androidVersion)) { ELOG("Failed to initialize graphics context."); delete graphicsContext; @@ -883,7 +1054,7 @@ extern "C" bool JNICALL Java_org_ppsspp_ppsspp_NativeActivity_runEGLRenderLoop(J renderer_inited = false; graphicsContext->Shutdown(); - + delete graphicsContext; renderLoopRunning = false; WLOG("Render loop function exited."); return true; diff --git a/ext/glslang.vcxproj b/ext/glslang.vcxproj index 53e1c2fee1..ad64018836 100644 --- a/ext/glslang.vcxproj +++ b/ext/glslang.vcxproj @@ -114,6 +114,8 @@ true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) glslang/glslang/OSDependent/Windows;glslang/glslang/MachineIndependent + MultiThreaded + false Windows @@ -132,6 +134,8 @@ true NDEBUG;_LIB;%(PreprocessorDefinitions) glslang/glslang/OSDependent/Windows;glslang/glslang/MachineIndependent + MultiThreaded + false Windows @@ -140,13 +144,11 @@ true - - - + @@ -191,6 +193,7 @@ + @@ -202,7 +205,6 @@ - @@ -217,9 +219,8 @@ - - \ No newline at end of file + diff --git a/ext/glslang.vcxproj.filters b/ext/glslang.vcxproj.filters index bd9df829ce..f1130d7b8d 100644 --- a/ext/glslang.vcxproj.filters +++ b/ext/glslang.vcxproj.filters @@ -1,8 +1,5 @@  - - - {300f8b24-cec5-41dc-bf7f-e60745f3e383} @@ -110,6 +107,9 @@ SPIRV + + glslang + @@ -202,9 +202,6 @@ glslang - - glslang - glslang @@ -212,13 +209,13 @@ glslang + + glslang + glslang - - glslang - \ No newline at end of file diff --git a/ext/libarmips.vcxproj b/ext/libarmips.vcxproj index f4f042f231..22bc0bba00 100644 --- a/ext/libarmips.vcxproj +++ b/ext/libarmips.vcxproj @@ -67,7 +67,6 @@ StaticLibrary false v140_xp - false Unicode @@ -221,6 +220,8 @@ WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) MultiThreaded armips + false + true Windows @@ -333,4 +334,4 @@ - \ No newline at end of file + diff --git a/ext/libkirk/libkirk.vcxproj b/ext/libkirk/libkirk.vcxproj index 661bf7f609..cdc3e4f739 100644 --- a/ext/libkirk/libkirk.vcxproj +++ b/ext/libkirk/libkirk.vcxproj @@ -46,7 +46,6 @@ StaticLibrary false v140_xp - false Unicode @@ -129,6 +128,7 @@ true false MultiThreaded + true true @@ -156,4 +156,4 @@ - \ No newline at end of file + diff --git a/ext/native/Android.mk b/ext/native/Android.mk index 28542deac3..1f3eea6530 100644 --- a/ext/native/Android.mk +++ b/ext/native/Android.mk @@ -81,6 +81,7 @@ LOCAL_SRC_FILES :=\ image/png_load.cpp \ thin3d/thin3d.cpp \ thin3d/thin3d_gl.cpp \ + thin3d/thin3d_vulkan.cpp \ ui/view.cpp \ ui/viewgroup.cpp \ ui/ui.cpp \ @@ -94,7 +95,7 @@ LOCAL_SRC_FILES :=\ LOCAL_CFLAGS := -O3 -DUSING_GLES2 -fsigned-char -fno-strict-aliasing -Wall -Wno-multichar -D__STDC_CONSTANT_MACROS LOCAL_CPPFLAGS := -fno-exceptions -std=gnu++11 -fno-rtti -Wno-reorder -LOCAL_C_INCLUDES := $(LOCAL_PATH)/ext $(LOCAL_PATH)/ext/libzip +LOCAL_C_INCLUDES := $(LOCAL_PATH)/ext $(LOCAL_PATH)/ext/libzip .. #Portable native and separate code on android in future is easy you needs add files #by ($(target_arch_ABI),arquitecture (armeabi-v7a , armeabi , x86 , MIPS) diff --git a/ext/native/math/dataconv.h b/ext/native/math/dataconv.h index 046bb63f35..46ea8b84be 100644 --- a/ext/native/math/dataconv.h +++ b/ext/native/math/dataconv.h @@ -29,6 +29,13 @@ inline void Uint8x3ToInt4(int i[4], uint32_t u) { i[3] = 0; } +inline void Uint8x3ToInt4_Alpha(int i[4], uint32_t u, uint8_t alpha) { + i[0] = ((u >> 0) & 0xFF); + i[1] = ((u >> 8) & 0xFF); + i[2] = ((u >> 16) & 0xFF); + i[3] = alpha; +} + inline void Uint8x3ToFloat4_Alpha(float f[4], uint32_t u, float alpha) { f[0] = ((u >> 0) & 0xFF) * (1.0f / 255.0f); f[1] = ((u >> 8) & 0xFF) * (1.0f / 255.0f); @@ -56,6 +63,10 @@ inline void CopyFloat2(float dest[2], const float src[2]) { memcpy(dest, src, sizeof(float) * 2); } +inline void CopyFloat3(float dest[3], const float src[3]) { + memcpy(dest, src, sizeof(float) * 3); +} + inline void CopyFloat1To4(float dest[4], const float src) { dest[0] = src; dest[1] = 0.0f; @@ -85,4 +96,4 @@ inline void CopyMatrix4x4(float dest[16], const float src[16]) { inline void ExpandFloat24x3ToFloat4(float dest[4], uint32_t src[3]) { uint32_t temp[4] = { src[0] << 8, src[1] << 8, src[2] << 8, 0 }; memcpy(dest, temp, sizeof(float) * 4); -} \ No newline at end of file +} diff --git a/ext/native/math/lin/matrix4x4.cpp b/ext/native/math/lin/matrix4x4.cpp index d90dc957ab..703ed366c3 100644 --- a/ext/native/math/lin/matrix4x4.cpp +++ b/ext/native/math/lin/matrix4x4.cpp @@ -203,23 +203,36 @@ void Matrix4x4::setProjectionD3D(float near_plane, float far_plane, float fov_ho } void Matrix4x4::setOrtho(float left, float right, float bottom, float top, float near, float far) { - setIdentity(); + empty(); xx = 2.0f / (right - left); yy = 2.0f / (top - bottom); zz = 2.0f / (far - near); wx = -(right + left) / (right - left); wy = -(top + bottom) / (top - bottom); wz = -(far + near) / (far - near); + ww = 1.0f; } void Matrix4x4::setOrthoD3D(float left, float right, float bottom, float top, float near, float far) { - setIdentity(); + empty(); xx = 2.0f / (right - left); yy = 2.0f / (top - bottom); zz = 1.0f / (far - near); wx = -(right + left) / (right - left); wy = -(top + bottom) / (top - bottom); wz = -near / (far - near); + ww = 1.0f; +} + +void Matrix4x4::setOrthoVulkan(float left, float right, float top, float bottom, float near, float far) { + empty(); + xx = 2.0f / (right - left); + yy = 2.0f / (bottom - top); + zz = 1.0f / (far - near); + wx = -(right + left) / (right - left); + wy = -(top + bottom) / (bottom - top); + wz = -near / (far - near); + ww = 1.0f; } void Matrix4x4::setProjectionInf(const float near_plane, const float fov_horiz, const float aspect) { diff --git a/ext/native/math/lin/matrix4x4.h b/ext/native/math/lin/matrix4x4.h index d56906d1f2..3b52e4ecd7 100644 --- a/ext/native/math/lin/matrix4x4.h +++ b/ext/native/math/lin/matrix4x4.h @@ -120,6 +120,7 @@ public: void setProjectionInf(float near_plane, float fov_horiz, float aspect = 0.75f); void setOrtho(float left, float right, float bottom, float top, float near, float far); void setOrthoD3D(float left, float right, float bottom, float top, float near, float far); + void setOrthoVulkan(float left, float right, float top, float bottom, float near, float far); void setShadow(float Lx, float Ly, float Lz, float Lw) { float Pa=0; float Pb=1; diff --git a/ext/native/native.vcxproj b/ext/native/native.vcxproj index 93d7860e03..f750063f7c 100644 --- a/ext/native/native.vcxproj +++ b/ext/native/native.vcxproj @@ -46,7 +46,6 @@ StaticLibrary false - false Unicode v140_xp @@ -80,7 +79,7 @@ Level3 _CRTDBG_MAP_ALLOC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); ProgramDatabase true false @@ -102,7 +101,7 @@ Level3 _CRTDBG_MAP_ALLOC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); true false false @@ -128,7 +127,7 @@ true true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); StreamingSIMDExtensions2 Fast true @@ -154,12 +153,14 @@ true true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); NotSet Fast true false MultiThreaded + false + true Windows @@ -344,7 +345,6 @@ - @@ -727,6 +727,7 @@ + diff --git a/ext/native/native.vcxproj.filters b/ext/native/native.vcxproj.filters index acbf041728..269ac5835d 100644 --- a/ext/native/native.vcxproj.filters +++ b/ext/native/native.vcxproj.filters @@ -502,9 +502,6 @@ ext\libpng17 - - ext\libpng17 - ext\libpng17 @@ -745,6 +742,9 @@ file + + thin3d + diff --git a/ext/native/thin3d/thin3d.cpp b/ext/native/thin3d/thin3d.cpp index 78dd46a9d8..d72e72f9a9 100644 --- a/ext/native/thin3d/thin3d.cpp +++ b/ext/native/thin3d/thin3d.cpp @@ -7,6 +7,10 @@ #include "file/vfs.h" #include "ext/jpge/jpgd.h" +// ================================== PIXEL/FRAGMENT SHADERS + +// The Vulkan ones can be re-used with modern GL later if desired, as they're just GLSL. + static const char * const glsl_fsTexCol = "#ifdef GL_ES\n" "precision lowp float;\n" @@ -23,6 +27,16 @@ static const char * const hlslFsTexCol = " return input.color * tex2D(Sampler0, input.uv);\n" "}\n"; +static const char * const vulkan_fsTexCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout(location = 0) in vec4 oColor0;\n" +"layout(location = 1) in vec2 oTexCoord0;\n" +"layout(location = 0) out vec4 fragColor0\n;" +"layout(set = 0, binding = 1) uniform sampler2D Sampler0;\n" +"void main() { fragColor0 = texture(Sampler0, oTexCoord0) * oColor0; }\n"; + static const char * const glsl_fsCol = "#ifdef GL_ES\n" "precision lowp float;\n" @@ -36,6 +50,18 @@ static const char * const hlslFsCol = " return input.color;\n" "}\n"; +static const char * const vulkan_fsCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout(location = 0) in vec4 oColor0;\n" +"layout(location = 0) out vec4 fragColor0\n;" +"void main() { fragColor0 = oColor0; }\n"; + + + +// ================================== VERTEX SHADERS + static const char * const glsl_vsCol = "attribute vec3 Position;\n" "attribute vec4 Color0;\n" @@ -57,6 +83,22 @@ static const char * const hlslVsCol = " return output;\n" "}\n"; +static const char * const vulkan_vsCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout (std140, set = 0, binding = 0) uniform bufferVals {\n" +" mat4 WorldViewProj;\n" +"} myBufferVals;\n" +"layout (location = 0) in vec4 pos;\n" +"layout (location = 1) in vec4 inColor;\n" +"layout (location = 0) out vec4 outColor;\n" +"void main() {\n" +" outColor = inColor;\n" +" gl_Position = myBufferVals.WorldViewProj * pos;\n" +"}\n"; + + static const char * const glsl_vsTexCol = "attribute vec3 Position;\n" "attribute vec4 Color0;\n" @@ -82,6 +124,25 @@ static const char * const hlslVsTexCol = " return output;\n" "}\n"; +static const char * const vulkan_vsTexCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout (std140, set = 0, binding = 0) uniform bufferVals {\n" +" mat4 WorldViewProj;\n" +"} myBufferVals;\n" +"layout (location = 0) in vec4 pos;\n" +"layout (location = 1) in vec4 inColor;\n" +"layout (location = 2) in vec2 inTexCoord;\n" +"layout (location = 0) out vec4 outColor;\n" +"layout (location = 1) out vec2 outTexCoord;\n" +"void main() {\n" +" outColor = inColor;\n" +" outTexCoord = inTexCoord;\n" +" gl_Position = myBufferVals.WorldViewProj * pos;\n" +"}\n"; + + void Thin3DContext::CreatePresets() { // Build prebuilt objects T3DBlendStateDesc off = { false }; @@ -100,11 +161,11 @@ void Thin3DContext::CreatePresets() { sampsPresets_[SAMPS_NEAREST] = CreateSamplerState(nearest); sampsPresets_[SAMPS_LINEAR] = CreateSamplerState(linear); - vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol); - vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol); + vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol, vulkan_vsTexCol); + vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol, vulkan_vsCol); - fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol); - fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol); + fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol, vulkan_fsTexCol); + fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol, vulkan_fsCol); ssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]); ssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]); diff --git a/ext/native/thin3d/thin3d.h b/ext/native/thin3d/thin3d.h index 1593778d56..131ad0a60e 100644 --- a/ext/native/thin3d/thin3d.h +++ b/ext/native/thin3d/thin3d.h @@ -334,8 +334,8 @@ public: Thin3DShaderSet *GetShaderSetPreset(T3DShaderSetPreset preset) { return ssPresets_[preset]; } // The implementation makes the choice of which shader code to use. - virtual Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) = 0; - virtual Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) = 0; + virtual Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) = 0; + virtual Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) = 0; // Bound state objects. Too cumbersome to add them all as parameters to Draw. virtual void SetBlendState(Thin3DBlendState *state) = 0; @@ -359,8 +359,15 @@ public: virtual void Draw(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) = 0; virtual void DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) = 0; virtual void DrawUP(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, const void *vdata, int vertexCount) = 0; + + // Render pass management. Default implementations here. + virtual void Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal) { + Clear(0xF, colorval, depthVal, stencilVal); + } + virtual void End() {} + virtual void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) = 0; - + // Necessary to correctly flip scissor rectangles etc for OpenGL. void SetTargetSize(int w, int h) { targetWidth_ = w; @@ -393,3 +400,7 @@ struct IDirect3DDevice9Ex; struct IDirect3D9Ex; Thin3DContext *T3DCreateDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx); #endif + +class VulkanContext; + +Thin3DContext *T3DCreateVulkanContext(VulkanContext *context); diff --git a/ext/native/thin3d/thin3d_d3d9.cpp b/ext/native/thin3d/thin3d_d3d9.cpp index d5e1e3edf8..19d373c56f 100644 --- a/ext/native/thin3d/thin3d_d3d9.cpp +++ b/ext/native/thin3d/thin3d_d3d9.cpp @@ -434,8 +434,8 @@ public: Thin3DTexture *CreateTexture() override; Thin3DTexture *CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override; - Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) override; - Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) override; + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; // Bound state objects. Too cumbersome to add them all as parameters to Draw. void SetBlendState(Thin3DBlendState *state) { @@ -502,7 +502,7 @@ Thin3DDX9Context::Thin3DDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int ada Thin3DDX9Context::~Thin3DDX9Context() { } -Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DDX9Shader *shader = new Thin3DDX9Shader(false); if (shader->Compile(device_, hlsl_source, "vs_2_0")) { return shader; @@ -512,7 +512,7 @@ Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, cons } } -Thin3DShader *Thin3DDX9Context::CreateFragmentShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DDX9Context::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DDX9Shader *shader = new Thin3DDX9Shader(true); if (shader->Compile(device_, hlsl_source, "ps_2_0")) { return shader; diff --git a/ext/native/thin3d/thin3d_gl.cpp b/ext/native/thin3d/thin3d_gl.cpp index 70453fc322..c04855a2db 100644 --- a/ext/native/thin3d/thin3d_gl.cpp +++ b/ext/native/thin3d/thin3d_gl.cpp @@ -386,8 +386,8 @@ public: } // The implementation makes the choice of which shader code to use. - Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) override; - Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) override; + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; void SetScissorEnabled(bool enable) override { if (enable) { @@ -737,7 +737,7 @@ void Thin3DGLContext::SetTextures(int start, int count, Thin3DTexture **textures } -Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DGLShader *shader = new Thin3DGLShader(false); if (shader->Compile(glsl_source)) { return shader; @@ -747,7 +747,7 @@ Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const } } -Thin3DShader *Thin3DGLContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DGLContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DGLShader *shader = new Thin3DGLShader(true); if (shader->Compile(glsl_source)) { return shader; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp new file mode 100644 index 0000000000..95d863c63c --- /dev/null +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -0,0 +1,1220 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include +#include +#include +#include + +#include "Common/Vulkan/SPIRVDisasm.h" + +#include "base/logging.h" +#include "base/display.h" +#include "base/stringutil.h" +#include "image/zim_load.h" +#include "math/lin/matrix4x4.h" +#include "math/dataconv.h" +#include "thin3d/thin3d.h" + +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanImage.h" +#include "Common/Vulkan/VulkanMemory.h" + +// We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. +// binding 0 - uniform data +// binding 1 - sampler +// +// Vertex data lives in a separate namespace (location = 0, 1, etc) + +#include "Common/Vulkan/VulkanLoader.h" + +// This can actually be replaced with a cast as the values are in the right order. +static const VkCompareOp compToVK[] = { + VK_COMPARE_OP_NEVER, + VK_COMPARE_OP_LESS, + VK_COMPARE_OP_EQUAL, + VK_COMPARE_OP_LESS_OR_EQUAL, + VK_COMPARE_OP_GREATER, + VK_COMPARE_OP_NOT_EQUAL, + VK_COMPARE_OP_GREATER_OR_EQUAL, + VK_COMPARE_OP_ALWAYS +}; + +// So can this. +static const VkBlendOp blendEqToGL[] = { + VK_BLEND_OP_ADD, + VK_BLEND_OP_SUBTRACT, + VK_BLEND_OP_REVERSE_SUBTRACT, +}; + +static const VkBlendFactor blendFactorToVk[] = { + VK_BLEND_FACTOR_ZERO, + VK_BLEND_FACTOR_ONE, + VK_BLEND_FACTOR_SRC_COLOR, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_FACTOR_DST_COLOR, + VK_BLEND_FACTOR_DST_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, + VK_BLEND_FACTOR_CONSTANT_COLOR, +}; + +static const VkLogicOp logicOpToVK[] = { + VK_LOGIC_OP_CLEAR, + VK_LOGIC_OP_SET, + VK_LOGIC_OP_COPY, + VK_LOGIC_OP_COPY_INVERTED, + VK_LOGIC_OP_NO_OP, + VK_LOGIC_OP_INVERT, + VK_LOGIC_OP_AND, + VK_LOGIC_OP_NAND, + VK_LOGIC_OP_OR, + VK_LOGIC_OP_NOR, + VK_LOGIC_OP_XOR, + VK_LOGIC_OP_EQUIVALENT, + VK_LOGIC_OP_AND_REVERSE, + VK_LOGIC_OP_AND_INVERTED, + VK_LOGIC_OP_OR_REVERSE, + VK_LOGIC_OP_OR_INVERTED, +}; + +static const VkPrimitiveTopology primToVK[] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, +}; + +static inline void Uint8x4ToFloat4(uint32_t u, float f[4]) { + f[0] = ((u >> 0) & 0xFF) * (1.0f / 255.0f); + f[1] = ((u >> 8) & 0xFF) * (1.0f / 255.0f); + f[2] = ((u >> 16) & 0xFF) * (1.0f / 255.0f); + f[3] = ((u >> 24) & 0xFF) * (1.0f / 255.0f); +} + + +class Thin3DVKBlendState : public Thin3DBlendState { +public: + bool blendEnabled; + VkBlendOp eqCol, eqAlpha; + VkBlendFactor srcCol, srcAlpha, dstColor, dstAlpha; + bool logicEnabled; + VkLogicOp logicOp; + + void ToVulkan(VkPipelineColorBlendStateCreateInfo *info, VkPipelineColorBlendAttachmentState *attachments) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + info->attachmentCount = 1; + info->logicOp = logicOp; + info->logicOpEnable = logicEnabled; + attachments[0].blendEnable = blendEnabled; + attachments[0].colorBlendOp = eqCol; + attachments[0].alphaBlendOp = eqAlpha; + attachments[0].colorWriteMask = 0xF; + attachments[0].dstAlphaBlendFactor = dstAlpha; + attachments[0].dstColorBlendFactor = dstColor; + attachments[0].srcAlphaBlendFactor = srcAlpha; + attachments[0].srcColorBlendFactor = srcCol; + info->pAttachments = attachments; + } +}; + +class Thin3DVKDepthStencilState : public Thin3DDepthStencilState { +public: + bool depthTestEnabled; + bool depthWriteEnabled; + VkCompareOp depthComp; + + void ToVulkan(VkPipelineDepthStencilStateCreateInfo *info) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + info->depthCompareOp = depthComp; + info->depthTestEnable = depthTestEnabled; + info->depthWriteEnable = depthWriteEnabled; + info->stencilTestEnable = false; + info->depthBoundsTestEnable = false; + } +}; + +// Very simplistic buffer that will simply copy its contents into our "pushbuffer" when it's time to draw, +// to avoid synchronization issues. +class Thin3DVKBuffer : public Thin3DBuffer { +public: + Thin3DVKBuffer(size_t size, uint32_t flags) : dataSize_(size) { + data_ = new uint8_t[size]; + } + ~Thin3DVKBuffer() override { + delete[] data_; + } + + void SetData(const uint8_t *data, size_t size) override { + delete[] data_; + dataSize_ = size; + data_ = new uint8_t[size]; + if (data) { + memcpy(data_, data, size); + } + } + + void SubData(const uint8_t *data, size_t offset, size_t size) override { + memcpy(data_, data_ + offset, size); + } + + size_t GetSize() const { return dataSize_; } + const uint8_t *GetData() const { return data_; } + +private: + uint8_t *data_; + size_t dataSize_; +}; + +// Not registering this as a resource holder, instead ShaderSet is registered. It will +// invoke Compile again to recreate the shader then link them together. +class Thin3DVKShader : public Thin3DShader { +public: + Thin3DVKShader(bool isFragmentShader) : module_(VK_NULL_HANDLE), ok_(false) { + stage_ = isFragmentShader ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; + } + bool Compile(VulkanContext *vulkan, const char *source); + const std::string &GetSource() const { return source_; } + ~Thin3DVKShader() { + } + VkShaderModule Get() const { return module_; } + +private: + VkShaderModule module_; + VkShaderStageFlagBits stage_; + bool ok_; + std::string source_; // So we can recompile in case of context loss. +}; + +bool Thin3DVKShader::Compile(VulkanContext *vulkan, const char *source) { + this->source_ = source; + std::vector spirv; + if (!GLSLtoSPV(stage_, source, spirv)) { + return false; + } + + // Just for kicks, sanity check the SPIR-V. The disasm isn't perfect + // but gives you some idea of what's going on. +#if 0 + std::string disasm; + if (DisassembleSPIRV(spirv, &disasm)) { + OutputDebugStringA(disasm.c_str()); + } +#endif + + if (vulkan->CreateShaderModule(spirv, &module_)) { + ok_ = true; + } else { + ok_ = false; + } + + return ok_; +} + + +inline VkFormat ConvertVertexDataTypeToVk(T3DVertexDataType type) { + switch (type) { + case FLOATx2: return VK_FORMAT_R32G32_SFLOAT; + case FLOATx3: return VK_FORMAT_R32G32B32_SFLOAT; + case FLOATx4: return VK_FORMAT_R32G32B32A32_SFLOAT; + case UNORM8x4: return VK_FORMAT_R8G8B8A8_UNORM; + default: return VK_FORMAT_UNDEFINED; + } +} + +class Thin3DVKVertexFormat : public Thin3DVertexFormat { +public: + void ToVulkan(VkPipelineVertexInputStateCreateInfo *info, VkVertexInputAttributeDescription *attrDescs, VkVertexInputBindingDescription *bindDescs) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + int offset = 0; + for (uint32_t i = 0; i < components_.size(); i++) { + attrDescs[i].binding = 0; + attrDescs[i].format = ConvertVertexDataTypeToVk(components_[i].type); + attrDescs[i].location = (int)components_[i].semantic; + attrDescs[i].offset = components_[i].offset; + } + bindDescs[0].binding = 0; + bindDescs[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + bindDescs[0].stride = stride_; + + info->vertexAttributeDescriptionCount = (uint32_t)components_.size(); + info->pVertexAttributeDescriptions = attrDescs; + info->vertexBindingDescriptionCount = 1; + info->pVertexBindingDescriptions = bindDescs; + info->flags = 0; + } + + bool RequiresBuffer() { + return false; + } + + std::vector components_; + int stride_; +}; + +class Thin3DVKShaderSet : public Thin3DShaderSet { +public: + Thin3DVKShaderSet() { + // HACK! Hardcoded + uboSize_ = 16 * sizeof(float); // WorldViewProj + ubo_ = new uint8_t[uboSize_]; + } + ~Thin3DVKShaderSet() { + vshader->Release(); + fshader->Release(); + delete[] ubo_; + } + bool Link(); + + // Returns the binding offset, and the VkBuffer to bind. + size_t PushUBO(VulkanPushBuffer *buf, VulkanContext *vulkan, VkBuffer *vkbuf) { + return buf->PushAligned(ubo_, uboSize_, vulkan->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment, vkbuf); + } + + int GetUniformLoc(const char *name); + + void SetVector(const char *name, float *value, int n) override; + void SetMatrix4x4(const char *name, const float value[16]) override; + + int GetUBOSize() const { + return uboSize_; + } + + Thin3DVKShader *vshader; + Thin3DVKShader *fshader; + +private: + uint8_t *ubo_; + int uboSize_; +}; + +struct PipelineKey { + Thin3DVKDepthStencilState *depthStencil; + Thin3DVKBlendState *blend; + Thin3DVKShaderSet *shaderSet; + VkPrimitiveTopology topology; + T3DCullMode cullMode; + + // etc etc + + bool operator < (const PipelineKey &other) const { + if (depthStencil < other.depthStencil) return true; else if (depthStencil > other.depthStencil) return false; + if (blend < other.blend) return true; else if (blend > other.blend) return false; + if (shaderSet < other.shaderSet) return true; else if (shaderSet > other.shaderSet) return false; + if (topology < other.topology) return true; else if (topology > other.topology) return false; + if (cullMode < other.cullMode) return true; else if (cullMode > other.cullMode) return false; + // etc etc + return false; + } +}; + + + +class Thin3DVKTexture; +class Thin3DVKSamplerState; + +struct DescriptorSetKey { + Thin3DVKTexture *texture_; + Thin3DVKSamplerState *sampler_; + VkBuffer buffer_; + + bool operator < (const DescriptorSetKey &other) const { + if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; + if (buffer_ < other.buffer_) return true; else if (buffer_ > other.buffer_) return false; + return false; + } +}; + +class Thin3DVKContext : public Thin3DContext { +public: + Thin3DVKContext(VulkanContext *vulkan); + virtual ~Thin3DVKContext(); + + Thin3DDepthStencilState *CreateDepthStencilState(bool depthTestEnabled, bool depthWriteEnabled, T3DComparison depthCompare) override; + Thin3DBlendState *CreateBlendState(const T3DBlendStateDesc &desc) override; + Thin3DBuffer *CreateBuffer(size_t size, uint32_t usageFlags) override; + Thin3DShaderSet *CreateShaderSet(Thin3DShader *vshader, Thin3DShader *fshader) override; + Thin3DVertexFormat *CreateVertexFormat(const std::vector &components, int stride, Thin3DShader *vshader) override; + Thin3DSamplerState *CreateSamplerState(const T3DSamplerStateDesc &desc) override; + Thin3DTexture *CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override; + Thin3DTexture *CreateTexture() override; + + // Bound state objects + void SetBlendState(Thin3DBlendState *state) override { + Thin3DVKBlendState *s = static_cast(state); + curBlendState_ = s; + } + + // Bound state objects + void SetDepthStencilState(Thin3DDepthStencilState *state) override { + Thin3DVKDepthStencilState *s = static_cast(state); + curDepthStencilState_ = s; + } + + // The implementation makes the choice of which shader code to use. + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + + void SetScissorEnabled(bool enable) override { + scissorEnabled_ = enable; + scissorDirty_ = true; + } + + void SetScissorRect(int left, int top, int width, int height) override; + + void SetViewports(int count, T3DViewport *viewports) override; + + void SetTextures(int start, int count, Thin3DTexture **textures) override; + + void SetSamplerStates(int start, int count, Thin3DSamplerState **state) override; + + void SetRenderState(T3DRenderState rs, uint32_t value) override; + + // TODO: Add more sophisticated draws. + void Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) override; + void DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) override; + void DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, const void *vdata, int vertexCount) override; + + void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) override; + + virtual void Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal); + virtual void End(); + + std::string GetInfoString(T3DInfo info) const override { + // TODO: Make these actually query the right information + switch (info) { + case APINAME: return "Vulkan"; + case VENDORSTRING: return vulkan_->GetPhysicalDeviceProperties().deviceName; + case VENDOR: return StringFromFormat("%08x", vulkan_->GetPhysicalDeviceProperties().vendorID); + case RENDERER: return StringFromFormat("%08x", vulkan_->GetPhysicalDeviceProperties().driverVersion); + case SHADELANGVERSION: return "N/A";; + case APIVERSION: + { + uint32_t ver = vulkan_->GetPhysicalDeviceProperties().apiVersion; + return StringFromFormat("%d.%d.%d", ver >> 22, (ver >> 12) & 0x3ff, ver & 0xfff); + } + default: return "?"; + } + } + + VkPipeline GetOrCreatePipeline(); + VkDescriptorSet GetOrCreateDescriptorSet(VkBuffer buffer); + + std::vector GetFeatureList() override; + +private: + void ApplyDynamicState(); + void DirtyDynamicState(); + + VulkanContext *vulkan_; + + // These are used to compose the pipeline cache key. + Thin3DVKBlendState *curBlendState_; + Thin3DVKDepthStencilState *curDepthStencilState_; + Thin3DVKShaderSet *curShaderSet_; + VkPrimitiveTopology curPrim_; + Thin3DVKVertexFormat *curVertexFormat_; + T3DCullMode curCullMode_; + + // We keep a pipeline state cache. + std::map pipelines_; + + VkDescriptorSetLayout descriptorSetLayout_; + VkPipelineLayout pipelineLayout_; + VkPipelineCache pipelineCache_; + + VkCommandPool cmdPool_; + VkDevice device_; + VkQueue queue_; + int queueFamilyIndex_; + + // State to apply at the next draw call if viewportDirty or scissorDirty are true. + bool viewportDirty_; + VkViewport viewport_; + bool scissorDirty_; + VkRect2D scissor_; + bool scissorEnabled_; + + VkRect2D noScissor_; // Simply a scissor covering the screen. + + enum {MAX_BOUND_TEXTURES = 1}; + Thin3DVKTexture *boundTextures_[MAX_BOUND_TEXTURES]; + Thin3DVKSamplerState *boundSamplers_[MAX_BOUND_TEXTURES]; + + VkCommandBuffer cmd_; // The current one + + struct FrameData { + VulkanPushBuffer *pushBuffer; + + // Per-frame descriptor set cache. As it's per frame and reset every frame, we don't need to + // worry about invalidating descriptors pointing to deleted textures. + std::map descSets_; + VkDescriptorPool descriptorPool; + }; + + FrameData frame_[2]; + + int frameNum_; + VulkanPushBuffer *push_; +}; + +VkFormat FormatToVulkan(T3DImageFormat fmt, int *bpp) { + switch (fmt) { + case RGBA8888: *bpp = 32; return VK_FORMAT_R8G8B8A8_UNORM; + case RGBA4444: *bpp = 16; return VK_FORMAT_R4G4B4A4_UNORM_PACK16; + case D24S8: *bpp = 32; return VK_FORMAT_D24_UNORM_S8_UINT; + case D16: *bpp = 16; return VK_FORMAT_D16_UNORM; + default: return VK_FORMAT_UNDEFINED; + } +} + +class Thin3DVKSamplerState : public Thin3DSamplerState { +public: + Thin3DVKSamplerState(VulkanContext *vulkan, const T3DSamplerStateDesc &desc) : vulkan_(vulkan) { + VkSamplerCreateInfo s = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + s.addressModeU = desc.wrapS ? VK_SAMPLER_ADDRESS_MODE_REPEAT : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + s.addressModeV = desc.wrapT ? VK_SAMPLER_ADDRESS_MODE_REPEAT : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + s.magFilter = desc.magFilt == T3DTextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + s.minFilter = desc.minFilt == T3DTextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + s.mipmapMode = desc.mipFilt == T3DTextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; + s.maxLod = 0.0; // TODO: Actually support mipmaps + + VkResult res = vkCreateSampler(vulkan_->GetDevice(), &s, nullptr, &sampler_); + assert(VK_SUCCESS == res); + } + ~Thin3DVKSamplerState() { + vkDestroySampler(vulkan_->GetDevice(), sampler_, nullptr); + } + + VkSampler GetSampler() { return sampler_; } + +private: + VulkanContext *vulkan_; + VkSampler sampler_; +}; + +Thin3DSamplerState *Thin3DVKContext::CreateSamplerState(const T3DSamplerStateDesc &desc) { + return new Thin3DVKSamplerState(vulkan_, desc); +} + +void Thin3DVKContext::SetSamplerStates(int start, int count, Thin3DSamplerState **state) { + for (int i = start; i < start + count; i++) { + boundSamplers_[i] = (Thin3DVKSamplerState *)state[i]; + } +} + +enum class TextureState { + UNINITIALIZED, + STAGED, + INITIALIZED, + PENDING_DESTRUCTION, +}; + +class Thin3DVKTexture : public Thin3DTexture { +public: + Thin3DVKTexture(VulkanContext *vulkan) : vulkan_(vulkan), vkTex_(nullptr) { + } + + Thin3DVKTexture(VulkanContext *vulkan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) + : vulkan_(vulkan), format_(format), mipLevels_(mipLevels) { + Create(type, format, width, height, depth, mipLevels); + } + + ~Thin3DVKTexture() { + Destroy(); + } + + bool Create(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override { + ILOG("texture created: %p", this); + format_ = format; + mipLevels_ = mipLevels; + width_ = width; + height_ = height; + depth_ = depth; + vkTex_ = new VulkanTexture(vulkan_); + // We don't actually do anything here. + return true; + } + + void SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) override; + void Finalize(int zim_flags) override; + void AutoGenMipmaps() {} + + VkImageView GetImageView() { return vkTex_->GetImageView(); } + +private: + void Destroy() { + ILOG("texture destroyed: %p", this); + if (vkTex_) { + vkTex_->Destroy(); + delete vkTex_; + } + } + + VulkanContext *vulkan_; + VulkanTexture *vkTex_; + + int mipLevels_; + + T3DImageFormat format_; +}; + +Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) + : viewportDirty_(false), scissorDirty_(false), vulkan_(vulkan), frameNum_(0) { + device_ = vulkan->GetDevice(); + + queue_ = vulkan->GetGraphicsQueue(); + queueFamilyIndex_ = vulkan->GetGraphicsQueueFamilyIndex(); + noScissor_.offset.x = 0; + noScissor_.offset.y = 0; + noScissor_.extent.width = pixel_xres; + noScissor_.extent.height = pixel_yres; + scissor_ = noScissor_; + viewport_.x = 0; + viewport_.y = 0; + viewport_.width = pixel_xres; + viewport_.height = pixel_yres; + viewport_.minDepth = 0.0f; + viewport_.maxDepth = 0.0f; + memset(boundTextures_, 0, sizeof(boundTextures_)); + CreatePresets(); + + VkCommandPoolCreateInfo p; + p.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + p.pNext = nullptr; + p.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + p.queueFamilyIndex = vulkan->GetGraphicsQueueFamilyIndex(); + VkResult res = vkCreateCommandPool(device_, &p, nullptr, &cmdPool_); + assert(VK_SUCCESS == res); + + VkDescriptorPoolSize dpTypes[2]; + dpTypes[0].descriptorCount = 200; + dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[1].descriptorCount = 200; + dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + VkDescriptorPoolCreateInfo dp; + dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + dp.pNext = nullptr; + dp.flags = 0; // Don't want to mess around with individually freeing these, let's go dynamic each frame. + dp.maxSets = 200; // 200 textures per frame should be enough for the UI... + dp.pPoolSizes = dpTypes; + dp.poolSizeCount = ARRAY_SIZE(dpTypes); + res = vkCreateDescriptorPool(device_, &dp, nullptr, &frame_[0].descriptorPool); + assert(VK_SUCCESS == res); + res = vkCreateDescriptorPool(device_, &dp, nullptr, &frame_[1].descriptorPool); + assert(VK_SUCCESS == res); + + frame_[0].pushBuffer = new VulkanPushBuffer(vulkan_, 1024 * 1024); + frame_[1].pushBuffer = new VulkanPushBuffer(vulkan_, 1024 * 1024); + + // binding 0 - uniform data + // binding 1 - combined sampler/image + VkDescriptorSetLayoutBinding bindings[2]; + bindings[0].descriptorCount = 1; + bindings[0].pImmutableSamplers = nullptr; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[0].binding = 0; + bindings[1].descriptorCount = 1; + bindings[1].pImmutableSamplers = nullptr; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[1].binding = 1; + + VkDescriptorSetLayoutCreateInfo dsl; + dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + dsl.pNext = nullptr; + dsl.bindingCount = 2; + dsl.pBindings = bindings; + res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_); + assert(VK_SUCCESS == res); + + VkPipelineLayoutCreateInfo pl; + pl.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pl.pNext = nullptr; + pl.pPushConstantRanges = nullptr; + pl.pushConstantRangeCount = 0; + pl.setLayoutCount = 1; + pl.pSetLayouts = &descriptorSetLayout_; + res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); + assert(VK_SUCCESS == res); + + pipelineCache_ = vulkan_->CreatePipelineCache(); +} + +Thin3DVKContext::~Thin3DVKContext() { + for (auto x : pipelines_) { + vkDestroyPipeline(device_, x.second, nullptr); + } + vkDestroyCommandPool(device_, cmdPool_, nullptr); + // This also destroys all descriptor sets. + for (int i = 0; i < 2; i++) { + frame_[i].descSets_.clear(); + vkDestroyDescriptorPool(device_, frame_[i].descriptorPool, nullptr); + frame_[i].pushBuffer->Destroy(vulkan_); + delete frame_[i].pushBuffer; + } + vkDestroyDescriptorSetLayout(device_, descriptorSetLayout_, nullptr); + vkDestroyPipelineLayout(device_, pipelineLayout_, nullptr); + vkDestroyPipelineCache(device_, pipelineCache_, nullptr); +} + +void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal) { + VkClearValue clearVal[2] = {}; + Uint8x4ToFloat4(colorval, clearVal[0].color.float32); + + // // Debug flicker - used to see if we swap at all. no longer necessary + // if (frameNum_ & 1) + // clearVal[0].color.float32[2] = 1.0f; + + clearVal[1].depthStencil.depth = depthVal; + clearVal[1].depthStencil.stencil = stencilVal; + + cmd_ = vulkan_->BeginSurfaceRenderPass(clearVal); + + FrameData *frame = &frame_[frameNum_ & 1]; + push_ = frame->pushBuffer; + + // OK, we now know that nothing is reading from this frame's data pushbuffer, + push_->Reset(); + push_->Begin(device_); + + frame->descSets_.clear(); + VkResult result = vkResetDescriptorPool(device_, frame->descriptorPool, 0); + assert(result == VK_SUCCESS); + + noScissor_.extent.width = pixel_xres; + noScissor_.extent.height = pixel_yres; + scissorDirty_ = true; + viewportDirty_ = true; +} + +void Thin3DVKContext::End() { + // Stop collecting data in the frame's data pushbuffer. + push_->End(device_); + vulkan_->EndSurfaceRenderPass(); + + frameNum_++; + cmd_ = nullptr; // will be set on the next begin + push_ = nullptr; + + DirtyDynamicState(); +} + +VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet(VkBuffer buf) { + DescriptorSetKey key; + + FrameData *frame = &frame_[frameNum_ & 1]; + + key.texture_ = boundTextures_[0]; + key.sampler_ = boundSamplers_[0]; + key.buffer_ = buf; + + auto iter = frame->descSets_.find(key); + if (iter != frame->descSets_.end()) { + return iter->second; + } + + VkDescriptorSet descSet; + VkDescriptorSetAllocateInfo alloc; + alloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc.pNext = nullptr; + alloc.descriptorPool = frame->descriptorPool; + alloc.pSetLayouts = &descriptorSetLayout_; + alloc.descriptorSetCount = 1; + // OutputDebugStringA("Allocated a desc set!\n"); + VkResult res = vkAllocateDescriptorSets(device_, &alloc, &descSet); + assert(VK_SUCCESS == res); + + // bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + VkDescriptorBufferInfo bufferDesc; + bufferDesc.buffer = buf; + bufferDesc.offset = 0; + bufferDesc.range = curShaderSet_->GetUBOSize(); + + VkDescriptorImageInfo imageDesc; + imageDesc.imageView = boundTextures_[0]->GetImageView(); + imageDesc.sampler = boundSamplers_[0]->GetSampler(); + imageDesc.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + VkWriteDescriptorSet writes[2]; + memset(writes, 0, sizeof(writes)); + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].pNext = nullptr; + writes[0].dstSet = descSet; + writes[0].dstArrayElement = 0; + writes[0].dstBinding = 0; + writes[0].pBufferInfo = &bufferDesc; + writes[0].pImageInfo = nullptr; + writes[0].pTexelBufferView = nullptr; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].pNext = nullptr; + writes[1].dstSet = descSet; + writes[1].dstArrayElement = 0; + writes[1].dstBinding = 1; + writes[1].pBufferInfo = nullptr; + writes[1].pImageInfo = &imageDesc; + writes[1].pTexelBufferView = nullptr; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + vkUpdateDescriptorSets(device_, 2, writes, 0, nullptr); + + frame->descSets_[key] = descSet; + return descSet; +} + +VkPipeline Thin3DVKContext::GetOrCreatePipeline() { + PipelineKey key; + key.blend = curBlendState_; + key.depthStencil = curDepthStencilState_; + key.shaderSet = curShaderSet_; + key.topology = curPrim_; + key.cullMode = curCullMode_; + + auto iter = pipelines_.find(key); + if (iter != pipelines_.end()) { + return iter->second; + } + + VkPipelineShaderStageCreateInfo stages[2]; + stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[0].pNext = nullptr; + stages[0].pSpecializationInfo = nullptr; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = curShaderSet_->vshader->Get(); + stages[0].pName = "main"; + stages[0].flags = 0; + + stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[1].pNext = nullptr; + stages[1].pSpecializationInfo = nullptr; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = curShaderSet_->fshader->Get(); + stages[1].pName = "main"; + stages[1].flags = 0; + + VkPipelineColorBlendStateCreateInfo colorBlend; + VkPipelineColorBlendAttachmentState attachment0; + curBlendState_->ToVulkan(&colorBlend, &attachment0); + + VkPipelineDepthStencilStateCreateInfo depthStencil; + curDepthStencilState_->ToVulkan(&depthStencil); + + VkPipelineVertexInputStateCreateInfo vertex; + VkVertexInputAttributeDescription attrDescs[4]; + VkVertexInputBindingDescription bindDescs[1]; + curVertexFormat_->ToVulkan(&vertex, attrDescs, bindDescs); + + VkPipelineInputAssemblyStateCreateInfo inputAssembly; + inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + inputAssembly.pNext = nullptr; + inputAssembly.topology = curPrim_; + inputAssembly.primitiveRestartEnable = false; + + VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamicInfo; + dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamicInfo.pNext = nullptr; + dynamicInfo.dynamicStateCount = ARRAY_SIZE(dynamics); + dynamicInfo.pDynamicStates = dynamics; + + VkPipelineRasterizationStateCreateInfo raster; + raster.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster.pNext = nullptr; + switch (curCullMode_) { + case NO_CULL: raster.cullMode = VK_CULL_MODE_NONE; break; + case CW: raster.cullMode = VK_CULL_MODE_BACK_BIT; break; + default: + case CCW: raster.cullMode = VK_CULL_MODE_FRONT_BIT; break; + } + raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + raster.polygonMode = VK_POLYGON_MODE_FILL; + raster.rasterizerDiscardEnable = false; + raster.lineWidth = 1.0f; + raster.depthBiasClamp = 0.0f; + raster.depthBiasEnable = false; + raster.depthClampEnable = false; + raster.depthBiasSlopeFactor = 0.0; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.pNext = nullptr; + ms.pSampleMask = nullptr; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineViewportStateCreateInfo vs; + vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vs.pNext = nullptr; + vs.viewportCount = 1; + vs.scissorCount = 1; + vs.pViewports = nullptr; // dynamic + vs.pScissors = nullptr; // dynamic + + VkGraphicsPipelineCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + info.pNext = nullptr; + info.flags = 0; + info.stageCount = 2; + info.pStages = stages; + info.pColorBlendState = &colorBlend; + info.pDepthStencilState = &depthStencil; + info.pDynamicState = &dynamicInfo; + info.pInputAssemblyState = &inputAssembly; + info.pTessellationState = nullptr; + info.pMultisampleState = &ms; + info.pVertexInputState = &vertex; + info.pRasterizationState = &raster; + info.pViewportState = &vs; // Must set viewport and scissor counts even if we set the actual state dynamically. + info.layout = pipelineLayout_; + info.subpass = 0; + info.renderPass = vulkan_->GetSurfaceRenderPass(); + + // OK, need to create a new pipeline. + VkPipeline pipeline; + VkResult result = vkCreateGraphicsPipelines(device_, pipelineCache_, 1, &info, nullptr, &pipeline); + if (result != VK_SUCCESS) { + ELOG("Failed to create graphics pipeline"); + return VK_NULL_HANDLE; + } + + pipelines_.insert(std::make_pair(key, pipeline)); + return pipeline; +} + +void Thin3DVKContext::SetScissorRect(int left, int top, int width, int height) { + scissor_.offset.x = left; + scissor_.offset.y = top; + scissor_.extent.width = width; + scissor_.extent.height = height; + scissorDirty_ = true; +} + +void Thin3DVKContext::SetViewports(int count, T3DViewport *viewports) { + viewport_.x = viewports[0].TopLeftX; + viewport_.y = viewports[0].TopLeftY; + viewport_.width = viewports[0].Width; + viewport_.height = viewports[0].Height; + viewport_.minDepth = viewports[0].MinDepth; + viewport_.maxDepth = viewports[0].MaxDepth; + viewportDirty_ = true; +} + +void Thin3DVKContext::ApplyDynamicState() { + if (scissorDirty_) { + if (scissorEnabled_) { + vkCmdSetScissor(cmd_, 0, 1, &scissor_); + } else { + vkCmdSetScissor(cmd_, 0, 1, &noScissor_); + } + scissorDirty_ = false; + } + if (viewportDirty_) { + vkCmdSetViewport(cmd_, 0, 1, &viewport_); + viewportDirty_ = false; + } +} + +void Thin3DVKContext::DirtyDynamicState() { + scissorDirty_ = true; + viewportDirty_ = true; +} + +Thin3DVertexFormat *Thin3DVKContext::CreateVertexFormat(const std::vector &components, int stride, Thin3DShader *vshader) { + Thin3DVKVertexFormat *fmt = new Thin3DVKVertexFormat(); + fmt->components_ = components; + fmt->stride_ = stride; + return fmt; +} + +Thin3DTexture *Thin3DVKContext::CreateTexture() { + return new Thin3DVKTexture(vulkan_); +} + +Thin3DTexture *Thin3DVKContext::CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) { + return new Thin3DVKTexture(vulkan_, type, format, width, height, depth, mipLevels); +} + +void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) { + int bpp; + VkFormat vulkanFormat = FormatToVulkan(format_, &bpp); + int bytesPerPixel = bpp / 8; + vkTex_->Create(width, height, vulkanFormat); + int rowPitch; + uint8_t *dstData = vkTex_->Lock(0, &rowPitch); + for (int y = 0; y < height; y++) { + memcpy(dstData + rowPitch * y, data + stride * y, width * bytesPerPixel); + } + vkTex_->Unlock(); +} + +void Thin3DVKTexture::Finalize(int zim_flags) { + // TODO +} + +static bool isPowerOf2(int n) { + return n == 1 || (n & (n - 1)) == 0; +} + +Thin3DDepthStencilState *Thin3DVKContext::CreateDepthStencilState(bool depthTestEnabled, bool depthWriteEnabled, T3DComparison depthCompare) { + Thin3DVKDepthStencilState *ds = new Thin3DVKDepthStencilState(); + ds->depthTestEnabled = depthTestEnabled; + ds->depthWriteEnabled = depthWriteEnabled; + ds->depthComp = compToVK[depthCompare]; + return ds; +} + +Thin3DBlendState *Thin3DVKContext::CreateBlendState(const T3DBlendStateDesc &desc) { + Thin3DVKBlendState *bs = new Thin3DVKBlendState(); + bs->blendEnabled = desc.enabled; + bs->eqCol = blendEqToGL[desc.eqCol]; + bs->srcCol = blendFactorToVk[desc.srcCol]; + bs->dstColor = blendFactorToVk[desc.dstCol]; + bs->eqAlpha = blendEqToGL[desc.eqAlpha]; + bs->srcAlpha = blendFactorToVk[desc.srcAlpha]; + bs->dstAlpha = blendFactorToVk[desc.dstAlpha]; + bs->logicEnabled = desc.logicEnabled; + bs->logicOp = logicOpToVK[desc.logicOp]; + return bs; +} + +Thin3DBuffer *Thin3DVKContext::CreateBuffer(size_t size, uint32_t usageFlags) { + return new Thin3DVKBuffer(size, usageFlags); +} + +Thin3DShaderSet *Thin3DVKContext::CreateShaderSet(Thin3DShader *vshader, Thin3DShader *fshader) { + if (!vshader || !fshader) { + ELOG("ShaderSet requires both a valid vertex and a fragment shader: %p %p", vshader, fshader); + return NULL; + } + Thin3DVKShaderSet *shaderSet = new Thin3DVKShaderSet(); + vshader->AddRef(); + fshader->AddRef(); + shaderSet->vshader = static_cast(vshader); + shaderSet->fshader = static_cast(fshader); + if (shaderSet->Link()) { + return shaderSet; + } else { + delete shaderSet; + return NULL; + } +} + +void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures) { + for (int i = start; i < start + count; i++) { + boundTextures_[i] = static_cast(textures[i]); + } +} + +Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { + Thin3DVKShader *shader = new Thin3DVKShader(false); + if (shader->Compile(vulkan_, vulkan_source)) { + return shader; + } else { + shader->Release(); + return nullptr; + } +} + +Thin3DShader *Thin3DVKContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { + Thin3DVKShader *shader = new Thin3DVKShader(true); + if (shader->Compile(vulkan_, vulkan_source)) { + return shader; + } else { + shader->Release(); + return nullptr; + } +} + +bool Thin3DVKShaderSet::Link() { + // There is no link step. However, we will create and cache Pipeline objects in the device context. + return true; +} + +int Thin3DVKShaderSet::GetUniformLoc(const char *name) { + int loc = -1; + + // HACK! As we only use one uniform we hardcode it. + if (!strcmp(name, "WorldViewProj")) { + return 0; + } + + return loc; +} + +void Thin3DVKShaderSet::SetVector(const char *name, float *value, int n) { + // TODO: Implement +} + +void Thin3DVKShaderSet::SetMatrix4x4(const char *name, const float value[16]) { + int loc = GetUniformLoc(name); + if (loc != -1) { + memcpy(ubo_ + loc, value, 16 * sizeof(float)); + } +} + +void Thin3DVKContext::SetRenderState(T3DRenderState rs, uint32_t value) { + switch (rs) { + case T3DRenderState::CULL_MODE: + curCullMode_ = (T3DCullMode)value; + break; + } +} + +void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + Thin3DVKBuffer *vbuf = static_cast(vdata); + + VkBuffer vulkanVbuf; + VkBuffer vulkanUBObuf; + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanVbuf); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), &vulkanUBObuf); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + VkBuffer buffers[1] = { vulkanVbuf }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + vkCmdDraw(cmd_, vertexCount, 1, offset, 0); +} + +void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + + Thin3DVKBuffer *ibuf = (Thin3DVKBuffer *)idata; + Thin3DVKBuffer *vbuf = (Thin3DVKBuffer *)vdata; + + VkBuffer vulkanVbuf, vulkanIbuf, vulkanUBObuf; + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanUBObuf); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), &vulkanVbuf); + size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize(), &vulkanIbuf); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + + VkBuffer buffers[1] = { vulkanVbuf }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + + vkCmdBindIndexBuffer(cmd_, vulkanIbuf, ibBindOffset, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, offset, 0); +} + +void Thin3DVKContext::DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, const void *vdata, int vertexCount) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + + VkBuffer vulkanVbuf, vulkanUBObuf; + size_t vbBindOffset = push_->Push(vdata, vertexCount * curVertexFormat_->stride_, &vulkanVbuf); + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanUBObuf); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + VkBuffer buffers[1] = { vulkanVbuf }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + vkCmdDraw(cmd_, vertexCount, 1, 0, 0); +} + +void Thin3DVKContext::Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) { + if (mask & T3DClear::COLOR) { + VkClearColorValue col; + Uint8x4ToFloat4(colorval, col.float32); + + /* + VkRect3D rect; + rect.extent.width = + vkCmdClearColorAttachment(cmdBuf_, 0, imageLayout_, &col, 1, nullptr); + */ + } + if (mask & (T3DClear::DEPTH | T3DClear::STENCIL)) { + + } +} + +Thin3DContext *T3DCreateVulkanContext(VulkanContext *vulkan) { + return new Thin3DVKContext(vulkan); +} + +void AddFeature(std::vector &features, const char *name, VkBool32 available, VkBool32 enabled) { + char buf[512]; + snprintf(buf, sizeof(buf), "%s: Available: %d Enabled: %d", name, (int)available, (int)enabled); + features.push_back(buf); +} + +std::vector Thin3DVKContext::GetFeatureList() { + const VkPhysicalDeviceFeatures &available = vulkan_->GetFeaturesAvailable(); + const VkPhysicalDeviceFeatures &enabled = vulkan_->GetFeaturesEnabled(); + std::vector features; + AddFeature(features, "dualSrcBlend", available.dualSrcBlend, enabled.dualSrcBlend); + AddFeature(features, "logicOp", available.logicOp, enabled.logicOp); + AddFeature(features, "geometryShader", available.geometryShader, enabled.geometryShader); + AddFeature(features, "depthBounds", available.depthBounds, enabled.depthBounds); + AddFeature(features, "depthClamp", available.depthClamp, enabled.depthClamp); + AddFeature(features, "fillModeNonSolid", available.fillModeNonSolid, enabled.fillModeNonSolid); + AddFeature(features, "largePoints", available.largePoints, enabled.largePoints); + AddFeature(features, "wideLines", available.wideLines, enabled.wideLines); + AddFeature(features, "pipelineStatisticsQuery", available.pipelineStatisticsQuery, enabled.pipelineStatisticsQuery); + AddFeature(features, "samplerAnisotropy", available.samplerAnisotropy, enabled.samplerAnisotropy); + AddFeature(features, "textureCompressionBC", available.textureCompressionBC, enabled.textureCompressionBC); + AddFeature(features, "textureCompressionETC2", available.textureCompressionETC2, enabled.textureCompressionETC2); + AddFeature(features, "textureCompressionASTC_LDR", available.textureCompressionASTC_LDR, enabled.textureCompressionASTC_LDR); + AddFeature(features, "shaderClipDistance", available.shaderClipDistance, enabled.shaderClipDistance); + AddFeature(features, "shaderCullDistance", available.shaderCullDistance, enabled.shaderCullDistance); + AddFeature(features, "occlusionQueryPrecise", available.occlusionQueryPrecise, enabled.occlusionQueryPrecise); + AddFeature(features, "multiDrawIndirect", available.multiDrawIndirect, enabled.multiDrawIndirect); + + // Also list texture formats and their properties. + for (int i = VK_FORMAT_BEGIN_RANGE; i <= VK_FORMAT_END_RANGE; i++) { + // TODO + } + + return features; +} diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp new file mode 100644 index 0000000000..ec46b011a9 --- /dev/null +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -0,0 +1,142 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#undef min +#undef max + +#endif + +#include +#include +#include + +#ifdef USE_CRT_DBG +#undef new +#endif + +#include "ext/glslang/SPIRV/GlslangToSpv.h" +#include "ext/glslang/SPIRV/disassemble.h" + +#ifdef USE_CRT_DBG +#define new DBG_NEW +#endif + +#include "thin3d/vulkan_utils.h" + +void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageTiling tiling, VkImageUsageFlags usage, int width, int height) { + VkDevice device = vulkan->GetDevice(); + width_ = width; + height_ = height; + + VkImageCreateInfo i = {}; + i.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + i.pNext = NULL; + i.imageType = VK_IMAGE_TYPE_2D; + i.format = format; + i.extent = { (uint32_t)width, (uint32_t)height, 1 }; + i.mipLevels = 1; + i.arrayLayers = 1; + i.samples = VK_SAMPLE_COUNT_1_BIT; + i.tiling = tiling; + i.usage = usage; + i.flags = 0; + i.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + i.queueFamilyIndexCount = 0; + i.pQueueFamilyIndices = nullptr; + i.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + VkMemoryRequirements mem_reqs; + + VkResult err = vkCreateImage(device, &i, nullptr, &image_); + assert(!err); + + vkGetImageMemoryRequirements(device, image_, &mem_reqs); + + mem_alloc_.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc_.pNext = NULL; + mem_alloc_.allocationSize = mem_reqs.size; + mem_alloc_.memoryTypeIndex = 0; + + bool res = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, required_props, &mem_alloc_.memoryTypeIndex); + assert(res); + + err = vkAllocateMemory(device, &mem_alloc_, nullptr, &memory_); + assert(!err); + + err = vkBindImageMemory(device, image_, memory_, 0); // at offset 0. + assert(!err); +} + +void VulkanImage::SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch) { + VkImageSubresource subres; + subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subres.mipLevel = 0; + subres.arrayLayer = 0; + + VkSubresourceLayout layout; + void *destData; + vkGetImageSubresourceLayout(device, image_, &subres, &layout); + + VkResult err = vkMapMemory(device, memory_, 0, mem_alloc_.allocationSize, 0, &destData); + assert(!err); + + uint8_t *writePtr = (uint8_t *)destData + layout.offset; + int bpp = 4; // TODO + for (int y = 0; y < height; y++) { + memcpy(writePtr + y * layout.rowPitch, data + y * pitch, bpp * width); + } + + vkUnmapMemory(device, memory_); +} + + +void VulkanImage::ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout) { + VkImageMemoryBarrier image_memory_barrier; + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.pNext = NULL; + image_memory_barrier.dstAccessMask = 0; + image_memory_barrier.srcAccessMask = 0; + image_memory_barrier.oldLayout = old_image_layout; + image_memory_barrier.newLayout = new_image_layout; + image_memory_barrier.image = image_; + image_memory_barrier.subresourceRange.aspectMask = aspectMask; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.subresourceRange.baseArrayLayer = 0; + image_memory_barrier.subresourceRange.baseMipLevel = 0; + image_memory_barrier.subresourceRange.levelCount = 1; + + if (old_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + // Make sure anything that was copying from this image has completed + image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + // Make sure any Copy or CPU writes to image are flushed + image_memory_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; + } + + VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + vkCmdPipelineBarrier(cmd, src_stages, dest_stages, false, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); +} diff --git a/ext/native/ui/ui_screen.cpp b/ext/native/ui/ui_screen.cpp index 172b357273..acad8fbaca 100644 --- a/ext/native/ui/ui_screen.cpp +++ b/ext/native/ui/ui_screen.cpp @@ -58,7 +58,7 @@ void UIScreen::update(InputState &input) { void UIScreen::preRender() { Thin3DContext *thin3d = screenManager()->getThin3DContext(); - thin3d->Clear(T3DClear::COLOR | T3DClear::DEPTH | T3DClear::STENCIL, 0xFF000000, 0.0f, 0); + thin3d->Begin(true, 0xFF000000, 0.0f, 0); T3DViewport viewport; viewport.TopLeftX = 0; @@ -72,6 +72,8 @@ void UIScreen::preRender() { } void UIScreen::postRender() { + Thin3DContext *thin3d = screenManager()->getThin3DContext(); + thin3d->End(); } void UIScreen::render() { diff --git a/ext/native/util/text/parsers.cpp b/ext/native/util/text/parsers.cpp index 748a292a50..ea53d43d6f 100644 --- a/ext/native/util/text/parsers.cpp +++ b/ext/native/util/text/parsers.cpp @@ -22,6 +22,11 @@ std::string Version::ToString() const { return std::string(temp); } +int Version::ToInteger() const { + // This allows for ~2000 major versions, ~100 minor versions, and ~10000 sub versions. + return major * 1000000 + minor * 10000 + sub; +} + bool ParseMacAddress(std::string str, uint8_t macAddr[6]) { int mac[6]; if (6 != sscanf(str.c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5])) { diff --git a/ext/native/util/text/parsers.h b/ext/native/util/text/parsers.h index 7f763cf9b8..fbf2c36d99 100644 --- a/ext/native/util/text/parsers.h +++ b/ext/native/util/text/parsers.h @@ -48,6 +48,7 @@ struct Version { } std::string ToString() const; + int ToInteger() const; private: bool ParseVersionString(std::string str); }; diff --git a/ext/vulkan/icd-spv.h b/ext/vulkan/icd-spv.h index b6640a4b3d..3019a1d2ca 100644 --- a/ext/vulkan/icd-spv.h +++ b/ext/vulkan/icd-spv.h @@ -1,28 +1,27 @@ /* + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. * - * Copyright (C) 2015-2016 Valve Corporation - * Copyright (C) 2015-2016 LunarG, Inc. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: * - * 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(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. * - * 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 + * THE MATERIALS ARE 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. + * 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 MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. * * Author: Cody Northrop - * */ #ifndef ICD_SPV_H diff --git a/ext/vulkan/vk_debug_marker_layer.h b/ext/vulkan/vk_debug_marker_layer.h deleted file mode 100644 index e882b02b48..0000000000 --- a/ext/vulkan/vk_debug_marker_layer.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// File: vk_debug_marker_layer.h -// -/* - * Copyright (c) 2015-2016 The Khronos Group Inc. - * Copyright (c) 2015-2016 Valve Corporation - * Copyright (c) 2015-2016 LunarG, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and/or associated documentation files (the "Materials"), to - * deal in the Materials without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Materials, and to permit persons to whom the Materials are - * furnished to do so, subject to the following conditions: - * - * The above copyright notice(s) and this permission notice shall be included in - * all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE 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 MATERIALS OR THE - * USE OR OTHER DEALINGS IN THE MATERIALS. - * - * Authors: - * Jon Ashburn - * Courtney Goeltzenleuchter - */ - -#pragma once - -#include "vulkan.h" -#include "vk_lunarg_debug_marker.h" -#include "vk_layer.h" - -typedef struct VkLayerDebugMarkerDispatchTable_ { - PFN_vkCmdDbgMarkerBegin CmdDbgMarkerBegin; - PFN_vkCmdDbgMarkerEnd CmdDbgMarkerEnd; - PFN_vkDbgSetObjectTag DbgSetObjectTag; - PFN_vkDbgSetObjectName DbgSetObjectName; -} VkLayerDebugMarkerDispatchTable; diff --git a/ext/vulkan/vk_icd.h b/ext/vulkan/vk_icd.h index 60b29e037b..fdb1e6e433 100644 --- a/ext/vulkan/vk_icd.h +++ b/ext/vulkan/vk_icd.h @@ -30,7 +30,7 @@ #ifndef VKICD_H #define VKICD_H -#include "vk_platform.h" +#include "vulkan.h" /* * The ICD must reserve space for a pointer for the loader's dispatch @@ -65,6 +65,7 @@ typedef enum _VkIcdWsiPlatform { VK_ICD_WSI_PLATFORM_WIN32, VK_ICD_WSI_PLATFORM_XCB, VK_ICD_WSI_PLATFORM_XLIB, + VK_ICD_WSI_PLATFORM_DISPLAY } VkIcdWsiPlatform; typedef struct _VkIcdSurfaceBase { @@ -111,4 +112,14 @@ typedef struct _VkIcdSurfaceXlib { } VkIcdSurfaceXlib; #endif // VK_USE_PLATFORM_XLIB_KHR +typedef struct _VkIcdSurfaceDisplay { + VkIcdSurfaceBase base; + VkDisplayModeKHR displayMode; + uint32_t planeIndex; + uint32_t planeStackIndex; + VkSurfaceTransformFlagBitsKHR transform; + float globalAlpha; + VkDisplayPlaneAlphaFlagBitsKHR alphaMode; + VkExtent2D imageExtent; +} VkIcdSurfaceDisplay; #endif // VKICD_H diff --git a/ext/vulkan/vk_layer.h b/ext/vulkan/vk_layer.h index 2487043401..95d8802553 100644 --- a/ext/vulkan/vk_layer.h +++ b/ext/vulkan/vk_layer.h @@ -34,7 +34,6 @@ #pragma once #include "vulkan.h" -#include "vk_lunarg_debug_marker.h" #if defined(__GNUC__) && __GNUC__ >= 4 #define VK_LAYER_EXPORT __attribute__((visibility("default"))) #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) @@ -226,6 +225,20 @@ typedef struct VkLayerInstanceDispatchTable_ { #ifdef VK_USE_PLATFORM_ANDROID_KHR PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR; #endif + PFN_vkGetPhysicalDeviceDisplayPropertiesKHR + GetPhysicalDeviceDisplayPropertiesKHR; + PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR + GetPhysicalDeviceDisplayPlanePropertiesKHR; + PFN_vkGetDisplayPlaneSupportedDisplaysKHR + GetDisplayPlaneSupportedDisplaysKHR; + PFN_vkGetDisplayModePropertiesKHR + GetDisplayModePropertiesKHR; + PFN_vkCreateDisplayModeKHR + CreateDisplayModeKHR; + PFN_vkGetDisplayPlaneCapabilitiesKHR + GetDisplayPlaneCapabilitiesKHR; + PFN_vkCreateDisplayPlaneSurfaceKHR + CreateDisplayPlaneSurfaceKHR; } VkLayerInstanceDispatchTable; // LL node for tree of dbg callback functions diff --git a/ext/vulkan/vk_lunarg_debug_marker.h b/ext/vulkan/vk_lunarg_debug_marker.h deleted file mode 100644 index edff2b9eee..0000000000 --- a/ext/vulkan/vk_lunarg_debug_marker.h +++ /dev/null @@ -1,98 +0,0 @@ -// -// File: vk_lunarg_debug_marker.h -// -/* - * Copyright (c) 2015-2016 The Khronos Group Inc. - * Copyright (c) 2015-2016 Valve Corporation - * Copyright (c) 2015-2016 LunarG, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and/or associated documentation files (the "Materials"), to - * deal in the Materials without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Materials, and to permit persons to whom the Materials are - * furnished to do so, subject to the following conditions: - * - * The above copyright notice(s) and this permission notice shall be included in - * all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE 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 MATERIALS OR THE - * USE OR OTHER DEALINGS IN THE MATERIALS. - * - * Authors: - * Jon Ashburn - * Courtney Goeltzenleuchter - */ - -#ifndef __VK_DEBUG_MARKER_H__ -#define __VK_DEBUG_MARKER_H__ - -#include "vulkan.h" - -#define VK_DEBUG_MARKER_EXTENSION_NUMBER 6 -#define VK_DEBUG_MARKER_EXTENSION_REVISION 1 -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -/* -*************************************************************************************************** -* DebugMarker Vulkan Extension API -*************************************************************************************************** -*/ - -#define DEBUG_MARKER_EXTENSION_NAME "VK_LUNARG_DEBUG_MARKER" - -// ------------------------------------------------------------------------------------------------ -// Enumerations - -#define VK_DEBUG_MARKER_ENUM_EXTEND(type, id) \ - ((type)(VK_DEBUG_MARKER_EXTENSION_NUMBER * -1000 + (id))) - -#define VK_OBJECT_INFO_TYPE_DBG_OBJECT_TAG \ - VK_DEBUG_MARKER_ENUM_EXTEND(VkDbgObjectInfoType, 0) -#define VK_OBJECT_INFO_TYPE_DBG_OBJECT_NAME \ - VK_DEBUG_MARKER_ENUM_EXTEND(VkDbgObjectInfoType, 1) - -// ------------------------------------------------------------------------------------------------ -// API functions - -typedef void(VKAPI_PTR *PFN_vkCmdDbgMarkerBegin)(VkCommandBuffer commandBuffer, - const char *pMarker); -typedef void(VKAPI_PTR *PFN_vkCmdDbgMarkerEnd)(VkCommandBuffer commandBuffer); -typedef VkResult(VKAPI_PTR *PFN_vkDbgSetObjectTag)( - VkDevice device, VkDebugReportObjectTypeEXT objType, uint64_t object, - size_t tagSize, const void *pTag); -typedef VkResult(VKAPI_PTR *PFN_vkDbgSetObjectName)( - VkDevice device, VkDebugReportObjectTypeEXT objType, uint64_t object, - size_t nameSize, const char *pName); - -#ifndef VK_NO_PROTOTYPES - -// DebugMarker extension entrypoints -VKAPI_ATTR void VKAPI_CALL -vkCmdDbgMarkerBegin(VkCommandBuffer commandBuffer, const char *pMarker); - -VKAPI_ATTR void VKAPI_CALL vkCmdDbgMarkerEnd(VkCommandBuffer commandBuffer); - -VKAPI_ATTR VkResult VKAPI_CALL -vkDbgSetObjectTag(VkDevice device, VkDebugReportObjectTypeEXT objType, - uint64_t object, size_t tagSize, const void *pTag); - -VKAPI_ATTR VkResult VKAPI_CALL -vkDbgSetObjectName(VkDevice device, VkDebugReportObjectTypeEXT objType, - uint64_t object, size_t nameSize, const char *pName); - -#endif // VK_NO_PROTOTYPES - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus - -#endif // __VK_DEBUG_MARKER_H__ diff --git a/ext/vulkan/vk_platform.h b/ext/vulkan/vk_platform.h index a53e725a9a..075a18cab3 100644 --- a/ext/vulkan/vk_platform.h +++ b/ext/vulkan/vk_platform.h @@ -2,7 +2,7 @@ // File: vk_platform.h // /* -** Copyright (c) 2014-2015 The Khronos Group Inc. +** Copyright (c) 2014-2016 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the diff --git a/ext/vulkan/vulkan-1.lib b/ext/vulkan/vulkan-1.lib deleted file mode 100644 index fa61ca91d0..0000000000 Binary files a/ext/vulkan/vulkan-1.lib and /dev/null differ diff --git a/ext/vulkan/vulkan.h b/ext/vulkan/vulkan.h index cd6a71ac1a..f57c4d9368 100644 --- a/ext/vulkan/vulkan.h +++ b/ext/vulkan/vulkan.h @@ -1,5 +1,5 @@ -#ifndef __vulkan_h_ -#define __vulkan_h_ 1 +#ifndef VULKAN_H_ +#define VULKAN_H_ 1 #ifdef __cplusplus extern "C" { @@ -41,7 +41,7 @@ extern "C" { (((major) << 22) | ((minor) << 12) | (patch)) // Vulkan API version supported by this file -#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 3) +#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 5) #define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) #define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) @@ -142,6 +142,7 @@ typedef enum VkResult { VK_ERROR_OUT_OF_DATE_KHR = -1000001004, VK_ERROR_INCOMPATIBLE_DISPLAY_KHR = -1000003001, VK_ERROR_VALIDATION_FAILED_EXT = -1000011001, + VK_ERROR_INVALID_SHADER_NV = -1000012000, VK_RESULT_BEGIN_RANGE = VK_ERROR_FORMAT_NOT_SUPPORTED, VK_RESULT_END_RANGE = VK_INCOMPLETE, VK_RESULT_RANGE_SIZE = (VK_INCOMPLETE - VK_ERROR_FORMAT_NOT_SUPPORTED + 1), @@ -209,7 +210,7 @@ typedef enum VkStructureType { VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR = 1000007000, VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR = 1000008000, VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000, - VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT = 1000011000, + VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT = 1000011000, VK_STRUCTURE_TYPE_BEGIN_RANGE = VK_STRUCTURE_TYPE_APPLICATION_INFO, VK_STRUCTURE_TYPE_END_RANGE = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, VK_STRUCTURE_TYPE_RANGE_SIZE = (VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO - VK_STRUCTURE_TYPE_APPLICATION_INFO + 1), @@ -701,8 +702,8 @@ typedef enum VkSamplerAddressMode { VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER = 3, VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4, VK_SAMPLER_ADDRESS_MODE_BEGIN_RANGE = VK_SAMPLER_ADDRESS_MODE_REPEAT, - VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, - VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1), + VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, + VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1), VK_SAMPLER_ADDRESS_MODE_MAX_ENUM = 0x7FFFFFFF } VkSamplerAddressMode; @@ -979,7 +980,7 @@ typedef enum VkShaderStageFlagBits { VK_SHADER_STAGE_GEOMETRY_BIT = 0x00000008, VK_SHADER_STAGE_FRAGMENT_BIT = 0x00000010, VK_SHADER_STAGE_COMPUTE_BIT = 0x00000020, - VK_SHADER_STAGE_ALL_GRAPHICS = 0x1F, + VK_SHADER_STAGE_ALL_GRAPHICS = 0x0000001F, VK_SHADER_STAGE_ALL = 0x7FFFFFFF, } VkShaderStageFlagBits; typedef VkFlags VkPipelineVertexInputStateCreateFlags; @@ -992,7 +993,7 @@ typedef enum VkCullModeFlagBits { VK_CULL_MODE_NONE = 0, VK_CULL_MODE_FRONT_BIT = 0x00000001, VK_CULL_MODE_BACK_BIT = 0x00000002, - VK_CULL_MODE_FRONT_AND_BACK = 0x3, + VK_CULL_MODE_FRONT_AND_BACK = 0x00000003, } VkCullModeFlagBits; typedef VkFlags VkCullModeFlags; typedef VkFlags VkPipelineMultisampleStateCreateFlags; @@ -1083,7 +1084,7 @@ typedef VkFlags VkCommandBufferResetFlags; typedef enum VkStencilFaceFlagBits { VK_STENCIL_FACE_FRONT_BIT = 0x00000001, VK_STENCIL_FACE_BACK_BIT = 0x00000002, - VK_STENCIL_FRONT_AND_BACK = 0x3, + VK_STENCIL_FRONT_AND_BACK = 0x00000003, } VkStencilFaceFlagBits; typedef VkFlags VkStencilFaceFlags; @@ -3326,8 +3327,8 @@ typedef enum VkDisplayPlaneAlphaFlagBitsKHR { VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR = 0x00000004, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR = 0x00000008, } VkDisplayPlaneAlphaFlagBitsKHR; -typedef VkFlags VkDisplayModeCreateFlagsKHR; typedef VkFlags VkDisplayPlaneAlphaFlagsKHR; +typedef VkFlags VkDisplayModeCreateFlagsKHR; typedef VkFlags VkDisplaySurfaceCreateFlagsKHR; typedef struct VkDisplayPropertiesKHR { @@ -3667,11 +3668,17 @@ VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceWin32PresentationSupportKHR( #endif #endif /* VK_USE_PLATFORM_WIN32_KHR */ +#define VK_KHR_sampler_mirror_clamp_to_edge 1 +#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_SPEC_VERSION 1 +#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME "VK_KHR_sampler_mirror_clamp_to_edge" + + #define VK_EXT_debug_report 1 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugReportCallbackEXT) -#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 1 +#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 2 #define VK_EXT_DEBUG_REPORT_EXTENSION_NAME "VK_EXT_debug_report" +#define VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT typedef enum VkDebugReportObjectTypeEXT { @@ -3768,6 +3775,11 @@ VKAPI_ATTR void VKAPI_CALL vkDebugReportMessageEXT( const char* pMessage); #endif +#define VK_NV_glsl_shader 1 +#define VK_NV_GLSL_SHADER_SPEC_VERSION 1 +#define VK_NV_GLSL_SHADER_EXTENSION_NAME "VK_NV_glsl_shader" + + #ifdef __cplusplus } #endif diff --git a/ext/zlib/zlib.vcxproj b/ext/zlib/zlib.vcxproj index 9a194bdff4..30bcd6ee0f 100644 --- a/ext/zlib/zlib.vcxproj +++ b/ext/zlib/zlib.vcxproj @@ -76,7 +76,6 @@ StaticLibrary false - false Unicode v140_xp @@ -183,6 +182,7 @@ true false MultiThreaded + true Windows @@ -194,4 +194,4 @@ - \ No newline at end of file + diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 36c8ffa865..a0a56ac585 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -25,9 +25,7 @@ #include "Compare.h" #include "StubHost.h" #ifdef _WIN32 -#include "Windows/GPU/WindowsGLContext.h" #include "WindowsHeadlessHost.h" -#include "WindowsHeadlessHostDx9.h" #endif // https://github.com/richq/android-ndk-profiler @@ -71,6 +69,7 @@ struct InputState; void D3D9_SwapBuffers() { } void GL_SwapBuffers() { } void GL_SwapInterval(int) { } +void Vulkan_SwapBuffers() {} void NativeUpdate(InputState &input_state) { } void NativeRender(GraphicsContext *graphicsContext) { } void NativeResized() { } @@ -119,10 +118,6 @@ static HeadlessHost *getHost(GPUCore gpuCore) { switch (gpuCore) { case GPU_NULL: return new HeadlessHost(); -#ifdef _WIN32 - case GPU_DIRECTX9: - return new WindowsHeadlessHostDx9(); -#endif #ifdef HEADLESSHOST_CLASS default: return new HEADLESSHOST_CLASS(); @@ -257,6 +252,8 @@ int main(int argc, const char* argv[]) gpuCore = GPU_SOFTWARE; else if (!strcasecmp(gpuName, "directx9")) gpuCore = GPU_DIRECTX9; + else if (!strcasecmp(gpuName, "vulkan")) + gpuCore = GPU_VULKAN; else if (!strcasecmp(gpuName, "null")) gpuCore = GPU_NULL; else @@ -294,10 +291,10 @@ int main(int argc, const char* argv[]) return printUsage(argv[0], argc <= 1 ? NULL : "No executables specified"); HeadlessHost *headlessHost = getHost(gpuCore); + headlessHost->SetGraphicsCore(gpuCore); host = headlessHost; std::string error_string; - GraphicsContext *graphicsContext; bool glWorking = host->InitGraphics(&error_string, &graphicsContext); @@ -340,7 +337,7 @@ int main(int argc, const char* argv[]) #ifdef USING_GLES2 g_Config.iAnisotropyLevel = 0; #else - g_Config.iAnisotropyLevel = 8; + g_Config.iAnisotropyLevel = 4; #endif g_Config.bVertexCache = true; g_Config.bTrueColor = true; diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 0ed50f1a78..c1ae2d41fa 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -47,7 +47,6 @@ Application false - false Unicode v140_xp @@ -203,6 +202,7 @@ true false MultiThreaded + true Console @@ -225,6 +225,10 @@ + + + + NotUsing @@ -233,7 +237,6 @@ NotUsing - @@ -246,6 +249,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} @@ -264,7 +270,6 @@ - diff --git a/headless/Headless.vcxproj.filters b/headless/Headless.vcxproj.filters index fd3ee83d54..d699015802 100644 --- a/headless/Headless.vcxproj.filters +++ b/headless/Headless.vcxproj.filters @@ -2,11 +2,24 @@ - - + + Windows + + + Windows + + + Windows + + + Windows + + + Windows + @@ -14,9 +27,15 @@ - - + + Windows + + + + + {28215e85-3e11-4a8a-8b4d-3e355b85a542} + \ No newline at end of file diff --git a/headless/StubHost.h b/headless/StubHost.h index d12ca57099..78e9b1a15f 100644 --- a/headless/StubHost.h +++ b/headless/StubHost.h @@ -17,6 +17,7 @@ #pragma once +#include "Core/CoreParameter.h" #include "Core/Host.h" #include "Core/Debugger/SymbolMap.h" @@ -30,6 +31,7 @@ public: void SetDebugMode(bool mode) { } + void SetGraphicsCore(GPUCore core) { gpuCore_ = core; } bool InitGraphics(std::string *error_message, GraphicsContext **ctx) override {return false;} void ShutdownGraphics() override {} @@ -70,4 +72,5 @@ public: protected: std::string debugOutputBuffer_; + GPUCore gpuCore_; }; \ No newline at end of file diff --git a/headless/WindowsHeadlessHost.cpp b/headless/WindowsHeadlessHost.cpp index e2e776f21c..55a9b39de5 100644 --- a/headless/WindowsHeadlessHost.cpp +++ b/headless/WindowsHeadlessHost.cpp @@ -28,6 +28,8 @@ #include "GPU/Common/GPUDebugInterface.h" #include "GPU/GPUState.h" #include "Windows/GPU/WindowsGLContext.h" +#include "Windows/GPU/D3D9Context.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "base/logging.h" #include "gfx/gl_common.h" @@ -141,79 +143,68 @@ void WindowsHeadlessHost::SetComparisonScreenshot(const std::string &filename) comparisonScreenshot = filename; } -bool WindowsHeadlessHost::InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) -{ +bool WindowsHeadlessHost::InitGraphics(std::string *error_message, GraphicsContext **ctx) { hWnd = CreateHiddenWindow(); - if (WINDOW_VISIBLE) - { + if (WINDOW_VISIBLE) { ShowWindow(hWnd, TRUE); SetFocus(hWnd); } - int pixelFormat; + WindowsGraphicsContext *graphicsContext = nullptr; + switch (gpuCore_) { + case GPU_NULL: + case GPU_GLES: + case GPU_SOFTWARE: + graphicsContext = new WindowsGLContext(); + break; - static PIXELFORMATDESCRIPTOR pfd = {0}; - pfd.nSize = sizeof(pfd); - pfd.nVersion = 1; - pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; - pfd.iPixelType = PFD_TYPE_RGBA; - pfd.cColorBits = 32; - pfd.cDepthBits = 16; - pfd.iLayerType = PFD_MAIN_PLANE; + case GPU_DIRECTX9: + graphicsContext = new D3D9Context(); + break; -#define ENFORCE(x, msg) { if (!(x)) { fprintf(stderr, msg); *error_message = msg; return false; } } + case GPU_DIRECTX11: + return false; - ENFORCE(hDC = GetDC(hWnd), "Unable to create DC."); - ENFORCE(pixelFormat = ChoosePixelFormat(hDC, &pfd), "Unable to match pixel format."); - ENFORCE(SetPixelFormat(hDC, pixelFormat, &pfd), "Unable to set pixel format."); - ENFORCE(hRC = wglCreateContext(hDC), "Unable to create GL context."); - ENFORCE(wglMakeCurrent(hDC, hRC), "Unable to activate GL context."); + case GPU_VULKAN: + graphicsContext = new WindowsVulkanContext(); + break; + } - // GL_SwapInterval(0); + if (graphicsContext->Init(NULL, hWnd, error_message)) { + *ctx = graphicsContext; + gfx_ = graphicsContext; + } else { + delete graphicsContext; + *ctx = nullptr; + gfx_ = nullptr; + return false; + } - glewInit(); - CheckGLExtensions(); + if (gpuCore_ == GPU_GLES) { + // TODO: Do we need to do this here? + CheckGLExtensions(); + } LoadNativeAssets(); - *graphicsContext = new DummyGraphicsContext(); - return ResizeGL(); + return true; } -void WindowsHeadlessHost::ShutdownGraphics() -{ - if (hRC) { - wglMakeCurrent(NULL, NULL); - wglDeleteContext(hRC); - hRC = NULL; - } - - if (hDC) - ReleaseDC(hWnd, hDC); - hDC = NULL; +void WindowsHeadlessHost::ShutdownGraphics() { + gfx_->Shutdown(); + delete gfx_; + gfx_ = nullptr; DestroyWindow(hWnd); hWnd = NULL; } -bool WindowsHeadlessHost::ResizeGL() -{ - if (!hWnd) - return false; - - RECT rc; - GetWindowRect(hWnd, &rc); - - glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0.0f, WINDOW_WIDTH, WINDOW_HEIGHT, 0.0f, -1.0f, 1.0f); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - return true; -} - -void WindowsHeadlessHost::SwapBuffers() -{ - ::SwapBuffers(hDC); +void WindowsHeadlessHost::SwapBuffers() { + if (gpuCore_ == GPU_DIRECTX9) { + MSG msg; + PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); + TranslateMessage(&msg); + DispatchMessage(&msg); + } + gfx_->SwapBuffers(); } diff --git a/headless/WindowsHeadlessHost.h b/headless/WindowsHeadlessHost.h index 7e968fb9fb..088e7935da 100644 --- a/headless/WindowsHeadlessHost.h +++ b/headless/WindowsHeadlessHost.h @@ -38,12 +38,12 @@ public: virtual void SetComparisonScreenshot(const std::string &filename) override; protected: - virtual bool ResizeGL(); void LoadNativeAssets(); void SendOrCollectDebugOutput(const std::string &output); HWND hWnd; HDC hDC; HGLRC hRC; + GraphicsContext *gfx_; std::string comparisonScreenshot; }; \ No newline at end of file diff --git a/headless/WindowsHeadlessHostDx9.cpp b/headless/WindowsHeadlessHostDx9.cpp deleted file mode 100644 index b110d69a7a..0000000000 --- a/headless/WindowsHeadlessHostDx9.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2012- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#include "WindowsHeadlessHostDx9.h" -#include "Compare.h" - -#include -#include "Common/CommonWindows.h" -#include - -#include "base/logging.h" -#include "thin3d/d3dx9_loader.h" -#include "GPU/Directx9/helper/global.h" -#include "GPU/Directx9/helper/dx_fbo.h" -#include "file/vfs.h" -#include "file/zip_read.h" - -const bool WINDOW_VISIBLE = false; -const int WINDOW_WIDTH = 480; -const int WINDOW_HEIGHT = 272; - -HWND DxCreateWindow() { - static WNDCLASSEX wndClass = { - sizeof(WNDCLASSEX), - CS_HREDRAW | CS_VREDRAW | CS_OWNDC, - DefWindowProc, - 0, - 0, - NULL, - NULL, - LoadCursor(NULL, IDC_ARROW), - (HBRUSH) GetStockObject(BLACK_BRUSH), - NULL, - _T("PPSSPPHeadless"), - NULL, - }; - RegisterClassEx(&wndClass); - - RECT wr = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}; // set the size, but not the position - AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size - - DWORD style = WS_OVERLAPPEDWINDOW | (WINDOW_VISIBLE ? WS_VISIBLE : 0); - return CreateWindowEx(0, _T("PPSSPPHeadless"), _T("PPSSPPHeadless"), style, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, NULL, NULL, NULL, NULL); -} - -bool WindowsHeadlessHostDx9::InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) { - *graphicsContext = nullptr; - LoadD3DX9Dynamic(); - hWnd = DxCreateWindow(); - - if (WINDOW_VISIBLE) { - ShowWindow(hWnd, TRUE); - SetFocus(hWnd); - } - - DX9::DirectxInit(hWnd); - - LoadNativeAssets(); - - DX9::pD3Ddevice->BeginScene(); - - return true; -} - -void WindowsHeadlessHostDx9::ShutdownGraphics() { - DX9::DestroyShaders(); - DX9::fbo_shutdown(); - DX9::pD3Ddevice->EndScene(); - DX9::pD3Ddevice->Release(); - DX9::pD3Ddevice = NULL; - hWnd = NULL; -} - -bool WindowsHeadlessHostDx9::ResizeGL() { - return true; -} - -void WindowsHeadlessHostDx9::SwapBuffers() { - MSG msg; - PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - TranslateMessage(&msg); - DispatchMessage(&msg); - - DX9::pD3Ddevice->EndScene(); - DX9::pD3Ddevice->Present(0, 0, 0, 0); - DX9::pD3Ddevice->BeginScene(); -} diff --git a/unittest/UnitTest.cpp b/unittest/UnitTest.cpp index e020d61191..3c8d6ccd40 100644 --- a/unittest/UnitTest.cpp +++ b/unittest/UnitTest.cpp @@ -54,6 +54,7 @@ std::string System_GetProperty(SystemProperty prop) { return ""; } int System_GetPropertyInt(SystemProperty prop) { return -1; } void NativeMessageReceived(const char *message, const char *value) {} void GL_SwapInterval(int) {} +void Vulkan_SwapBuffers() {} #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index 9f396c145a..0ea78b3d12 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -48,7 +48,6 @@ Application false v140_xp - false Unicode @@ -88,8 +87,8 @@ Level3 - _CRTDBG_MAP_ALLOC;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + _CRTDBG_MAP_ALLOC;USING_WIN_UI;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib true false false @@ -111,7 +110,7 @@ Level3 _CRTDBG_MAP_ALLOC;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_64=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib true false false @@ -137,7 +136,7 @@ true true USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib false Speed true @@ -163,11 +162,12 @@ true true USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_ARCH_64=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib false true false MultiThreaded + true Console @@ -195,6 +195,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} @@ -219,4 +222,4 @@ - \ No newline at end of file +