/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2002 Philipp Pertermann * * All files in this archive are subject to the GNU General Public License. * See the file COPYING in the source tree root for full license agreement. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "plugin.h" #include "configfile.h" PLUGIN_HEADER /* size of the field the worm lives in */ #define FIELD_RECT_X 1 #define FIELD_RECT_Y 1 #define FIELD_RECT_WIDTH (LCD_WIDTH - 45) #define FIELD_RECT_HEIGHT (LCD_HEIGHT - 2) /* when the game starts */ #define INITIAL_WORM_LENGTH 10 /* num of pixel the worm grows per eaten food */ #define WORM_PER_FOOD 7 /* num of worms creeping in the FIELD */ #define MAX_WORMS 3 /* minimal distance between a worm and an argh when a new argh is made */ #define MIN_ARGH_DIST 5 #if (CONFIG_KEYPAD == RECORDER_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_PLAYER2_DIR1 BUTTON_F2 #define BTN_PLAYER2_DIR2 BUTTON_F3 #define BTN_STARTPAUSE BUTTON_PLAY #define BTN_QUIT BUTTON_OFF #define BTN_STOPRESET BUTTON_ON #define BTN_TOGGLE_KEYS BUTTON_F1 #if BUTTON_REMOTE != 0 #define BTN_RC_UP BUTTON_RC_VOL_UP #define BTN_RC_DOWN BUTTON_RC_VOL_DOWN #define REMOTE #define MULTIPLAYER #endif #define PLAYERS_TEXT "UP/DN" #define WORMS_TEXT "L/R" #define KEY_CONTROL_TEXT "F1" #elif (CONFIG_KEYPAD == ARCHOS_AV300_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_PLAYER2_DIR1 BUTTON_F2 #define BTN_PLAYER2_DIR2 BUTTON_F3 #define BTN_STARTPAUSE BUTTON_SELECT #define BTN_QUIT BUTTON_OFF #define BTN_STOPRESET BUTTON_ON #define BTN_TOGGLE_KEYS BUTTON_F1 #define PLAYERS_TEXT "UP/DN" #define WORMS_TEXT "L/R" #define KEY_CONTROL_TEXT "F1" #elif (CONFIG_KEYPAD == ONDIO_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE (BUTTON_MENU|BUTTON_REL) #define BTN_QUIT (BUTTON_OFF|BUTTON_REL) #define BTN_STOPRESET (BUTTON_OFF|BUTTON_MENU) #define PLAYERS_TEXT "UP/DN" #define WORMS_TEXT "L/R" #elif (CONFIG_KEYPAD == IPOD_4G_PAD) || (CONFIG_KEYPAD == IPOD_3G_PAD) || \ (CONFIG_KEYPAD == IPOD_1G2G_PAD) #define BTN_DIR_UP BUTTON_MENU #define BTN_DIR_DOWN BUTTON_PLAY #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE (BUTTON_SELECT|BUTTON_REL) #define BTN_QUIT (BUTTON_SELECT|BUTTON_MENU) #define BTN_STOPRESET (BUTTON_SELECT|BUTTON_PLAY) #define PLAYERS_TEXT "Menu/Play" #define WORMS_TEXT "Left/Right" #elif (CONFIG_KEYPAD == IRIVER_H300_PAD) || (CONFIG_KEYPAD == IRIVER_H100_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE (BUTTON_SELECT|BUTTON_REL) #define BTN_QUIT BUTTON_OFF #define BTN_STOPRESET BUTTON_ON #define BTN_RC_QUIT BUTTON_RC_STOP #define PLAYERS_TEXT "Up/Down" #define WORMS_TEXT "Left/Right" #elif (CONFIG_KEYPAD == IAUDIO_X5M5_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE BUTTON_PLAY #define BTN_QUIT BUTTON_POWER #define BTN_STOPRESET BUTTON_REC #define PLAYERS_TEXT "Up/Down" #define WORMS_TEXT "Left/Right" #elif (CONFIG_KEYPAD == GIGABEAT_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE BUTTON_SELECT #define BTN_QUIT BUTTON_POWER #define BTN_STOPRESET BUTTON_A #define PLAYERS_TEXT "Up/Down" #define WORMS_TEXT "Left/Right" #elif (CONFIG_KEYPAD == SANSA_E200_PAD) #define BTN_DIR_UP BUTTON_UP #define BTN_DIR_DOWN BUTTON_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE BUTTON_SELECT #define BTN_QUIT BUTTON_POWER #define BTN_STOPRESET BUTTON_REC #define PLAYERS_TEXT "Up/Down" #define WORMS_TEXT "Left/Right" #elif (CONFIG_KEYPAD == IRIVER_H10_PAD) #define BTN_DIR_UP BUTTON_SCROLL_UP #define BTN_DIR_DOWN BUTTON_SCROLL_DOWN #define BTN_DIR_LEFT BUTTON_LEFT #define BTN_DIR_RIGHT BUTTON_RIGHT #define BTN_STARTPAUSE BUTTON_PLAY #define BTN_QUIT BUTTON_POWER #define BTN_STOPRESET BUTTON_REW #define PLAYERS_TEXT "Up/Down" #define WORMS_TEXT "Left/Right" #endif #if (LCD_WIDTH == 112) && (LCD_HEIGHT == 64) #define FOOD_SIZE 3 #define ARGH_SIZE 4 #define SPEED 14 #define MAX_WORM_SEGMENTS 128 #elif (LCD_WIDTH == 138) && (LCD_HEIGHT == 110) #define FOOD_SIZE 4 #define ARGH_SIZE 5 #define SPEED 10 #define MAX_WORM_SEGMENTS 128 #elif (LCD_WIDTH == 128) && (LCD_HEIGHT == 128) #define FOOD_SIZE 4 #define ARGH_SIZE 5 #define SPEED 9 #define MAX_WORM_SEGMENTS 128 #elif (LCD_WIDTH == 160) && (LCD_HEIGHT == 128) #define FOOD_SIZE 4 #define ARGH_SIZE 5 #define SPEED 8 #define MAX_WORM_SEGMENTS 256 #elif (LCD_WIDTH == 176) && (LCD_HEIGHT == 132) #define FOOD_SIZE 4 #define ARGH_SIZE 5 #define SPEED 6 #define MAX_WORM_SEGMENTS 256 #elif (LCD_WIDTH == 220) && (LCD_HEIGHT == 176) #define FOOD_SIZE 5 #define ARGH_SIZE 6 #define SPEED 4 #define MAX_WORM_SEGMENTS 512 #elif (LCD_WIDTH == 176) && (LCD_HEIGHT == 220) #define FOOD_SIZE 5 #define ARGH_SIZE 6 #define SPEED 4 #define MAX_WORM_SEGMENTS 512 #elif (LCD_WIDTH == 320) && (LCD_HEIGHT == 240) #define FOOD_SIZE 7 #define ARGH_SIZE 8 #define SPEED 4 #define MAX_WORM_SEGMENTS 512 #elif (LCD_WIDTH == 240) && (LCD_HEIGHT == 320) #define FOOD_SIZE 7 #define ARGH_SIZE 8 #define SPEED 4 #define MAX_WORM_SEGMENTS 512 #endif #ifdef HAVE_LCD_COLOR #define COLOR_WORM LCD_RGBPACK(80, 40, 0) #define COLOR_ARGH LCD_RGBPACK(175, 0, 0) #define COLOR_FOOD LCD_RGBPACK(0, 150, 0) #define COLOR_FG LCD_RGBPACK(0, 0, 0) #define COLOR_BG LCD_RGBPACK(181, 199, 231) #endif /** * All the properties that a worm has. */ static struct worm { /* The worm is stored in a ring of xy coordinates */ int x[MAX_WORM_SEGMENTS]; int y[MAX_WORM_SEGMENTS]; int head; /* index of the head within the buffer */ int tail; /* index of the tail within the buffer */ int growing; /* number of cyles the worm still keeps growing */ bool alive; /* the worms living state */ /* direction vector in which the worm moves */ int dirx; /* only values -1 0 1 allowed */ int diry; /* only values -1 0 1 allowed */ /* this method is used to fetch the direction the user has selected. It can be one of the values human_player1, human_player2, remote_player, virtual_player. All these values are fuctions, that can change the direction of the worm */ void (*fetch_worm_direction)(struct worm *w); } worms[MAX_WORMS]; /* stores the highscore - besides it was scored by a virtual player */ static int highscore; #define MAX_FOOD 5 /* maximal number of food items */ /* The arrays store the food coordinates */ static int foodx[MAX_FOOD]; static int foody[MAX_FOOD]; #define MAX_ARGH 100 /* maximal number of argh items */ #define ARGHS_PER_FOOD 2 /* number of arghs produced per eaten food */ /* The arrays store the argh coordinates */ static int arghx[MAX_ARGH]; static int arghy[MAX_ARGH]; /* the number of arghs that are currently in use */ static int argh_count; /* the number of arghs per food, settable by user */ static int arghs_per_food = ARGHS_PER_FOOD; /* the size of the argh, settable by user */ static int argh_size = ARGH_SIZE; /* the size of the food, settable by user */ static int food_size = FOOD_SIZE; /* the speed of the worm, settable by user */ static int speed = SPEED; /* the amount a worm grows by eating a food, settable by user */ static int worm_food = WORM_PER_FOOD; /* End additional variables */ #ifdef DEBUG_WORMLET /* just a buffer used for debug output */ static char debugout[15]; #endif /* the number of active worms (dead or alive) */ static int worm_count = MAX_WORMS; /* in multiplayer mode: en- / disables the remote worm control in singleplayer mode: toggles 4 / 2 button worm control */ static bool use_remote = false; /* return values of check_collision */ #define COLLISION_NONE 0 #define COLLISION_WORM 1 #define COLLISION_FOOD 2 #define COLLISION_ARGH 3 #define COLLISION_FIELD 4 /* constants for use as directions. Note that the values are ordered clockwise. Thus increasing / decreasing the values is equivalent to right / left turns. */ #define WEST 0 #define NORTH 1 #define EAST 2 #define SOUTH 3 /* direction of human player 1 */ static int player1_dir = EAST; /* direction of human player 2 */ static int player2_dir = EAST; /* direction of human player 3 */ static int player3_dir = EAST; /* the number of (human) players that currently control a worm */ static int players = 1; /* the rockbox plugin api */ static struct plugin_api* rb; #define SETTINGS_VERSION 1 #define SETTINGS_MIN_VERSION 1 #define SETTINGS_FILENAME "wormlet.cfg" static struct configdata config[] = { {TYPE_INT, 0, 1024, &highscore, "highscore", NULL, NULL}, {TYPE_INT, 0, 15, &arghs_per_food, "arghs per food", NULL, NULL}, {TYPE_INT, 0, 15, &argh_size, "argh size", NULL, NULL}, {TYPE_INT, 0, 15, &food_size, "food size", NULL, NULL}, {TYPE_INT, 0, 3, &players, "players", NULL, NULL}, {TYPE_INT, 0, 3, &worm_count, "worms", NULL, NULL}, {TYPE_INT, 0, 20, &speed, "speed", NULL, NULL}, {TYPE_INT, 0, 15, &worm_food, "Worm Growth Per Food", NULL, NULL}//, //{TYPE_INT, 0, 3, &use_remote, "use remote", NULL, NULL} }; #ifdef DEBUG_WORMLET static void set_debug_out(char *str){ strcpy(debugout, str); } #endif /** * Returns the direction id in which the worm * currently is creeping. * @param struct worm *w The worm that is to be investigated. * w Must not be null. * @return int A value 0 <= value < 4 * Note the predefined constants NORTH, SOUTH, EAST, WEST */ static int get_worm_dir(struct worm *w) { int retVal ; if (w->dirx == 0) { if (w->diry == 1) { retVal = SOUTH; } else { retVal = NORTH; } } else { if (w->dirx == 1) { retVal = EAST; } else { retVal = WEST; } } return retVal; } /** * Set the direction of the specified worm with a direction id. * Increasing the value by 1 means to turn the worm direction * to right by 90 degree. * @param struct worm *w The worm that is to be altered. w Must not be null. * @param int dir The new direction in which the worm is to creep. * dir must be 0 <= dir < 4. Use predefined constants * NORTH, SOUTH, EAST, WEST */ static void set_worm_dir(struct worm *w, int dir) { switch (dir) { case WEST: w->dirx = -1; w->diry = 0; break; case NORTH: w->dirx = 0; w->diry = - 1; break; case EAST: w->dirx = 1; w->diry = 0; break; case SOUTH: w->dirx = 0; w->diry = 1; break; } } /** * Returns the current length of the worm array. This * is also a value for the number of bends that are in the worm. * @return int a positive value with 0 <= value < MAX_WORM_SEGMENTS */ static int get_worm_array_length(struct worm *w) { /* initial simple calculation will be overwritten if wrong. */ int retVal = w->head - w->tail; /* if the worm 'crosses' the boundaries of the ringbuffer */ if (retVal < 0) { retVal = w->head + MAX_WORM_SEGMENTS - w->tail; } return retVal; } /** * Returns the score the specified worm. The score is the length * of the worm. * @param struct worm *w The worm that is to be investigated. * w must not be null. * @return int The length of the worm (>= 0). */ static int get_score(struct worm *w) { int retval = 0; int length = get_worm_array_length(w); int i; for (i = 0; i < length; i++) { /* The iteration iterates the length of the worm. Here's the conversion to the true indices within the worm arrays. */ int linestart = (w->tail + i ) % MAX_WORM_SEGMENTS; int lineend = (linestart + 1) % MAX_WORM_SEGMENTS; int startx = w->x[linestart]; int starty = w->y[linestart]; int endx = w->x[lineend]; int endy = w->y[lineend]; int minimum, maximum; if (startx == endx) { minimum = MIN(starty, endy); maximum = MAX(starty, endy); } else { minimum = MIN(startx, endx); maximum = MAX(startx, endx); } retval += abs(maximum - minimum); } return retval; } /** * Determines wether the line specified by startx, starty, endx, endy intersects * the rectangle specified by x, y, width, height. Note that the line must be exactly * horizontal or vertical (startx == endx or starty == endy). * @param int startx The x coordinate of the start point of the line. * @param int starty The y coordinate of the start point of the line. * @param int endx The x coordinate of the end point of the line. * @param int endy The y coordinate of the end point of the line. * @param int x The x coordinate of the top left corner of the rectangle. * @param int y The y coordinate of the top left corner of the rectangle. * @param int width The width of the rectangle. * @param int height The height of the rectangle. * @return bool Returns true if the specified line intersects with the recangle. */ static bool line_in_rect(int startx, int starty, int endx, int endy, int x, int y, int width, int height) { bool retval = false; int simple, simplemin, simplemax; int compa, compb, compmin, compmax; int temp; if (startx == endx) { simple = startx; simplemin = x; simplemax = x + width; compa = starty; compb = endy; compmin = y; compmax = y + height; } else { simple = starty; simplemin = y; simplemax = y + height; compa = startx; compb = endx; compmin = x; compmax = x + width; }; temp = compa; compa = MIN(compa, compb); compb = MAX(temp, compb); if (simplemin <= simple && simple <= simplemax) { if ((compmin <= compa && compa <= compmax) || (compmin <= compb && compb <= compmax) || (compa <= compmin && compb >= compmax)) { retval = true; } } return retval; } /** * Tests wether the specified worm intersects with the rect. * @param struct worm *w The worm to be investigated * @param int x The x coordinate of the top left corner of the rect * @param int y The y coordinate of the top left corner of the rect * @param int widht The width of the rect * @param int height The height of the rect * @return bool Returns true if the worm intersects with the rect */ static bool worm_in_rect(struct worm *w, int x, int y, int width, int height) { bool retval = false; /* get_worm_array_length is expensive -> buffer the value */ int wormLength = get_worm_array_length(w); int i; /* test each entry that is part of the worm */ for (i = 0; i < wormLength && retval == false; i++) { /* The iteration iterates the length of the worm. Here's the conversion to the true indices within the worm arrays. */ int linestart = (w->tail + i ) % MAX_WORM_SEGMENTS; int lineend = (linestart + 1) % MAX_WORM_SEGMENTS; int startx = w->x[linestart]; int starty = w->y[linestart]; int endx = w->x[lineend]; int endy = w->y[lineend]; retval = line_in_rect(startx, starty, endx, endy, x, y, width, height); } return retval; } /** * Checks wether a specific food in the food arrays is at the * specified coordinates. * @param int foodIndex The index of the food in the food arrays * @param int x the x coordinate. * @param int y the y coordinate. * @return Returns true if the coordinate hits the food specified by * foodIndex. */ static bool specific_food_collision(int foodIndex, int x, int y) { bool retVal = false; if (x >= foodx[foodIndex] && x < foodx[foodIndex] + food_size && y >= foody[foodIndex] && y < foody[foodIndex] + food_size) { retVal = true; } return retVal; } /** * Returns the index of the food that is at the * given coordinates. If no food is at the coordinates * -1 is returned. * @return int -1 <= value < MAX_FOOD */ static int food_collision(int x, int y) { int i = 0; int retVal = -1; for (i = 0; i < MAX_FOOD; i++) { if (specific_food_collision(i, x, y)) { retVal = i; break; } } return retVal; } /** * Checks wether a specific argh in the argh arrays is at the * specified coordinates. * @param int arghIndex The index of the argh in the argh arrays * @param int x the x coordinate. * @param int y the y coordinate. * @return Returns true if the coordinate hits the argh specified by * arghIndex. */ static bool specific_argh_collision(int arghIndex, int x, int y) { if ( x >= arghx[arghIndex] && y >= arghy[arghIndex] && x < arghx[arghIndex] + argh_size && y < arghy[arghIndex] + argh_size ) { return true; } return false; } /** * Returns the index of the argh that is at the * given coordinates. If no argh is at the coordinates * -1 is returned. * @param int x The x coordinate. * @param int y The y coordinate. * @return int -1 <= value < argh_count <= MAX_ARGH */ static int argh_collision(int x, int y) { int i = 0; int retVal = -1; /* search for the argh that has the specified coords */ for (i = 0; i < argh_count; i++) { if (specific_argh_collision(i, x, y)) { retVal = i; break; } } return retVal; } /** * Checks wether the worm collides with the food at the specfied food-arrays. * @param int foodIndex The index of the food in the arrays. Ensure the value is * 0 <= foodIndex <= MAX_FOOD * @return Returns true if the worm collides with the specified food. */ static bool worm_food_collision(struct worm *w, int foodIndex) { bool retVal = false; retVal = worm_in_rect(w, foodx[foodIndex], foody[foodIndex], food_size - 1, food_size - 1); return retVal; } /** * Returns true if the worm hits the argh within the next moves (unless * the worm changes it's direction). * @param struct worm *w - The worm to investigate * @param int argh_idx - The index of the argh * @param int moves - The number of moves that are considered. * @return Returns false if the specified argh is not hit within the next * moves. */ static bool worm_argh_collision_in_moves(struct worm *w, int argh_idx, int moves){ bool retVal = false; int x1, y1, x2, y2; x1 = w->x[w->head]; y1 = w->y[w->head]; x2 = w->x[w->head] + moves * w->dirx; y2 = w->y[w->head] + moves * w->diry; retVal = line_in_rect(x1, y1, x2, y2, arghx[argh_idx], arghy[argh_idx], argh_size, argh_size); return retVal; } /** * Checks wether the worm collides with the argh at the specfied argh-arrays. * @param int arghIndex The index of the argh in the arrays. * Ensure the value is 0 <= arghIndex < argh_count <= MAX_ARGH * @return Returns true if the worm collides with the specified argh. */ static bool worm_argh_collision(struct worm *w, int arghIndex) { bool retVal = false; retVal = worm_in_rect(w, arghx[arghIndex], arghy[arghIndex], argh_size - 1, argh_size - 1); return retVal; } /** * Find new coordinates for the food stored in foodx[index], foody[index] * that don't collide with any other food or argh * @param int index * Ensure that 0 <= index < MAX_FOOD. */ static void make_food(int index) { int x = 0; int y = 0; bool collisionDetected = false; int i; do { /* make coordinates for a new food so that the entire food lies within the FIELD */ x = rb->rand() % (FIELD_RECT_WIDTH - food_size); y = rb->rand() % (FIELD_RECT_HEIGHT - food_size); /* Ensure that the new food doesn't collide with any existing foods or arghs. If one or more corners of the new food hit any existing argh or food a collision is detected. */ collisionDetected = food_collision(x , y ) >= 0 || food_collision(x , y + food_size - 1) >= 0 || food_collision(x + food_size - 1, y ) >= 0 || food_collision(x + food_size - 1, y + food_size - 1) >= 0 || argh_collision(x , y ) >= 0 || argh_collision(x , y + food_size - 1) >= 0 || argh_collision(x + food_size - 1, y ) >= 0 || argh_collision(x + food_size - 1, y + food_size - 1) >= 0; /* use coordinates for further testing */ foodx[index] = x; foody[index] = y; /* now test wether we accidently hit the worm with food ;) */ i = 0; for (i = 0; i < worm_count && !collisionDetected; i++) { collisionDetected |= worm_food_collision(&worms[i], index); } } while (collisionDetected); return; } /** * Clears a food from the lcd buffer. * @param int index The index of the food arrays under which * the coordinates of the desired food can be found. Ensure * that the value is 0 <= index <= MAX_FOOD. */ static void clear_food(int index) { /* remove the old food from the screen */ rb->lcd_set_drawmode(DRMODE_SOLID|DRMODE_INVERSEVID); rb->lcd_fillrect(foodx[index] + FIELD_RECT_X, foody[index] + FIELD_RECT_Y, food_size, food_size); rb->lcd_set_drawmode(DRMODE_SOLID); } /** * Draws a food in the lcd buffer. * @param int index The index of the food arrays under which * the coordinates of the desired food can be found. Ensure * that the value is 0 <= index <= MAX_FOOD. */ static void draw_food(int index) { /* draw the food object */ #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_FOOD); #endif rb->lcd_fillrect(foodx[index] + FIELD_RECT_X, foody[index] + FIELD_RECT_Y, food_size, food_size); rb->lcd_set_drawmode(DRMODE_SOLID|DRMODE_INVERSEVID); rb->lcd_fillrect(foodx[index] + FIELD_RECT_X + 1, foody[index] + FIELD_RECT_Y + 1, food_size - 2, food_size - 2); rb->lcd_set_drawmode(DRMODE_SOLID); #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_FG); #endif } /** * Find new coordinates for the argh stored in arghx[index], arghy[index] * that don't collide with any other food or argh. * @param int index * Ensure that 0 <= index < argh_count < MAX_ARGH. */ static void make_argh(int index) { int x = -1; int y = -1; bool collisionDetected = false; int i; do { /* make coordinates for a new argh so that the entire food lies within the FIELD */ x = rb->rand() % (FIELD_RECT_WIDTH - argh_size); y = rb->rand() % (FIELD_RECT_HEIGHT - argh_size); /* Ensure that the new argh doesn't intersect with any existing foods or arghs. If one or more corners of the new argh hit any existing argh or food an intersection is detected. */ collisionDetected = food_collision(x , y ) >= 0 || food_collision(x , y + argh_size - 1) >= 0 || food_collision(x + argh_size - 1, y ) >= 0 || food_collision(x + argh_size - 1, y + argh_size - 1) >= 0 || argh_collision(x , y ) >= 0 || argh_collision(x , y + argh_size - 1) >= 0 || argh_collision(x + argh_size - 1, y ) >= 0 || argh_collision(x + argh_size - 1, y + argh_size - 1) >= 0; /* use the candidate coordinates to make a real argh */ arghx[index] = x; arghy[index] = y; /* now test wether we accidently hit the worm with argh ;) */ for (i = 0; i < worm_count && !collisionDetected; i++) { collisionDetected |= worm_argh_collision(&worms[i], index); collisionDetected |= worm_argh_collision_in_moves(&worms[i], index, MIN_ARGH_DIST); } } while (collisionDetected); return; } /** * Draws an argh in the lcd buffer. * @param int index The index of the argh arrays under which * the coordinates of the desired argh can be found. Ensure * that the value is 0 <= index < argh_count <= MAX_ARGH. */ static void draw_argh(int index) { /* draw the new argh */ #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_ARGH); #endif rb->lcd_fillrect(arghx[index] + FIELD_RECT_X, arghy[index] + FIELD_RECT_Y, argh_size, argh_size); #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_FG); #endif } static void virtual_player(struct worm *w); /** * Initialzes the specified worm with INITIAL_WORM_LENGTH * and the tail at the specified position. The worm will * be initialized alive and creeping EAST. * @param struct worm *w The worm that is to be initialized * @param int x The x coordinate at which the tail of the worm starts. * x must be 0 <= x < FIELD_RECT_WIDTH. * @param int y The y coordinate at which the tail of the worm starts * y must be 0 <= y < FIELD_RECT_WIDTH. */ static void init_worm(struct worm *w, int x, int y){ /* initialize the worm size */ w->head = 1; w->tail = 0; w->x[w->head] = x + 1; w->y[w->head] = y; w->x[w->tail] = x; w->y[w->tail] = y; /* set the initial direction the worm creeps to */ w->dirx = 1; w->diry = 0; w->growing = INITIAL_WORM_LENGTH - 1; w->alive = true; w->fetch_worm_direction = virtual_player; } /** * Writes the direction that was stored for * human player 1 into the specified worm. This function * may be used to be stored in worm.fetch_worm_direction. * The value of * the direction is read from player1_dir. * @param struct worm *w - The worm of which the direction * is altered. */ static void human_player1(struct worm *w) { set_worm_dir(w, player1_dir); } /** * Writes the direction that was stored for * human player 2 into the specified worm. This function * may be used to be stored in worm.fetch_worm_direction. * The value of * the direction is read from player2_dir. * @param struct worm *w - The worm of which the direction * is altered. */ static void human_player2(struct worm *w) { set_worm_dir(w, player2_dir); } /** * Writes the direction that was stored for * human player using a remote control * into the specified worm. This function * may be used to be stored in worm.fetch_worm_direction. * The value of * the direction is read from player3_dir. * @param struct worm *w - The worm of which the direction * is altered. */ static void remote_player(struct worm *w) { set_worm_dir(w, player3_dir); } /** * Initializes the worm-, food- and argh-arrays, draws a frame, * makes some food and argh and display all that stuff. */ static void init_wormlet(void) { int i; for (i = 0; i< worm_count; i++) { /* Initialize all the worm coordinates to center. */ int x = (int)(FIELD_RECT_WIDTH / 2); int y = (int)((FIELD_RECT_HEIGHT - 20)/ 2) + i * 10; init_worm(&worms[i], x, y); } player1_dir = EAST; player2_dir = EAST; player3_dir = EAST; if (players > 0) { worms[0].fetch_worm_direction = human_player1; } if (players > 1) { if (use_remote) { worms[1].fetch_worm_direction = remote_player; } else { worms[1].fetch_worm_direction = human_player2; } } if (players > 2) { worms[2].fetch_worm_direction = human_player2; } /* Needed when the game is restarted using BTN_STOPRESET */ rb->lcd_clear_display(); /* make and display some food and argh */ argh_count = MAX_FOOD; for (i = 0; i < MAX_FOOD; i++) { make_food(i); draw_food(i); make_argh(i); draw_argh(i); } /* draw the game field */ rb->lcd_set_drawmode(DRMODE_COMPLEMENT); rb->lcd_fillrect(0, 0, FIELD_RECT_WIDTH + 2, FIELD_RECT_HEIGHT + 2); rb->lcd_fillrect(1, 1, FIELD_RECT_WIDTH, FIELD_RECT_HEIGHT); rb->lcd_set_drawmode(DRMODE_SOLID); /* make everything visible */ rb->lcd_update(); } /** * Move the worm one step further if it is alive. * The direction in which the worm moves is taken from dirx and diry. * move_worm decreases growing if > 0. While the worm is growing the tail * is left untouched. * @param struct worm *w The worm to move. w must not be NULL. */ static void move_worm(struct worm *w) { if (w->alive) { /* determine the head point and its precessor */ int headx = w->x[w->head]; int heady = w->y[w->head]; int prehead = (w->head + MAX_WORM_SEGMENTS - 1) % MAX_WORM_SEGMENTS; int preheadx = w->x[prehead]; int preheady = w->y[prehead]; /* determine the old direction */ int olddirx; int olddiry; if (headx == preheadx) { olddirx = 0; olddiry = (heady > preheady) ? 1 : -1; } else { olddiry = 0; olddirx = (headx > preheadx) ? 1 : -1; } /* olddir == dir? a change of direction means a new segment has been opened */ if (olddirx != w->dirx || olddiry != w->diry) { w->head = (w->head + 1) % MAX_WORM_SEGMENTS; } /* new head position */ w->x[w->head] = headx + w->dirx; w->y[w->head] = heady + w->diry; /* while the worm is growing no tail procession is necessary */ if (w->growing > 0) { /* update the worms grow state */ w->growing--; } /* if the worm isn't growing the tail has to be dragged */ else { /* index of the end of the tail segment */ int tail_segment_end = (w->tail + 1) % MAX_WORM_SEGMENTS; /* drag the end of the tail */ /* only one coordinate has to be altered. Here it is determined which one */ int dir = 0; /* specifies wether the coord has to be in- or decreased */ if (w->x[w->tail] == w->x[tail_segment_end]) { dir = (w->y[w->tail] - w->y[tail_segment_end] < 0) ? 1 : -1; w->y[w->tail] += dir; } else { dir = (w->x[w->tail] - w->x[tail_segment_end] < 0) ? 1 : -1; w->x[w->tail] += dir; } /* when the tail has been dragged so far that it meets the next segment start the tail segment is obsolete and must be freed */ if (w->x[w->tail] == w->x[tail_segment_end] && w->y[w->tail] == w->y[tail_segment_end]){ /* drop the last tail point */ w->tail = tail_segment_end; } } } } /** * Draws the head and clears the tail of the worm in * the display buffer. lcd_update() is NOT called thus * the caller has to take care that the buffer is displayed. */ static void draw_worm(struct worm *w) { #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_WORM); #endif /* draw the new head */ int x = w->x[w->head]; int y = w->y[w->head]; if (x >= 0 && x < FIELD_RECT_WIDTH && y >= 0 && y < FIELD_RECT_HEIGHT) { rb->lcd_drawpixel(x + FIELD_RECT_X, y + FIELD_RECT_Y); } rb->lcd_set_drawmode(DRMODE_SOLID|DRMODE_INVERSEVID); /* clear the space behind the worm */ x = w->x[w->tail] ; y = w->y[w->tail] ; if (x >= 0 && x < FIELD_RECT_WIDTH && y >= 0 && y < FIELD_RECT_HEIGHT) { rb->lcd_drawpixel(x + FIELD_RECT_X, y + FIELD_RECT_Y); } rb->lcd_set_drawmode(DRMODE_SOLID); #ifdef HAVE_LCD_COLOR rb->lcd_set_foreground(COLOR_FG); #endif } /** * Checks wether the coordinate is part of the worm. Returns * true if any part of the worm was hit - including the head. * @param x int The x coordinate * @param y int The y coordinate * @return int The index of the worm arrays that contain x, y. * Returns -1 if the coordinates are not part of the worm. */ static int specific_worm_collision(struct worm *w, int x, int y) { int retVal = -1; /* get_worm_array_length is expensive -> buffer the value */ int wormLength = get_worm_array_length(w); int i; /* test each entry that is part of the worm */ for (i = 0; i < wormLength && retVal == -1; i++) { /* The iteration iterates the length of the worm. Here's the conversion to the true indices within the worm arrays. */ int linestart = (w->tail + i ) % MAX_WORM_SEGMENTS; int lineend = (linestart + 1) % MAX_WORM_SEGMENTS; bool samex = (w->x[linestart] == x) && (w->x[lineend] == x); bool samey = (w->y[linestart] == y) && (w->y[lineend] == y); if (samex || samey){ int test, min, max, tmp; if (samey) { min = w->x[linestart]; max = w->x[lineend]; test = x; } else { min = w->y[linestart]; max = w->y[lineend]; test = y; } tmp = min; min = MIN(min, max); max = MAX(tmp, max); if (min <= test && test <= max) { retVal = lineend; } } } return retVal; } /** * Increases the length of the specified worm by marking * that it may grow by len pixels. Note that the worm has * to move to make the growing happen. * @param worm static int send_hid(libusb_device_handle *dev, int xfer_size, uint8_t *data, int size, int nr_xfers) { libusb_detach_kernel_driver(dev, 0); libusb_claim_interface(dev, 0); int recv_size; uint32_t my_tag = 0xcafebabe; uint8_t *xfer_buf = malloc(1 + xfer_size); struct hid_cmd_report_t cmd; memset(&cmd, 0, sizeof(cmd)); cmd.report_id = HID_BLTC_CMD_REPORT; cmd.cbw.signature = CBW_BLTC; cmd.cbw.tag = my_tag; cmd.cbw.length = size; cmd.cbw.flags = CBW_DIR_OUT; cmd.cbw.cdb.command = BLTC_DOWNLOAD_FW; put32be((void *)&cmd.cbw.cdb.length, size); int ret = libusb_control_transfer(dev, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x9, 0x201, 0, (void *)&cmd, sizeof(cmd), 1000); if(ret < 0) { printf("transfer error at init step\n"); goto Lstatus; } for(int i = 0; i < nr_xfers; i++) { xfer_buf[0] = HID_BLTC_DATA_REPORT; memcpy(&xfer_buf[1], &data[i * xfer_size], xfer_size); ret = libusb_control_transfer(dev, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x9, 0x202, 0, xfer_buf, xfer_size + 1, 1000); if(ret < 0) { printf("transfer error at send step %d\n", i); goto Lstatus; } } Lstatus: ret = libusb_interrupt_transfer(dev, 0x81, xfer_buf, xfer_size, &recv_size, 1000); if(ret == 0 && recv_size == sizeof(struct hid_status_report_t)) { struct hid_status_report_t *report = (void *)xfer_buf; if(report->report_id != HID_BLTC_STATUS_REPORT) { printf("Error: got non-status report\n"); return -1; } if(report->csw.signature != CSW_BLTS) { printf("Error: status report signature mismatch\n"); return -2; } if(report->csw.tag != my_tag) { printf("Error: status report tag mismtahc\n"); return -3; } if(report->csw.residue != 0) printf("Warning: %d byte were not transferred\n", report->csw.residue); switch(report->csw.status) { case CSW_PASSED: printf("Status: Passed\n"); return 0; case CSW_FAILED: printf("Status: Failed\n"); return -1; case CSW_PHASE_ERROR: printf("Status: Phase Error\n"); return -2; default: printf("Status: Unknown Error\n"); return -3; } } else if(ret < 0) printf("Error: cannot get status report\n"); else printf("Error: status report has wrong size\n"); return ret; } static int send_recovery(libusb_device_handle *dev, int xfer_size, uint8_t *data, int size, int nr_xfers) { (void) nr_xfers; // there should be no kernel driver attached but in doubt... libusb_detach_kernel_driver(dev, 0); libusb_claim_interface(dev, 0); int sent = 0; while(sent < size) { int xfered; int len = MIN(size - sent, xfer_size); int ret = libusb_bulk_transfer(dev, 1, data + sent, len, &xfered, 1000); if(ret < 0) { printf("transfer error at send offset %d\n", sent); return 1; } if(xfered == 0) { printf("empty transfer at step offset %d\n", sent); return 2; } sent += xfered; } return 0; } static void usage(void) { printf("sbloader [options] file\n"); printf("options:\n"); printf(" -h/-?/--help Display this help\n"); printf(" -d/--debug Enable debug output\n"); printf(" -x <size> Force transfer size\n"); printf(" -u <vid>:<pid> Force USB PID and VID\n"); printf(" -b <bus>:<dev> Force USB bus and device\n"); printf(" -p <protocol> Force protocol ('hid' or 'recovery')\n"); printf("The following devices are known to this tool:\n"); for(unsigned i = 0; i < sizeof(g_dev_info) / sizeof(g_dev_info[0]); i++) { const char *type = "unk"; if(g_dev_info[i].dev_type == HID_DEVICE) type = "hid"; else if(g_dev_info[i].dev_type == RECOVERY_DEVICE) type = "recovery"; else if(g_dev_info[i].dev_type == PROBE_DEVICE) type = "probe"; printf(" %04x:%04x %s (%d bytes/xfer)\n", g_dev_info[i].vendor_id, g_dev_info[i].product_id, type, g_dev_info[i].xfer_size); } printf("You can select a particular device by USB PID and VID.\n"); printf("In case this is ambiguous, use bus and device number.\n"); printf("Protocol is infered if possible and unspecified.\n"); printf("Transfer size is infered if possible.\n"); exit(1); } static bool dev_match(libusb_device *dev, struct dev_info_t *arg_di, int usb_bus, int usb_dev, int *db_idx) { // match bus/dev if(usb_bus != -1) return libusb_get_bus_number(dev) == usb_bus && libusb_get_device_address(dev) == usb_dev; // get device descriptor struct libusb_device_descriptor desc; if(libusb_get_device_descriptor(dev, &desc)) return false; // match command line vid/pid if specified if(arg_di->vendor_id != 0) return desc.idVendor == arg_di->vendor_id && desc.idProduct == arg_di->product_id; // match known vid/pid for(unsigned i = 0; i < sizeof(g_dev_info) / sizeof(g_dev_info[0]); i++) if(desc.idVendor == g_dev_info[i].vendor_id && desc.idProduct == g_dev_info[i].product_id) { if(db_idx) *db_idx = i; return true; } return false; } static void print_match(libusb_device *dev) { struct libusb_device_descriptor desc; if(libusb_get_device_descriptor(dev, &desc)) printf("????:????"); else printf("%04x:%04x", desc.idVendor, desc.idProduct); printf(" @ %d.%d\n", libusb_get_bus_number(dev), libusb_get_device_address(dev)); } static bool is_hid_dev(struct libusb_config_descriptor *desc) { if(desc->bNumInterfaces != 1) return false; if(desc->interface[0].num_altsetting != 1) return false; const struct libusb_interface_descriptor *intf = &desc->interface[0].altsetting[0]; if(intf->bNumEndpoints != 1) return false; if(intf->bInterfaceClass != LIBUSB_CLASS_HID || intf->bInterfaceSubClass != 0 || intf->bInterfaceProtocol != 0) return false; return true; } static bool is_recovery_dev(struct libusb_config_descriptor *desc) { (void) desc; return false; } static enum dev_type_t probe_protocol(libusb_device_handle *dev) { struct libusb_config_descriptor *desc; if(libusb_get_config_descriptor(libusb_get_device(dev), 0, &desc)) goto Lerr; if(is_hid_dev(desc)) return HID_DEVICE; if(is_recovery_dev(desc)) return RECOVERY_DEVICE; Lerr: printf("Cannot probe protocol, please specify it on command line.\n"); exit(11); return PROBE_DEVICE; } struct hid_item_t { int tag; int type; int total_size; int data_offset; int data_size; }; static bool hid_parse_short_item(uint8_t *buf, int size, struct hid_item_t *item) { if(size == 0) return false; item->tag = buf[0] >> 4; item->data_size = buf[0] & 3; item->type = (buf[0] >> 2) & 3; item->data_offset = 1; item->total_size = 1 + item->data_size; return size >= item->total_size; } static bool hid_parse_item(uint8_t *buf, int size, struct hid_item_t *item) { if(!hid_parse_short_item(buf, size, item)) return false; /* long item ? */ if(item->data_size == 2 && item->type == 3 && item->tag == 15) { item->tag = buf[2]; item->data_size = buf[1]; item->total_size = 3 + item->data_size; return size >= item->total_size; } else return true; } static int probe_hid_xfer_size(libusb_device_handle *dev) { // FIXME detahc kernel and claim interface here ? /* get HID descriptor */ uint8_t buffer[1024]; int ret = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8) | 0, 0, buffer, sizeof(buffer), 1000); if(ret <= 0) goto Lerr; /* this is not a real parser, since the HID descriptor of the device is * is mostly trivial, we assume that all reports are made up of one item * and simply compute the maximum of report size * report count */ int xfer_size = 0; int report_size = 0; int report_count = 0; uint8_t *buf = buffer; int size = ret; while(true) { struct hid_item_t item; if(!hid_parse_item(buf, size, &item)) break; if(item.type == /*global*/1) { if(item.tag == /*report count*/9) report_count = buf[item.data_offset]; if(item.tag == /*report size*/7) report_size = buf[item.data_offset]; } else if(item.type == /*main*/0) { if(item.tag == /*output*/9) xfer_size = MAX(xfer_size, report_count * report_size); } buf += item.total_size; size -= item.total_size; } return xfer_size / 8; Lerr: printf("Cannot probe transfer size, using default.\n"); return 0; } static int probe_xfer_size(enum dev_type_t prot, libusb_device_handle *dev) { if(prot == HID_DEVICE) return probe_hid_xfer_size(dev); printf("Cannot probe transfer size, using default.\n"); return 0; } int main(int argc, char **argv) { if(argc <= 1) usage(); struct dev_info_t di = {.vendor_id = 0, .product_id = 0, .xfer_size = 0, .dev_type = PROBE_DEVICE}; int usb_bus = -1; int usb_dev = -1; int force_xfer_size = 0; /* parse command line */ while(1) { static struct option long_options[] = { {"help", no_argument, 0, '?'}, {"debug", no_argument, 0, 'd'}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "?dx:u:b:p:", long_options, NULL); if(c == -1) break; switch(c) { case -1: break; case 'd': g_debug = true; break; case '?': usage(); break; case 'x': { char *end; force_xfer_size = strtoul(optarg, &end, 0); if(*end) { printf("Invalid transfer size!\n"); exit(2); } break; } case 'u': { char *end; di.vendor_id = strtoul(optarg, &end, 16); if(*end != ':') { printf("Invalid USB PID!\n"); exit(3); } di.product_id = strtoul(end + 1, &end, 16); if(*end) { printf("Invalid USB VID!\n"); exit(4); } break; } case 'b': { char *end; usb_bus = strtol(optarg, &end, 0); if(*end != ':') { printf("Invalid USB bus!\n"); exit(5); } usb_dev = strtol(end, &end, 0); if(*end) { printf("Invalid USB device!\n"); exit(6); } break; } case 'p': if(strcmp(optarg, "hid") == 0) di.dev_type = HID_DEVICE; else if(strcmp(optarg, "recovery") == 0) di.dev_type = RECOVERY_DEVICE; else { printf("Invalid protocol!\n"); exit(7); } break; default: printf("Internal error: unknown option '%c'\n", c); abort(); } } if(optind + 1 != argc) usage(); const char *filename = argv[optind]; /* lookup device */ libusb_init(NULL); libusb_set_debug(NULL, 3); libusb_device **list; ssize_t list_size = libusb_get_device_list(NULL, &list); libusb_device_handle *dev = NULL; int db_idx = -1; { libusb_device *mdev = NULL; int nr_matches = 0; for(int i = 0; i < list_size; i++) { // match bus/dev if specified if(dev_match(list[i], &di, usb_bus, usb_dev, &db_idx)) { mdev = list[i]; nr_matches++; } } if(nr_matches == 0) { printf("No device found\n"); exit(8); } if(nr_matches > 1) { printf("Several devices match the specified parameters:\n"); for(int i = 0; i < list_size; i++) { // match bus/dev if specified if(dev_match(list[i], &di, usb_bus, usb_dev, NULL)) { printf(" "); print_match(list[i]); } } } printf("Device: "); print_match(mdev); libusb_open(mdev, &dev); } if(dev == NULL) { printf("Cannot open device\n"); return 1; } /* get protocol */ enum dev_type_t dev_type = PROBE_DEVICE; int xfer_size = di.xfer_size; if(db_idx >= 0) { dev_type = g_dev_info[db_idx].dev_type; xfer_size = g_dev_info[db_idx].xfer_size; } /* if not forced, try to probe transfer size */ if(force_xfer_size == 0) force_xfer_size = probe_xfer_size(dev_type, dev); /* make a decision */ if(force_xfer_size > 0) xfer_size = force_xfer_size; else if(xfer_size == 0) { printf("Cannot probe transfer size, please specify it on the command line.\n"); exit(10); } if(dev_type == PROBE_DEVICE) dev_type = probe_protocol(dev); /* open file */ FILE *f = fopen(filename, "r"); if(f == NULL) { perror("Cannot open file"); return 1; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); printf("Transfer size: %d\n", xfer_size); int nr_xfers = (size + xfer_size - 1) / xfer_size; uint8_t *file_buf = malloc(nr_xfers * xfer_size); memset(file_buf, 0xff, nr_xfers * xfer_size); // pad with 0xff if(fread(file_buf, size, 1, f) != 1) { perror("read error"); fclose(f); return 1; } fclose(f); /* send file */ switch(dev_type) { case HID_DEVICE: send_hid(dev, xfer_size, file_buf, size, nr_xfers); break; case RECOVERY_DEVICE: send_recovery(dev, xfer_size, file_buf, size, nr_xfers); break; default: printf("unknown device type\n"); break; } return 0; }