/* boxes.c - Moving Inverted Boxes Author Jani Kniivilä compile with: gcc -o boxes boxes.c -lSDL -lpthread -ltSGGL */ #include #include #include #include SDL_Surface *surface; gfx_image_t *output; #define WIDTH 640 #define HEIGHT 480 #define N_BOXES 250 typedef struct { int x, y, speed, size; } box_t; box_t boxes[N_BOXES]; void move_boxes() { int i; for (i = 0; i < N_BOXES; i++) { boxes[i].y += boxes[i].speed; if (boxes[i].y > output->view_bottom) boxes[i].y = -boxes[i].size; else if (boxes[i].y < -boxes[i].size) boxes[i].y = output->view_bottom; } } void draw_boxes() { int i; for (i = 0; i < N_BOXES; i++) { gfx_slow_negate_area( boxes[i].x, boxes[i].y, boxes[i].x + boxes[i].size, boxes[i].y + boxes[i].size, output); } } int fx_init() { int i; if (SDL_Init(SDL_INIT_VIDEO) < 0) return -1; atexit(SDL_Quit); surface = SDL_SetVideoMode(WIDTH, HEIGHT, 16, SDL_SWSURFACE); if (!surface) return -2; output = gfx_create_null_image(WIDTH, HEIGHT); /* create an image without pixel-data */ if (!output) return -3; output->data = (Uint16 *) surface->pixels; /* redirect the pixels to "screen" */ for (i = 0; i < N_BOXES; i++) { boxes[i].x = rand() % output->width; boxes[i].y = rand() % output->height; boxes[i].size = 5 + (rand() % 40); boxes[i].speed = -7 + (3 * (rand() % 5)); if (boxes[i].speed == 0) boxes[i].speed = 1; } return 0; } void fx_shutdown() { free(output); } int fx_draw_frame() { move_boxes(); if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface); gfx_clear(output); draw_boxes(); if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface); SDL_Flip(surface); return 0; } int main() { SDL_Event event; int i, done = 0; i = fx_init(); if (i) return i; while (!done) { fx_draw_frame(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: case SDL_KEYDOWN: case SDL_MOUSEBUTTONDOWN: done = 1; } } } fx_shutdown(); return 0; }