DirectX 12 texture binding causes memcpy error

I have tried long and hard to solve this. So… I am contacting all of you guys! The issue is that each frame, I try and bind my texture:

Texture.hpp

class Texture : public Component
{
public:

    void Bind()
    {
        auto commandList = Renderer::GetInstance()->GetCommandList();

        UpdateSubresources(commandList.Get(), texture.Get(), textureUploadHeap.Get(), 0, 0, 1, &subresourceData);

        CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
        commandList->ResourceBarrier(1, &barrier);
    }

    void CleanUp() override
    {
        texture.Reset();
        textureUploadHeap.Reset();
    }

    ComPtr<ID3D12Resource> GetRaw()
    {
        return texture;
    }

    String GetName()
    {
        return name;
    }

    static Shared<Texture> Create(const String& name, const String& localPath, const String& domain = Settings::GetInstance()->Get<String>("defaultDomain"))
    {
        Shared<Texture> out = std::make_shared<Texture>();

        out->name = name;
        out->localPath = localPath;
        out->path = "Assets/" + domain + "/" + localPath;
        out->Generate();

        return out;
    }

private:

    void Generate()
    {
        ComPtr<IWICImagingFactory> factory;
        ComPtr<IWICBitmapDecoder> decoder;
        ComPtr<IWICBitmapFrameDecode> frame;
        ComPtr<IWICFormatConverter> converter;

        HRESULT result = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);

        if (FAILED(result))
            throw std::runtime_error("Failed to initialize COM library.");

        result = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory));

        if (FAILED(result))
            throw std::runtime_error("Failed to create WIC Imaging Factory.");

        result = factory->CreateDecoderFromFilename(WString(path.begin(), path.end()).c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &decoder);

        if (FAILED(result))
            throw std::runtime_error("Failed to load image.");

        result = decoder->GetFrame(0, &frame);

        if (FAILED(result))
            throw std::runtime_error("Failed to get image frame.");

        result = factory->CreateFormatConverter(&converter);

        if (FAILED(result))
            throw std::runtime_error("Failed to create WIC format converter.");

        result = converter->Initialize(frame.Get(), GUID_WICPixelFormat32bppRGBA, WICBitmapDitherTypeNone, nullptr, 0.0, WICBitmapPaletteTypeCustom);

        if (FAILED(result))
            throw std::runtime_error("Failed to initialize WIC format converter.");

        UINT width, height;

        result = converter->GetSize(&width, &height);

        if (FAILED(result))
            throw std::runtime_error("Failed to get image dimensions.");

        Vector<unsigned char> imageData(width * height * 4);

        result = converter->CopyPixels(nullptr, width * 4, static_cast<UINT>(imageData.size()), imageData.data());

        if (FAILED(result))
            throw std::runtime_error("Failed to copy image pixels.");

        auto device = Renderer::GetInstance()->GetDevice();

        D3D12_RESOURCE_DESC textureDescription = {};

        textureDescription.MipLevels = 1;
        textureDescription.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        textureDescription.Width = width;
        textureDescription.Height = height;
        textureDescription.Flags = D3D12_RESOURCE_FLAG_NONE;
        textureDescription.DepthOrArraySize = 1;
        textureDescription.SampleDesc.Count = 1;
        textureDescription.SampleDesc.Quality = 0;
        textureDescription.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

        CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT);

        result = device->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &textureDescription, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&texture));

        if (FAILED(result))
            throw std::runtime_error("Failed to create texture resource.");

        const UINT64 uploadBufferSize = GetRequiredIntermediateSize(texture.Get(), 0, 1);

        CD3DX12_HEAP_PROPERTIES uploadHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
        CD3DX12_RESOURCE_DESC bufferDescription = CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize);

        result = device->CreateCommittedResource(&uploadHeapProperties, D3D12_HEAP_FLAG_NONE, &bufferDescription, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&textureUploadHeap));

        if (FAILED(result))
            throw std::runtime_error("Failed to create texture upload heap.");

        D3D12_SUBRESOURCE_DATA textureData = {};

        textureData.pData = imageData.data();
        textureData.RowPitch = static_cast<LONG_PTR>(width) * 4;
        textureData.SlicePitch = textureData.RowPitch * height;

        subresourceData = textureData;
    }

    String name;
    String localPath;
    String path;

    ComPtr<ID3D12Resource> texture;
    ComPtr<ID3D12Resource> textureUploadHeap;

    D3D12_SUBRESOURCE_DATA subresourceData = {};
};

Texture#Bind() is called once per frame, before the shader is bound.
Texture#Create() is called before the mesh is even created, and is called once at the start of the program. It is not called for each mesh created (that would be very inefficient!)

Just to help you understand, here is my shader class:

Shader.hpp

class Shader : public Component
{
public:

    void Bind()
    {
        auto commandList = Renderer::GetInstance()->GetCommandList();

        if (rootSignature)
            commandList->SetGraphicsRootSignature(rootSignature.Get());

        if (pipelineState)
            commandList->SetPipelineState(pipelineState.Get());

        ID3D12DescriptorHeap* descriptorHeaps[] = { constantBufferViewShaderResourceViewUnorderedAccessViewHeap.Get(), samplerHeap.Get() };
        commandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);

        if (!constantBuffers.empty() && !constantBufferDatas.empty())
            commandList->SetGraphicsRootDescriptorTable(0, constantBufferViewShaderResourceViewUnorderedAccessViewHeap->GetGPUDescriptorHandleForHeapStart());

        if (!textures.empty())
            commandList->SetGraphicsRootDescriptorTable(1, samplerHeap->GetGPUDescriptorHandleForHeapStart());
    }

    void CreateConstantBuffer(UINT bufferSize, UINT bufferIndex)
    {
        if (bufferIndex >= constantBuffers.size())
            constantBuffers.resize(static_cast<std::vector<ComPtr<ID3D12Resource>, std::allocator<ComPtr<ID3D12Resource>>>::size_type>(bufferIndex) + 1);

        CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
        CD3DX12_RESOURCE_DESC bufferDescription = CD3DX12_RESOURCE_DESC::Buffer(bufferSize);

        HRESULT result = Renderer::GetInstance()->GetDevice()->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &bufferDescription, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constantBuffers[bufferIndex]));

        if (FAILED(result))
            Logger_ThrowError("D3D12", "Failed to create constant buffer", true);

        constantBuffers[bufferIndex]->Map(0, nullptr, reinterpret_cast<void**>(&constantBufferDatas[bufferIndex]));

        D3D12_CONSTANT_BUFFER_VIEW_DESC constantBufferViewDecription = {};

        constantBufferViewDecription.BufferLocation = constantBuffers[bufferIndex]->GetGPUVirtualAddress();
        constantBufferViewDecription.SizeInBytes = (bufferSize + 255) & ~255;

        CD3DX12_CPU_DESCRIPTOR_HANDLE constantBufferViewHandle(constantBufferViewShaderResourceViewUnorderedAccessViewHeap->GetCPUDescriptorHandleForHeapStart(), bufferIndex, constantBufferViewShaderResourceViewUnorderedAccessViewDescriptorSize);
        Renderer::GetInstance()->GetDevice()->CreateConstantBufferView(&constantBufferViewDecription, constantBufferViewHandle);
    }

    void UpdateConstantBuffer(const void* data, Size dataSize, UINT bufferIndex)
    {
        memcpy(constantBufferDatas[bufferIndex], data, dataSize);
    }

    void CreateTexture(ComPtr<ID3D12Resource> resource, UINT textureIndex)
    {
        if (textureIndex >= textures.size())
            textures.resize(static_cast<std::vector<ComPtr<ID3D12Resource>, std::allocator<ComPtr<ID3D12Resource>>>::size_type>(textureIndex) + 1);

        textures[textureIndex] = resource;

        D3D12_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDescription = {};

        shaderResourceViewDescription.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        shaderResourceViewDescription.Format = resource->GetDesc().Format;
        shaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
        shaderResourceViewDescription.Texture2D.MipLevels = resource->GetDesc().MipLevels;

        CD3DX12_CPU_DESCRIPTOR_HANDLE shaderResourceViewHandle(constantBufferViewShaderResourceViewUnorderedAccessViewHeap->GetCPUDescriptorHandleForHeapStart(), textureIndex + maxConstantBuffers, constantBufferViewShaderResourceViewUnorderedAccessViewDescriptorSize);
        Renderer::GetInstance()->GetDevice()->CreateShaderResourceView(resource.Get(), &shaderResourceViewDescription, shaderResourceViewHandle);
    }

    void CreateSampler(UINT samplerIndex)
    {
        if (samplerIndex >= samplers.size())
            samplers.resize(static_cast<std::vector<ComPtr<ID3D12Resource>, std::allocator<ComPtr<ID3D12Resource>>>::size_type>(samplerIndex) + 1);

        D3D12_SAMPLER_DESC samplerDescription = {};

        samplerDescription.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
        samplerDescription.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDescription.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDescription.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDescription.MinLOD = 0;
        samplerDescription.MaxLOD = D3D12_FLOAT32_MAX;
        samplerDescription.MipLODBias = 0.0f;
        samplerDescription.MaxAnisotropy = 1;
        samplerDescription.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;

        CD3DX12_CPU_DESCRIPTOR_HANDLE samplerHandle(samplerHeap->GetCPUDescriptorHandleForHeapStart(), samplerIndex, samplerDescriptorSize);
        Renderer::GetInstance()->GetDevice()->CreateSampler(&samplerDescription, samplerHandle);
    }

    String GetName() const
    {
        return name;
    }

    String GetLocalPath() const
    {
        return localPath;
    }

    String GetDomain() const
    {
        return domain;
    }

    UnorderedMap<String, String> GetPaths() const
    {
        return
        {
            { "vertex", vertexPath },
            { "pixel", pixelPath },
            { "compute", computePath },
            { "geometry", geometryPath },
            { "hull", hullPath },
            { "domain", domainPath }
        };
    }

    ComPtr<ID3D12RootSignature> GetRootSignature() const
    {
        return rootSignature;
    }

    ComPtr<ID3D12PipelineState> GetPipelineState() const
    {
        return pipelineState;
    }

    void CleanUp()
    {
        for (auto& buffer : constantBuffers)
        {
            if (buffer)
                buffer->Unmap(0, nullptr);
        }
    }

    static Shared<Shader> Create(const String& name, const String& localPath, Shared<RootSignature> rootSignature, const String& domain = Settings::GetInstance()->Get<String>("defaultDomain"))
    {
        Shared<Shader> out = std::make_shared<Shader>();

        out->name = name;
        out->localPath = localPath;
        out->domain = domain;
        out->vertexPath = "Assets/" + domain + "/" + localPath + "Vertex.hlsl";
        out->pixelPath = "Assets/" + domain + "/" + localPath + "Pixel.hlsl";
        out->computePath = "Assets/" + domain + "/" + localPath + "Compute.hlsl";
        out->geometryPath = "Assets/" + domain + "/" + localPath + "Geometry.hlsl";
        out->hullPath = "Assets/" + domain + "/" + localPath + "Hull.hlsl";
        out->domainPath = "Assets/" + domain + "/" + localPath + "Domain.hlsl";
        out->rootSignature = rootSignature->Generate();

        out->Generate();

        return std::move(out);
    }

private:

    void Generate()
    {
        //Just compiles shaders and creates the pso
    }

    void CreateDescriptorHeaps()
    {
        D3D12_DESCRIPTOR_HEAP_DESC constantBufferViewShaderResourceViewUnorderedAccessViewHeapDescription = {};

        constantBufferViewShaderResourceViewUnorderedAccessViewHeapDescription.NumDescriptors = maxConstantBuffers + maxTextures;
        constantBufferViewShaderResourceViewUnorderedAccessViewHeapDescription.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
        constantBufferViewShaderResourceViewUnorderedAccessViewHeapDescription.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;

        HRESULT result = Renderer::GetInstance()->GetDevice()->CreateDescriptorHeap(&constantBufferViewShaderResourceViewUnorderedAccessViewHeapDescription, IID_PPV_ARGS(&constantBufferViewShaderResourceViewUnorderedAccessViewHeap));

        if (FAILED(result))
            Logger_ThrowError("D3D12", "Failed to create CBV/SRV/UAV descriptor heap", true);

        constantBufferViewShaderResourceViewUnorderedAccessViewDescriptorSize = Renderer::GetInstance()->GetDevice()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);

        D3D12_DESCRIPTOR_HEAP_DESC samplerHeapDescription = {};

        samplerHeapDescription.NumDescriptors = maxTextures;
        samplerHeapDescription.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
        samplerHeapDescription.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;

        result = Renderer::GetInstance()->GetDevice()->CreateDescriptorHeap(&samplerHeapDescription, IID_PPV_ARGS(&samplerHeap));

        if (FAILED(result))
            Logger_ThrowError("D3D12", "Failed to create sampler descriptor heap", true);

        samplerDescriptorSize = Renderer::GetInstance()->GetDevice()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
    }

    ComPtr<IDxcBlob> CompileShader(ComPtr<IDxcUtils>& utils, ComPtr<IDxcCompiler3>& compiler, ComPtr<IDxcIncludeHandler>& includeHandler, const String& path, const wchar_t* target)
    {
        //Long and compilicated function...
    }

    void CreateGraphicsPipelineState(ComPtr<IDxcBlob>& vertexShaderBlob, ComPtr<IDxcBlob>& pixelShaderBlob, ComPtr<IDxcBlob>& geometryShaderBlob, ComPtr<IDxcBlob>& hullShaderBlob, ComPtr<IDxcBlob>& domainShaderBlob)
    {
        D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineStateDescription = {};

        pipelineStateDescription.VS = vertexShaderBlob ? D3D12_SHADER_BYTECODE{ vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() } : D3D12_SHADER_BYTECODE{};
        pipelineStateDescription.PS = pixelShaderBlob ? D3D12_SHADER_BYTECODE{ pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() } : D3D12_SHADER_BYTECODE{};
        pipelineStateDescription.GS = geometryShaderBlob ? D3D12_SHADER_BYTECODE{ geometryShaderBlob->GetBufferPointer(), geometryShaderBlob->GetBufferSize() } : D3D12_SHADER_BYTECODE{};
        pipelineStateDescription.HS = hullShaderBlob ? D3D12_SHADER_BYTECODE{ hullShaderBlob->GetBufferPointer(), hullShaderBlob->GetBufferSize() } : D3D12_SHADER_BYTECODE{};
        pipelineStateDescription.DS = domainShaderBlob ? D3D12_SHADER_BYTECODE{ domainShaderBlob->GetBufferPointer(), domainShaderBlob->GetBufferSize() } : D3D12_SHADER_BYTECODE{};

        pipelineStateDescription.pRootSignature = rootSignature.Get();
        pipelineStateDescription.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
        pipelineStateDescription.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
        pipelineStateDescription.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
        pipelineStateDescription.InputLayout = { Vertex::GetInputLayout().data(), (uint)Vertex::GetInputLayout().size() };
        pipelineStateDescription.SampleMask = UINT_MAX;
        pipelineStateDescription.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
        pipelineStateDescription.NumRenderTargets = 1;
        pipelineStateDescription.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
        pipelineStateDescription.DSVFormat = DXGI_FORMAT_D32_FLOAT;
        pipelineStateDescription.SampleDesc.Count = 1;

        HRESULT result = Renderer::GetInstance()->GetDevice()->CreateGraphicsPipelineState(&pipelineStateDescription, IID_PPV_ARGS(&pipelineState));

        if (FAILED(result))
            Logger_ThrowError("FAILED", "Failed to create graphics pipeline state", true);
    }

    //Member variables
};

And finally, the order in which operations are called:

void Render()
{
    if (!shader) //'shader' and 'texture' are both std::shared_ptr
        return;

    texture->Bind();
    shader->Bind();

    UINT stride = sizeof(Vertex);
    UINT offset = 0;

    ComPtr<ID3D12GraphicsCommandList> commandList = Renderer::GetInstance()->GetCommandList();

    commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
    commandList->IASetIndexBuffer(&indexBufferView);
    commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    commandList->DrawIndexedInstanced(static_cast<UINT>(indices.size()), 1, 0, 0, 0);
}

I have tried using ChatGPT, looking at Microsoft Learn, creating a Minimal Reproducible Example, but nothing really worked. I just cannot find the correct way to set a texture!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật