0
\$\begingroup\$

I'm trying to make a simple engine with DirectX where you can draw to the screen with a function Draw(x, y, r, g, b). The function sets the pixel at x,y to the color r,g,b. The engine has a parameter for the size of a pixel, making the engine capable of looking somewhat retro or low resolution. My question is in the title. I would like to take an array of color data and paste it into a Texture2D which will then be rendered to the screen, and I would be greatful if someone could point me in the right direction of how I could go about doing that in DirectX.

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

I'll answer my own question, cause I recently figured it out.

first you'll need the array of data to fill your texture with usually of type uint32_t:

uint32_t* colorBuffer;
m_colorBuffer = new uint32_t[CanvasWidth() * CanvasHeight()];
memset(m_colorBuffer, 0, sizeof(uint32_t) * CanvasWidth() * CanvasHeight());

for (int x = 0; x < TEXTUREWIDTH; x++) {
    for (int y = 0; y < TEXTUREHEIGHT; y++) {
        m_colorBuffer[x + y * CanvasWidth()] = (RED) | (GREEN << 8) | (BLUE << 16) | (ALPHA << 24); //R | G | B | A
    }
}

second you need a D3D11_SUBRESOURCE_DATA element to fill your texture with data.

D3D11_SUBRESOURCE_DATA subrecData;
subrecData.pSysMem = colorBuffer;
subrecData.SysMemPitch = TEXTUREWIDTH * sizeof(uint32_t);
subrecData.SysMemSlicePitch = 0;

and a D3D11_TEXTURE2D_DESC:

D3D11_TEXTURE2D_DESC desc;
desc.Width = TEXTUREWIDTH;
desc.Height = TEXTUREHEIGHT;
desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT; //or D3D11_USAGE_DYNAMIC for map/unmap
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0; // D3D11_CPU_ACCESS_WRITE for dynamic usage
desc.MiscFlags = 0;

then create the texture with your device:

ID3D11Texture2D* texture;
myDevice->CreateTexture2D(&desc, &subrecData, &texture);

lastly create a D3D11_SHADER_RESOURCE_VIEW_DESC and ID3D11ShaderResourceView:

D3D11_SHADER_RESOURCE_VIEW_DESC srvd;
srvd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvd.Texture2D.MipLevels = 1;
srvd.Texture2D.MostDetailedMip = 0;

ID3D11ShaderResourceView* shaderResourceView;
myDevice->CreateShaderResourceView(texture, &srvd, &shaderResourceView);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .