Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Misallocated Pixels when GS2HMSBFormat has a width that's not a multiple of 4 #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
galdam opened this issue Apr 4, 2025 · 1 comment

Comments

@galdam
Copy link

galdam commented Apr 4, 2025

When the frame buffer has a width that's not a multiple of 4, pixels at the edge are misallocated.
I've put together the following as an example:

BLACK = 1
RED = 2
WHITE = 3

WIDTH = 7
HEIGHT = 2

buffer = bytearray(math.ceil((WIDTH * HEIGHT) / 4))
fb = adafruit_framebuf.FrameBuffer(
    buffer, WIDTH, HEIGHT, buf_format=adafruit_framebuf.GS2_HMSB, 
)
fb.fill(WHITE)

def print_arr(a):
   "Print the byte array as paired bytes"
    n = 2
    a = ''.join([f'{v:08b}' for v in a])
    a = [a[i:i + n] for i in range(0, len(a), n)]
    for r in range(HEIGHT):
        print(' '.join(a[r*WIDTH:(r+1)*WIDTH]))
    print(' '.join(a[(r+1)*WIDTH:]))

color_map = {3:'_', 2: '*', 1: '#'}
def print_buffer(the_fb):
    print("+" * (the_fb.width + 2))
    for y in range(the_fb.height):
        print("+", end="")
        for x in range(the_fb.width):
            c = fb.pixel(x, y)
            print(color_map[c], end="")
        print("+")
    print("+" * (the_fb.width + 2))

Using the above, setup:

fb.pixel(4,0, RED) 
print_arr(fb.buf)
print_buffer(fb)

gives

11 11 11 11 11 11 11
10 11 11 11 11 11 11
11 11

+++++++++
+____*__+
+*______+
+++++++++

The same result occurs with fb.pixel(0,1, RED) as well.

@galdam
Copy link
Author

galdam commented Apr 5, 2025

How about this as a solution:

class GS2HMSBFormat:

    @staticmethod
    def get_pixel(framebuf, x, y):
        """Get the color of a given pixel"""
        index = (y * framebuf.stride + x) >> 2
        pixel = framebuf.buf[index]

        # shift = (x & 0b11) << 1
        shift = ((y * framebuf.stride + x) & 0b11) << 1  # Update to use the absolute index of the pixel
        return (pixel >> shift) & 0b11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant