Updating only a portion of texture2d-data - possible?

Hello,

as we all know, we can set the pixels of a texture2d-object by calling .SetData<T>(...) and uploading an arbitrary array of pixel-data, let’s call it M.

Let’s say I want to modify four elements of array M (four because I want to modify a single pixel, i.e. four different channels r, g, b, a) beginning at index = x * 4 + y * 4 * Width.
Is it now possible to upload these 4 modified pixel-data only, beginning from index (x *4 + y * 4 * Width) up to (index + 4)?
Or do I have to upload the whole pixel-data-array (several thousands bytes) after each pixel-update?

Kind regards.

Check the other overloads of SetData. There’s one that takes a start index and a count, and another that takes a rectangle area to modify (though I’m not sure how that interacts with the start and count the same method also takes).

Check 'em out, maybe those will work for you :slight_smile:

Hello, yes, I already tried it out, but it didn’t work as planned.

My attempt was the following:

int index = x * 4 + y * 4 * Width;
data[index + 0] = b;
data[index + 1] = g;
data[index + 2] = r;
data[index + 3] = a;
tex.SetData<byte>(data, index, 4);

=> error,
then I tried:

int index = x * 4 + y * 4 * Width;
data[index + 0] = b;
data[index + 1] = g;
data[index + 2] = r;
data[index + 3] = a;
tex.SetData<byte>(data, index, index + 4);

=> error

elementCount is not the right size, elementCount * sizeof(T) is 4, but data size is 4342468. Arg_ParamName_Name"

In both cases, the count should be 4 (not index + 4) because you’re only modifying 4 bytes in the array. That said, I would expect the first example to work, that looks like what I would expect.

I’ve never used SetData with byte before though, only Color. I’ll try playing around with this and get back to you.

1 Like

Your data array is the same size as the texture. If you want to update only 4 bytes, then your data array should only be 4 bytes.

1 Like

Edit:

Thank God, got it working:

 public void SetPixel(int x, int y, Microsoft.Xna.Framework.Color color)
    {
        if (x < 0 || x >= Width)
            return;

        if (y < 0 || y >= Height)
            return;

        Microsoft.Xna.Framework.Color bgra = new Microsoft.Xna.Framework.Color(color.B, color.G, color.R, color.A);

        this.SetData<Microsoft.Xna.Framework.Color>(
            0, 
            new Microsoft.Xna.Framework.Rectangle(x, y, 1, 1), 
            new Microsoft.Xna.Framework.Color[] { bgra }, 
            0, 
            1);
    }

Source: https://social.msdn.microsoft.com/Forums/en-US/92ca8f03-8843-4914-937e-743ced33f654/xna-setpixel-functionality?forum=xnaframework

… I thought this specific overload (is) only works/used with regards/for to mipmappings, guess I learned something new.