CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/GPU/D3D11/DrawEngineD3D11.cpp
Views: 1401
// Copyright (c) 2012- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <algorithm>1819#include "Common/Log.h"20#include "Common/MemoryUtil.h"21#include "Common/TimeUtil.h"22#include "Common/Profiler/Profiler.h"2324#include "Core/MemMap.h"25#include "Core/System.h"26#include "Core/Config.h"27#include "Core/CoreTiming.h"2829#include "GPU/Math3D.h"30#include "GPU/GPUState.h"31#include "GPU/ge_constants.h"3233#include "GPU/Common/TextureDecoder.h"34#include "GPU/Common/SplineCommon.h"35#include "GPU/Common/TransformCommon.h"36#include "GPU/Common/VertexDecoderCommon.h"37#include "GPU/Common/SoftwareTransformCommon.h"38#include "GPU/Debugger/Debugger.h"39#include "GPU/D3D11/FramebufferManagerD3D11.h"40#include "GPU/D3D11/TextureCacheD3D11.h"41#include "GPU/D3D11/DrawEngineD3D11.h"42#include "GPU/D3D11/ShaderManagerD3D11.h"43#include "GPU/D3D11/GPU_D3D11.h"4445const D3D11_PRIMITIVE_TOPOLOGY d3d11prim[8] = {46D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // Points are expanded to triangles.47D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // Lines are expanded to triangles too.48D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // Lines are expanded to triangles too.49D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST,50D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,51D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // Fans not supported52D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // Need expansion - though we could do it with geom shaders in most cases53};5455enum {56VERTEX_PUSH_SIZE = 1024 * 1024 * 16,57INDEX_PUSH_SIZE = 1024 * 1024 * 4,58};5960static const D3D11_INPUT_ELEMENT_DESC TransformedVertexElements[] = {61{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, offsetof(TransformedVertex, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },62{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(TransformedVertex, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },63{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, offsetof(TransformedVertex, color0), D3D11_INPUT_PER_VERTEX_DATA, 0 },64{ "COLOR", 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0, offsetof(TransformedVertex, color1), D3D11_INPUT_PER_VERTEX_DATA, 0 },65{ "NORMAL", 0, DXGI_FORMAT_R32_FLOAT, 0, offsetof(TransformedVertex, fog), D3D11_INPUT_PER_VERTEX_DATA, 0 },66};6768DrawEngineD3D11::DrawEngineD3D11(Draw::DrawContext *draw, ID3D11Device *device, ID3D11DeviceContext *context)69: draw_(draw),70device_(device),71context_(context),72inputLayoutMap_(32),73blendCache_(32),74blendCache1_(32),75depthStencilCache_(64),76rasterCache_(4) {77device1_ = (ID3D11Device1 *)draw->GetNativeObject(Draw::NativeObject::DEVICE_EX);78context1_ = (ID3D11DeviceContext1 *)draw->GetNativeObject(Draw::NativeObject::CONTEXT_EX);79decOptions_.expandAllWeightsToFloat = true;80decOptions_.expand8BitNormalsToFloat = true;8182// Allocate nicely aligned memory. Maybe graphics drivers will83// appreciate it.84// All this is a LOT of memory, need to see if we can cut down somehow.85indexGen.Setup(decIndex_);8687InitDeviceObjects();8889// Vertex pushing buffers. For uniforms we use short DISCARD buffers, but we could use90// this kind of buffer there as well with D3D11.1. We might be able to use the same buffer91// for both vertices and indices, and possibly all three data types.92}9394DrawEngineD3D11::~DrawEngineD3D11() {95DestroyDeviceObjects();96}9798void DrawEngineD3D11::InitDeviceObjects() {99pushVerts_ = new PushBufferD3D11(device_, VERTEX_PUSH_SIZE, D3D11_BIND_VERTEX_BUFFER);100pushInds_ = new PushBufferD3D11(device_, INDEX_PUSH_SIZE, D3D11_BIND_INDEX_BUFFER);101102tessDataTransferD3D11 = new TessellationDataTransferD3D11(context_, device_);103tessDataTransfer = tessDataTransferD3D11;104105draw_->SetInvalidationCallback(std::bind(&DrawEngineD3D11::Invalidate, this, std::placeholders::_1));106}107108void DrawEngineD3D11::ClearInputLayoutMap() {109inputLayoutMap_.Iterate([&](const InputLayoutKey &key, ID3D11InputLayout *il) {110if (il)111il->Release();112});113inputLayoutMap_.Clear();114}115116void DrawEngineD3D11::NotifyConfigChanged() {117DrawEngineCommon::NotifyConfigChanged();118ClearInputLayoutMap();119}120121void DrawEngineD3D11::DestroyDeviceObjects() {122if (draw_) {123draw_->SetInvalidationCallback(InvalidationCallback());124}125126ClearTrackedVertexArrays();127ClearInputLayoutMap();128delete tessDataTransferD3D11;129tessDataTransferD3D11 = nullptr;130tessDataTransfer = nullptr;131delete pushVerts_;132delete pushInds_;133depthStencilCache_.Iterate([&](const uint64_t &key, ID3D11DepthStencilState *ds) {134ds->Release();135});136depthStencilCache_.Clear();137blendCache_.Iterate([&](const uint64_t &key, ID3D11BlendState *bs) {138bs->Release();139});140blendCache_.Clear();141blendCache1_.Iterate([&](const uint64_t &key, ID3D11BlendState1 *bs) {142bs->Release();143});144blendCache1_.Clear();145rasterCache_.Iterate([&](const uint32_t &key, ID3D11RasterizerState *rs) {146rs->Release();147});148rasterCache_.Clear();149}150151struct DeclTypeInfo {152DXGI_FORMAT type;153const char * name;154};155156static const DeclTypeInfo VComp[] = {157{ DXGI_FORMAT_UNKNOWN, "NULL" }, // DEC_NONE,158{ DXGI_FORMAT_R32_FLOAT, "D3DDECLTYPE_FLOAT1 " }, // DEC_FLOAT_1,159{ DXGI_FORMAT_R32G32_FLOAT, "D3DDECLTYPE_FLOAT2 " }, // DEC_FLOAT_2,160{ DXGI_FORMAT_R32G32B32_FLOAT, "D3DDECLTYPE_FLOAT3 " }, // DEC_FLOAT_3,161{ DXGI_FORMAT_R32G32B32A32_FLOAT, "D3DDECLTYPE_FLOAT4 " }, // DEC_FLOAT_4,162163{ DXGI_FORMAT_R8G8B8A8_SNORM, "UNUSED" }, // DEC_S8_3,164165{ DXGI_FORMAT_R16G16B16A16_SNORM, "D3DDECLTYPE_SHORT4N " }, // DEC_S16_3,166{ DXGI_FORMAT_R8G8B8A8_UNORM, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_1,167{ DXGI_FORMAT_R8G8B8A8_UNORM, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_2,168{ DXGI_FORMAT_R8G8B8A8_UNORM, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_3,169{ DXGI_FORMAT_R8G8B8A8_UNORM, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_4,170171{ DXGI_FORMAT_UNKNOWN, "UNUSED_DEC_U16_1" }, // DEC_U16_1,172{ DXGI_FORMAT_UNKNOWN, "UNUSED_DEC_U16_2" }, // DEC_U16_2,173{ DXGI_FORMAT_R16G16B16A16_UNORM ,"D3DDECLTYPE_USHORT4N "}, // DEC_U16_3,174{ DXGI_FORMAT_R16G16B16A16_UNORM ,"D3DDECLTYPE_USHORT4N "}, // DEC_U16_4,175};176177static void VertexAttribSetup(D3D11_INPUT_ELEMENT_DESC * VertexElement, u8 fmt, u8 offset, const char *semantic, u8 semantic_index = 0) {178memset(VertexElement, 0, sizeof(D3D11_INPUT_ELEMENT_DESC));179VertexElement->AlignedByteOffset = offset;180VertexElement->Format = VComp[fmt].type;181VertexElement->SemanticName = semantic;182VertexElement->SemanticIndex = semantic_index;183}184185ID3D11InputLayout *DrawEngineD3D11::SetupDecFmtForDraw(D3D11VertexShader *vshader, const DecVtxFormat &decFmt, u32 pspFmt) {186// TODO: Instead of one for each vshader, we can reduce it to one for each type of shader187// that reads TEXCOORD or not, etc. Not sure if worth it.188const InputLayoutKey key{ vshader, decFmt.id };189ID3D11InputLayout *inputLayout;190if (inputLayoutMap_.Get(key, &inputLayout)) {191return inputLayout;192} else {193D3D11_INPUT_ELEMENT_DESC VertexElements[8];194D3D11_INPUT_ELEMENT_DESC *VertexElement = &VertexElements[0];195196// Vertices Elements orders197// WEIGHT198if (decFmt.w0fmt != 0) {199VertexAttribSetup(VertexElement, decFmt.w0fmt, decFmt.w0off, "TEXCOORD", 1);200VertexElement++;201}202203if (decFmt.w1fmt != 0) {204VertexAttribSetup(VertexElement, decFmt.w1fmt, decFmt.w1off, "TEXCOORD", 2);205VertexElement++;206}207208// TC209if (decFmt.uvfmt != 0) {210VertexAttribSetup(VertexElement, decFmt.uvfmt, decFmt.uvoff, "TEXCOORD", 0);211VertexElement++;212}213214// COLOR215if (decFmt.c0fmt != 0) {216VertexAttribSetup(VertexElement, decFmt.c0fmt, decFmt.c0off, "COLOR", 0);217VertexElement++;218}219// Never used ?220if (decFmt.c1fmt != 0) {221VertexAttribSetup(VertexElement, decFmt.c1fmt, decFmt.c1off, "COLOR", 1);222VertexElement++;223}224225// NORMAL226if (decFmt.nrmfmt != 0) {227VertexAttribSetup(VertexElement, decFmt.nrmfmt, decFmt.nrmoff, "NORMAL", 0);228VertexElement++;229}230231// POSITION232// Always233VertexAttribSetup(VertexElement, DecVtxFormat::PosFmt(), decFmt.posoff, "POSITION", 0);234VertexElement++;235236// Create declaration237HRESULT hr = device_->CreateInputLayout(VertexElements, VertexElement - VertexElements, vshader->bytecode().data(), vshader->bytecode().size(), &inputLayout);238if (FAILED(hr)) {239ERROR_LOG(Log::G3D, "Failed to create input layout!");240inputLayout = nullptr;241}242243// Add it to map244inputLayoutMap_.Insert(key, inputLayout);245return inputLayout;246}247}248249void DrawEngineD3D11::BeginFrame() {250pushVerts_->Reset();251pushInds_->Reset();252253lastRenderStepId_ = -1;254}255256// In D3D, we're synchronous and state carries over so all we reset here on a new step is the viewport/scissor.257void DrawEngineD3D11::Invalidate(InvalidationCallbackFlags flags) {258if (flags & InvalidationCallbackFlags::RENDER_PASS_STATE) {259gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);260}261}262263// The inline wrapper in the header checks for numDrawCalls_ == 0264void DrawEngineD3D11::DoFlush() {265bool textureNeedsApply = false;266if (gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS) && !gstate.isModeClear() && gstate.isTextureMapEnabled()) {267textureCache_->SetTexture();268gstate_c.Clean(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);269textureNeedsApply = true;270} else if (gstate.getTextureAddress(0) == (gstate.getFrameBufRawAddress() | 0x04000000)) {271// This catches the case of clearing a texture. (#10957)272gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);273}274275// This is not done on every drawcall, we collect vertex data276// until critical state changes. That's when we draw (flush).277278GEPrimitiveType prim = prevPrim_;279280// Always use software for flat shading to fix the provoking index.281bool tess = gstate_c.submitType == SubmitType::HW_BEZIER || gstate_c.submitType == SubmitType::HW_SPLINE;282bool useHWTransform = CanUseHardwareTransform(prim) && (tess || gstate.getShadeMode() != GE_SHADE_FLAT);283284if (useHWTransform) {285ID3D11Buffer *vb_ = nullptr;286ID3D11Buffer *ib_ = nullptr;287288int vertexCount;289int maxIndex;290bool useElements;291DecodeVerts(decoded_);292DecodeIndsAndGetData(&prim, &vertexCount, &maxIndex, &useElements, false);293gpuStats.numUncachedVertsDrawn += vertexCount;294295bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE;296if (gstate.isModeThrough()) {297gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255);298} else {299gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255);300}301302if (textureNeedsApply) {303textureCache_->ApplyTexture();304}305306// Need to ApplyDrawState after ApplyTexture because depal can launch a render pass and that wrecks the state.307ApplyDrawState(prim);308ApplyDrawStateLate(true, dynState_.stencilRef);309310D3D11VertexShader *vshader;311D3D11FragmentShader *fshader;312shaderManager_->GetShaders(prim, dec_, &vshader, &fshader, pipelineState_, useHWTransform, useHWTessellation_, decOptions_.expandAllWeightsToFloat, decOptions_.applySkinInDecode);313ID3D11InputLayout *inputLayout = SetupDecFmtForDraw(vshader, dec_->GetDecVtxFmt(), dec_->VertexType());314context_->PSSetShader(fshader->GetShader(), nullptr, 0);315context_->VSSetShader(vshader->GetShader(), nullptr, 0);316shaderManager_->UpdateUniforms(framebufferManager_->UseBufferedRendering());317shaderManager_->BindUniforms();318319context_->IASetInputLayout(inputLayout);320UINT stride = dec_->GetDecVtxFmt().stride;321context_->IASetPrimitiveTopology(d3d11prim[prim]);322323if (!vb_) {324// Push!325UINT vOffset;326int vSize = numDecodedVerts_ * dec_->GetDecVtxFmt().stride;327uint8_t *vptr = pushVerts_->BeginPush(context_, &vOffset, vSize);328memcpy(vptr, decoded_, vSize);329pushVerts_->EndPush(context_);330ID3D11Buffer *buf = pushVerts_->Buf();331context_->IASetVertexBuffers(0, 1, &buf, &stride, &vOffset);332if (useElements) {333UINT iOffset;334int iSize = 2 * vertexCount;335uint8_t *iptr = pushInds_->BeginPush(context_, &iOffset, iSize);336memcpy(iptr, decIndex_, iSize);337pushInds_->EndPush(context_);338context_->IASetIndexBuffer(pushInds_->Buf(), DXGI_FORMAT_R16_UINT, iOffset);339context_->DrawIndexed(vertexCount, 0, 0);340} else {341context_->Draw(vertexCount, 0);342}343} else {344UINT offset = 0;345context_->IASetVertexBuffers(0, 1, &vb_, &stride, &offset);346if (useElements) {347context_->IASetIndexBuffer(ib_, DXGI_FORMAT_R16_UINT, 0);348context_->DrawIndexed(vertexCount, 0, 0);349} else {350context_->Draw(vertexCount, 0);351}352}353} else {354PROFILE_THIS_SCOPE("soft");355if (!decOptions_.applySkinInDecode) {356decOptions_.applySkinInDecode = true;357lastVType_ |= (1 << 26);358dec_ = GetVertexDecoder(lastVType_);359}360DecodeVerts(decoded_);361int vertexCount = DecodeInds();362363bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE;364if (gstate.isModeThrough()) {365gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255);366} else {367gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255);368}369370gpuStats.numUncachedVertsDrawn += vertexCount;371prim = IndexGenerator::GeneralPrim((GEPrimitiveType)drawInds_[0].prim);372VERBOSE_LOG(Log::G3D, "Flush prim %i SW! %i verts in one go", prim, vertexCount);373374u16 *inds = decIndex_;375SoftwareTransformResult result{};376SoftwareTransformParams params{};377params.decoded = decoded_;378params.transformed = transformed_;379params.transformedExpanded = transformedExpanded_;380params.fbman = framebufferManager_;381params.texCache = textureCache_;382params.allowClear = true;383params.allowSeparateAlphaClear = false; // D3D11 doesn't support separate alpha clears384params.flippedY = false;385params.usesHalfZ = true;386387if (gstate.getShadeMode() == GE_SHADE_FLAT) {388// We need to rotate the index buffer to simulate a different provoking vertex.389// We do this before line expansion etc.390IndexBufferProvokingLastToFirst(prim, inds, vertexCount);391}392393// We need correct viewport values in gstate_c already.394if (gstate_c.IsDirty(DIRTY_VIEWPORTSCISSOR_STATE)) {395ViewportAndScissor vpAndScissor;396ConvertViewportAndScissor(framebufferManager_->UseBufferedRendering(),397framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(),398framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(),399vpAndScissor);400UpdateCachedViewportState(vpAndScissor);401}402403SoftwareTransform swTransform(params);404405const Lin::Vec3 trans(gstate_c.vpXOffset, -gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f);406const Lin::Vec3 scale(gstate_c.vpWidthScale, -gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f);407swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight < 0, trans, scale);408409swTransform.Transform(prim, dec_->VertexType(), dec_->GetDecVtxFmt(), numDecodedVerts_, &result);410// Non-zero depth clears are unusual, but some drivers don't match drawn depth values to cleared values.411// Games sometimes expect exact matches (see #12626, for example) for equal comparisons.412if (result.action == SW_CLEAR && everUsedEqualDepth_ && gstate.isClearModeDepthMask() && result.depth > 0.0f && result.depth < 1.0f)413result.action = SW_NOT_READY;414415if (textureNeedsApply) {416gstate_c.pixelMapped = result.pixelMapped;417textureCache_->ApplyTexture();418gstate_c.pixelMapped = false;419}420421// Need to ApplyDrawState after ApplyTexture because depal can launch a render pass and that wrecks the state.422ApplyDrawState(prim);423424if (result.action == SW_NOT_READY)425swTransform.BuildDrawingParams(prim, vertexCount, dec_->VertexType(), inds, RemainingIndices(inds), numDecodedVerts_, VERTEX_BUFFER_MAX, &result);426if (result.setSafeSize)427framebufferManager_->SetSafeSize(result.safeWidth, result.safeHeight);428429ApplyDrawStateLate(result.setStencil, result.stencilValue);430431if (result.action == SW_DRAW_INDEXED) {432D3D11VertexShader *vshader;433D3D11FragmentShader *fshader;434shaderManager_->GetShaders(prim, dec_, &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat, true);435context_->PSSetShader(fshader->GetShader(), nullptr, 0);436context_->VSSetShader(vshader->GetShader(), nullptr, 0);437shaderManager_->UpdateUniforms(framebufferManager_->UseBufferedRendering());438shaderManager_->BindUniforms();439440// We really do need a vertex layout for each vertex shader (or at least check its ID bits for what inputs it uses)!441// Some vertex shaders ignore one of the inputs, and then the layout created from it will lack it, which will be a problem for others.442InputLayoutKey key{ vshader, 0xFFFFFFFF }; // Let's use 0xFFFFFFFF to signify TransformedVertex443ID3D11InputLayout *layout;444if (!inputLayoutMap_.Get(key, &layout)) {445ASSERT_SUCCESS(device_->CreateInputLayout(TransformedVertexElements, ARRAY_SIZE(TransformedVertexElements), vshader->bytecode().data(), vshader->bytecode().size(), &layout));446inputLayoutMap_.Insert(key, layout);447}448context_->IASetInputLayout(layout);449context_->IASetPrimitiveTopology(d3d11prim[prim]);450451UINT stride = sizeof(TransformedVertex);452UINT vOffset = 0;453int vSize = numDecodedVerts_ * stride;454uint8_t *vptr = pushVerts_->BeginPush(context_, &vOffset, vSize);455memcpy(vptr, result.drawBuffer, vSize);456pushVerts_->EndPush(context_);457ID3D11Buffer *buf = pushVerts_->Buf();458context_->IASetVertexBuffers(0, 1, &buf, &stride, &vOffset);459UINT iOffset;460int iSize = sizeof(uint16_t) * result.drawNumTrans;461uint8_t *iptr = pushInds_->BeginPush(context_, &iOffset, iSize);462memcpy(iptr, inds, iSize);463pushInds_->EndPush(context_);464context_->IASetIndexBuffer(pushInds_->Buf(), DXGI_FORMAT_R16_UINT, iOffset);465context_->DrawIndexed(result.drawNumTrans, 0, 0);466} else if (result.action == SW_CLEAR) {467u32 clearColor = result.color;468float clearDepth = result.depth;469470uint32_t clearFlag = 0;471472if (gstate.isClearModeColorMask()) clearFlag |= Draw::FBChannel::FB_COLOR_BIT;473if (gstate.isClearModeAlphaMask()) clearFlag |= Draw::FBChannel::FB_STENCIL_BIT;474if (gstate.isClearModeDepthMask()) clearFlag |= Draw::FBChannel::FB_DEPTH_BIT;475476if (clearFlag & Draw::FBChannel::FB_COLOR_BIT) {477framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason);478}479480uint8_t clearStencil = clearColor >> 24;481draw_->Clear(clearFlag, clearColor, clearDepth, clearStencil);482483if (gstate_c.Use(GPU_USE_CLEAR_RAM_HACK) && gstate.isClearModeColorMask() && (gstate.isClearModeAlphaMask() || gstate_c.framebufFormat == GE_FORMAT_565)) {484int scissorX1 = gstate.getScissorX1();485int scissorY1 = gstate.getScissorY1();486int scissorX2 = gstate.getScissorX2() + 1;487int scissorY2 = gstate.getScissorY2() + 1;488framebufferManager_->ApplyClearToMemory(scissorX1, scissorY1, scissorX2, scissorY2, clearColor);489}490}491decOptions_.applySkinInDecode = g_Config.bSoftwareSkinning;492}493494ResetAfterDrawInline();495framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason);496GPUDebug::NotifyDraw();497}498499TessellationDataTransferD3D11::TessellationDataTransferD3D11(ID3D11DeviceContext *context, ID3D11Device *device)500: context_(context), device_(device) {501desc.Usage = D3D11_USAGE_DYNAMIC;502desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;503desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;504desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;505}506507TessellationDataTransferD3D11::~TessellationDataTransferD3D11() {508for (int i = 0; i < 3; ++i) {509if (buf[i]) buf[i]->Release();510if (view[i]) view[i]->Release();511}512}513514template <typename T>515static void DoRelease(T *&ptr) {516if (ptr) {517ptr->Release();518ptr = nullptr;519}520}521522void TessellationDataTransferD3D11::SendDataToShader(const SimpleVertex *const *points, int size_u, int size_v, u32 vertType, const Spline::Weight2D &weights) {523struct TessData {524float pos[3]; float pad1;525float uv[2]; float pad2[2];526float color[4];527};528529int size = size_u * size_v;530531if (prevSize < size || !buf[0]) {532prevSize = size;533DoRelease(buf[0]);534DoRelease(view[0]);535536desc.ByteWidth = size * sizeof(TessData);537desc.StructureByteStride = sizeof(TessData);538device_->CreateBuffer(&desc, nullptr, &buf[0]);539if (buf[0])540device_->CreateShaderResourceView(buf[0], nullptr, &view[0]);541if (!buf[0] || !view[0])542return;543context_->VSSetShaderResources(0, 1, &view[0]);544}545D3D11_MAPPED_SUBRESOURCE map{};546HRESULT hr = context_->Map(buf[0], 0, D3D11_MAP_WRITE_DISCARD, 0, &map);547if (FAILED(hr))548return;549uint8_t *data = (uint8_t *)map.pData;550551float *pos = (float *)(data);552float *tex = (float *)(data + offsetof(TessData, uv));553float *col = (float *)(data + offsetof(TessData, color));554int stride = sizeof(TessData) / sizeof(float);555556CopyControlPoints(pos, tex, col, stride, stride, stride, points, size, vertType);557558context_->Unmap(buf[0], 0);559560using Spline::Weight;561562// Weights U563if (prevSizeWU < weights.size_u || !buf[1]) {564prevSizeWU = weights.size_u;565DoRelease(buf[1]);566DoRelease(view[1]);567568desc.ByteWidth = weights.size_u * sizeof(Weight);569desc.StructureByteStride = sizeof(Weight);570device_->CreateBuffer(&desc, nullptr, &buf[1]);571if (buf[1])572device_->CreateShaderResourceView(buf[1], nullptr, &view[1]);573if (!buf[1] || !view[1])574return;575context_->VSSetShaderResources(1, 1, &view[1]);576}577hr = context_->Map(buf[1], 0, D3D11_MAP_WRITE_DISCARD, 0, &map);578if (SUCCEEDED(hr))579memcpy(map.pData, weights.u, weights.size_u * sizeof(Weight));580context_->Unmap(buf[1], 0);581582// Weights V583if (prevSizeWV < weights.size_v) {584prevSizeWV = weights.size_v;585DoRelease(buf[2]);586DoRelease(view[2]);587588desc.ByteWidth = weights.size_v * sizeof(Weight);589desc.StructureByteStride = sizeof(Weight);590device_->CreateBuffer(&desc, nullptr, &buf[2]);591if (buf[2])592device_->CreateShaderResourceView(buf[2], nullptr, &view[2]);593if (!buf[2] || !view[2])594return;595context_->VSSetShaderResources(2, 1, &view[2]);596}597hr = context_->Map(buf[2], 0, D3D11_MAP_WRITE_DISCARD, 0, &map);598if (SUCCEEDED(hr))599memcpy(map.pData, weights.v, weights.size_v * sizeof(Weight));600context_->Unmap(buf[2], 0);601}602603604