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
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
+