Looking at the SDL_Rect documentation, it's defined as:
typedef struct {
Sint16 x, y;
Uint16 w, h;
} SDL_Rect;
This gives you a range of −32768 to 32767 for the x
and y
component, and a range of 0 to 65535 for the w
and h
component. It doesn't make sense to have negative widths and heights (thus w
and h
are unsigned), and x
and y
are already signed, meaning that it can represent off-screen positions (up to 32k pixels to the left of the screen and up to 32k pixels above the top of the screen).
Assuming your characters are 8 pixels wide (you do destrect.x+=8;
), you can have 4000 charaters to the left of the screen and still be within the representable range of Sint16
.
Only render what's on the screen, as the other poster suggested. In general, there are 3 cases:
Character is completely off-screen, no need to render
Character is partially off-screen, render parts of it
Character is completely on-screen, render it fully
In case the blitting function handles clipping, case 2 and 3 can be combined.
Given that you have a fixed-width font, skipping off-screen characters is relatively easy and can be done up-front, with no conditionals inside the loop:
// The X position of where the text starts
int text_position_x = -90000;
// The text that you want to output
const char *chars = "Hello World";
// The fixed width of each character
int char_width = 8;
// Determine the first on-screen character
int first_character = 0;
int last_character = strlen(chars);
// If text starts off-screen, skip completely invisible characters
if (text_position_x < 0) {
first_character = -text_position_x / char_width;
text_position_x += char_width * first_character;
}
// text_position_x will be >= -char_width + 1
dstrect.x = text_position_x;
for (int i=first_character; i<last_character; i++) {
SDL_Blitsurface(bitmapsurface, rects[chars[i]], screen, destrect);
destrect.x+=8;
}
Some other remarks:
- Call
strlen()
only once at the beginning and not in every iteration
- You can do clipping on the top / right / bottom edge of the screen as well
- You could cull some strings early once you know they are fully off-screen