int main(int argc, char** argv) { ros::init(argc, argv, "base_planner_cu"); ros::NodeHandle nh; ros::Rate loop_rate(100); // load globals from parameter server double param_input; bool bool_input; if(ros::param::get("base_planner_cu/obstacle_cost", param_input)) OBSTACLE_COST = param_input; // the cost of an obstacle if(ros::param::get("base_planner_cu/robot_radius", param_input)) robot_radius = param_input; //(m) if(ros::param::get("base_planner_cu/safety_distance", param_input)) safety_distance = param_input; //(m), distance that must be maintained between robot and obstacles if(ros::param::get("base_planner_cu/better_path_ratio", param_input)) old_path_discount = param_input; // if (current path length)*old_path_discount < (old path length) < (current path length)/old_path_discount, then stick with the old path if(ros::param::get("base_planner_cu/replan_jump", param_input)) MAX_POSE_JUMP = param_input; //(map grids) after which it is easer to replan from scratch if(ros::param::get("base_planner_cu/using_extra_safety_distance", bool_input)) high_cost_safety_region = bool_input; // true: dilate obstacles by an extra extra_dilation but instad of lethal, multiply existing cost by extra_dilation_mult if(ros::param::get("base_planner_cu/extra_safety_distance", param_input)) extra_dilation = param_input; //(m) // print data about parameters printf("obstacle cost: %f, robot radius: %f, safety_distance: %f, extra_safety_distance: %f, \nbetter_path_ratio: %f, replan_jump: %f \n", OBSTACLE_COST, robot_radius, safety_distance, extra_dilation, old_path_discount, MAX_POSE_JUMP); if(high_cost_safety_region) printf("using extra safety distance \n"); else printf("not using extra safety distance \n"); // wait until the map service is provided (we need its tf /world_cu -> /map_cu to be broadcast) ros::service::waitForService("/cu/get_map_cu", -1); // set up ROS topic subscriber callbacks pose_sub = nh.subscribe("/cu/pose_cu", 1, pose_callback); goal_sub = nh.subscribe("/cu/goal_cu", 1, goal_callback); map_changes_sub = nh.subscribe("/cu/map_changes_cu", 10, map_changes_callback); // set up ROS topic publishers global_path_pub = nh.advertise<nav_msgs::Path>("/cu/global_path_cu", 1); system_update_pub = nh.advertise<std_msgs::Int32>("/cu/system_update_cu", 10); // spin ros once ros::spinOnce(); loop_rate.sleep(); // wait for a map while(!load_map() && ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } // init map buildGraphAndMap(raw_map->height, raw_map->width); populate_map_from_raw_map(); // wait until we have a goal and a robot pose (these arrive via callbacks) while((goal_pose == NULL || robot_pose == NULL) && ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } // initialize search and related data structures (this calculates initial cost field) if(ros::ok()) { initialize_search(true); // true := use old map, (raw_map was populated in a pre-processing step) new_goal = false; ros::spinOnce(); // check in on callbacks // added to give map changes a chance to propogate before first real search ros::Rate one_time_sleep(2); one_time_sleep.sleep(); ros::spinOnce(); // check in on callbacks } // main planning loop int lr, ud; int time_counter = 0; MapPath* old_path = NULL; while (ros::ok()) { while(change_token_used) {printf("change token used, main \n");} change_token_used = true; time_counter++; //printf(" This is the base planner %d\n", time_counter); // heartbeat for debugging load_goal(); if(new_goal || reload_map) { if(reload_map) { printf("reinitializing map and searchtree \n"); change_token_used = false; // wait for a map while(!load_map() && ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } change_token_used = true; initialize_search(false); // false := reset map based in what is in raw_map (raw_map was just re-populated with info from the map server) } else // new_goal { printf("reinitializing search tree, reusing map \n"); initialize_search(true); // true := reuse the old map } new_goal = false; reload_map = false; if(old_path != NULL) { deleteMapPath(old_path); old_path = NULL; } // get best estimate of pose while(!load_pose()) { // wait for most up to date pose } printf(" recieved pose via service \n"); } else load_pose(); // if services lag then this is a bad idea, but have had problems on netbooks never getting new pose // find the new exact coordinates of the robot robot_pos_x = robot_pose->x/raw_map->resolution; // need to add global offset ability if(robot_pos_x > raw_map->width) robot_pos_x = raw_map->width; if(robot_pos_x < 0) robot_pos_x = 0; robot_pos_y = robot_pose->y/raw_map->resolution; // need to add global offset ability if(robot_pos_y > raw_map->width) robot_pos_y = raw_map->width; if(robot_pos_y < 0) robot_pos_y = 0; // do replanning, note that we need to make sure that all neighboring nodes of the cell(s) containing the robot are updated //printf("replanning %d \n", time_counter); if(robot_pos_x == (double)((int)robot_pos_x)) // then on a vertical edge, need to plan to nodes on cells to the left and right of the robot lr = -1; else //only need to plan to nodes on cells with x == int_pos_x lr = 0; while(lr < 2) { if(robot_pos_y == (double)((int)robot_pos_y)) // then on a horizontal edge, need to plan to nodes on cells to the top and bottom of the robot ud = -1; else //only need to plan to nodes on cells with y == int_pos_y ud = 0; if((int)robot_pos_x + lr < 0 || (int)robot_pos_x + lr > WIDTH) { lr++; continue; } while(ud < 2) { if((int)robot_pos_y + ud < 0 || (int)robot_pos_y + ud > HEIGHT) { ud++; continue; } s_start = &graph[(int)robot_pos_y + ud][(int)robot_pos_x + lr]; computeShortestPath(); // this updates the cost field to this node ud++; } lr++; } // extract the path, this will be used to figure out where to move the robot //printf("extract path1 %d \n", time_counter); MapPath* pathToGoalWithLookAhead = extractPathOneLookahead(); double path1_max_single_grid; double path1_cost = calculatePathCost(pathToGoalWithLookAhead, path1_max_single_grid); //printf("extract path2 %d \n", time_counter); MapPath* pathToGoalMine = extractPathMine(0); // this uses gradient descent where possible double path2_max_single_grid; double path2_cost = calculatePathCost(pathToGoalMine, path2_max_single_grid); double old_path_cost = LARGE; double old_path_max_single_grid; if(old_path != NULL) old_path_cost = calculatePathCost(old_path, old_path_max_single_grid); change_token_used = false; // use better path of the two to move the robot (or retain the old path if it is still better) if(old_path != NULL && path1_cost*old_path_discount <= old_path_cost && old_path_cost <= path1_cost/old_path_discount && path2_cost*old_path_discount <= old_path_cost && old_path_cost <= path2_cost/old_path_discount && old_path_max_single_grid < OBSTACLE_COST) { publish_global_path(old_path); //printf("old path is about the same or better %d [%f vs %f] %f \n", time_counter, old_path_cost, (path1_cost+path2_cost)/2, old_path_max_single_grid); deleteMapPath(pathToGoalMine); deleteMapPath(pathToGoalWithLookAhead); } else if(path1_cost < path2_cost && path1_max_single_grid < OBSTACLE_COST) { publish_global_path(pathToGoalWithLookAhead); //printf("path1 is better %d %f %f\n", time_counter, path1_cost, path1_max_single_grid); if(old_path != NULL) { deleteMapPath(old_path); old_path = NULL; } old_path = pathToGoalWithLookAhead; deleteMapPath(pathToGoalMine); } else if(path2_max_single_grid < OBSTACLE_COST) { publish_global_path(pathToGoalMine); //printf("path2 is better %d %f %f\n", time_counter, path2_cost, path2_max_single_grid); if(old_path != NULL) { deleteMapPath(old_path); old_path = NULL; } old_path = pathToGoalMine; deleteMapPath(pathToGoalWithLookAhead); } else // all paths go through obstacles { printf("Base Planner: No safe path exists to goal %f %f %f\n", old_path_cost, path1_cost, path2_cost); publish_system_update(1); reload_map = true; } ros::spinOnce(); loop_rate.sleep(); //printf("done %d \n", time_counter); } if(old_path != NULL) deleteMapPath(old_path); pose_sub.shutdown(); goal_sub.shutdown(); map_changes_sub.shutdown(); global_path_pub.shutdown(); system_update_pub.shutdown(); destroy_pose(robot_pose); destroy_pose(goal_pose); cpDeleteHeap(primaryCellPathHeap); cpDeleteHeap(secondaryCellPathHeap); deleteHeap(); deleteGraphAndMap(); }
int load_level( char map[MAP_HSIZE][MAP_WSIZE], int nlevel, gps* player, int* diamonds ){ *diamonds = 0; if( nlevel >= 1 && nlevel <= 11 ){ char file[30]; sprintf( file, "data/levels/%02i", nlevel ); if( !load_map( file, map ) ){ msgbox( "no-load level" ); return 0; } int i, ii; for(i = 0; i < MAP_HSIZE; i++) for(ii = 0; ii < MAP_WSIZE; ii++){ if( map[i][ii] == DIAMOND ) (*diamonds)++; if( map[i][ii] == PLAYER ){ player->y = i; player->x = ii; } } return 1; } else return 0; }
struct bogoman_map *bogoman_load(const char *path) { FILE *f = fopen(path, "r"); if (f == NULL) return NULL; unsigned int w, h; get_map_info(f, &w, &h); DEBUG(1, "Have map %ux%u\n", w, h); struct bogoman_map *map; size_t map_size; map_size = sizeof(struct bogoman_map) + w * h * sizeof(struct bogoman_map_elem); map = malloc(map_size); if (map == NULL) goto err0; memset(map, 0, map_size); map->w = w; map->h = h; load_map(f, map); return map; err0: fclose(f); return NULL; }
static int el_load_map(const char * file_name) { int ret; init_map_loading(file_name); ret = load_map(file_name, &updat_func); if (!ret) // don't try to build pathfinder maps etc. when loading // the map failed... return ret; if (strstr(file_name, "underworld") != NULL) { skybox_set_type(SKYBOX_UNDERWORLD); skybox_update_colors(); } else if (dungeon) { skybox_set_type(SKYBOX_NONE); skybox_update_colors(); } else { skybox_set_type(SKYBOX_CLOUDY); skybox_init_defs(file_name); } build_path_map(); init_buffers(); // reset light levels in case we enter or leave an inside map new_minute(); destroy_loading_win(); return ret; }
void init_game() { WINDOW* map_win = newwin(24, 80, 0, 0); WINDOW* area_win = newwin(6, 10, 0, 80); WINDOW* stats_win = newwin(8, 10, 6, 80); WINDOW* examine_win = newwin(10, 10, 14, 80); WINDOW* hp_win = newwin(1, 90, 24, 0); WINDOW* log_win = newwin(10, 90, 25, 0); dead = false; init_log(log_win); init_map(map_win); init_items(); world = calloc(LEVEL_COUNT, sizeof(map*)); world[0] = load_map("data/maps/farm.map", 78, 22, false, true); for(int i = 1; i < 3; ++i) world[i] = load_map("data/maps/easy_cave.map", 80 + 10 * (i - 1), 24 + 4 * (i - 1), true, true); for(int i = 3; i < 5; ++i) world[i] = load_map("data/maps/mid_cave.map", 80 + 10 * (i - 1), 24 + 4 * (i - 1), true, true); for(int i = 5; i < 7; ++i) world[i] = load_map("data/maps/hard_cave.map", 80 + 15 * (i - 1), 24 + 6 * (i - 1), true, true); for(int i =7; i < 9; ++i) world[i] = load_map("data/maps/crazy_cave.map", 80 + 18 * (i - 1), 24 + 8 * (i - 1), true, true); world[LEVEL_COUNT - 1] = load_map("data/maps/final.map", 78, 22, true, false); init_player(map_win, stats_win, hp_win, area_win, examine_win, world[0]); int x, y; get_random_empty_tile(&x, &y, world[LEVEL_COUNT - 1]); spawn_item(x, y, "data/items/cat.item", world[LEVEL_COUNT - 1]); get_random_empty_tile(&x, &y, world[0]); player_set_position(x, y); draw_map(x, y, world[0]); add_message(COLOR_DEFAULT, "@ symbol, a brave young farmer, was out for a stroll on his farm when his cat Cuddles ran down into the gaping starcase to the deadly Caves of Consternation! @ symbol had been meaning to patch that up for a while, but hadn't gotten a chance yet. Don't judge."); if(ask_question(COLOR_SELECTION, "Will you help @ symbol retrieve his cat, Cuddles?")) add_message(COLOR_HP_GOOD, "Excellent! Get to it, then!"); else { add_message(COLOR_HP_CRIT, "Well that was unexpected. Okay then, press q to quit to the main menu."); dead = true; } draw_log(); }
int main() { int exit_flag = 0, i; MAT16F tmat, modelmat; VEC3F pos = vec3f(0.0, 0.0, 0.5), ang = vec3f(0.0, 0.0, 0.0); int vnum, snum; VEC2F *map_vec2f; WALL_SEGMENT *map_segment; VERTEX *map_vertex; MD2_MODEL mdl; VERTEX *model_verts; TRI *model_tris; VERTEX floor[4]; floor[0].local = vec3f(-200.0, 0.0, 200.0); floor[1].local = vec3f(200.0, 0.0, 200.0); floor[2].local = vec3f(200.0, 0.0, -200.0); floor[3].local = vec3f(-200.0, 0.0, -200.0); NODE *head = NULL; init(); if(load_md2("data/babe.md2", &mdl)) { allegro_message("Error: I need the MD2 model, stupid!"); exit(1); } convert_md2_to_base(&model_verts, &model_tris, &mdl, 0.2); load_map("map.txt", &map_vec2f, &map_segment, &vnum, &snum, 1.0); head = (NODE *)malloc(sizeof(NODE)); head->val = val; head->a = map_segment[0].a; head->b = map_segment[0].b; head->n = NORMALIZED_NORMAL_VEC2F(map_vec2f[map_segment[0].a], map_vec2f[map_segment[0].b]); head->parent = NULL; head->left = NULL; head->right = NULL; val++; for(i = 1; i < snum; i++) { add_node(head, &val, map_segment[i].a, map_segment[i].b, &map_vec2f, &vnum); val++; } map_vertex = (VERTEX *)malloc(vnum * 2 * sizeof(VERTEX)); for(i = 0; i < vnum; i++) { map_vertex[i * 2].local = USCALE_VEC3F(vec3f(map_vec2f[i].x, 0.0, map_vec2f[i].y), 0.2); map_vertex[i * 2 + 1].local = USCALE_VEC3F(vec3f(map_vec2f[i].x, WALL_HEIGHT, map_vec2f[i].y), 0.2); map_vec2f[i] = USCALE_VEC2F(map_vec2f[i], 0.2); } LOCK_VARIABLE(fps); LOCK_VARIABLE(frame_count); LOCK_FUNCTION(update_fps); install_int(update_fps, 1000); float frame = 0.0; VEC3F cam_pos = vec3f(0.0, 3.0, 0.0), cam_dir, cam_dir_normal, cam_ang = vec3f(0.0, 0.0, 0.0); while(!exit_flag) { set_texture_mapping_mode(0); int mx, my; get_mouse_mickeys(&mx, &my); position_mouse(SCREEN_W / 2, SCREEN_H / 2); cam_ang.x += my * 0.001; cam_ang.y -= mx * 0.001; cam_dir.x = SPEED * cos(0.5 * M_PI + cam_ang.y); cam_dir.y = 0.0; cam_dir.z = SPEED * sin(0.5 * M_PI + cam_ang.y); cam_dir_normal = vec3f(-cam_dir.z, 0.0, cam_dir.x); if(key[KEY_ESC]) { exit_flag = 1; } if(key[KEY_W]) { cam_pos = VEC3F_SUM(cam_pos, cam_dir); } if(key[KEY_S]) { cam_pos = VEC3F_DIFF(cam_pos, cam_dir); } if(key[KEY_A]) { cam_pos = VEC3F_SUM(cam_pos, cam_dir_normal); } if(key[KEY_D]) { cam_pos = VEC3F_DIFF(cam_pos, cam_dir_normal); } //if(key[KEY_SPACE]) { set_texture_mapping_mode(1); } reset_mat16f(tmat); translate_mat16f(tmat, -cam_pos.x, -cam_pos.y, -cam_pos.z); rotate_mat16f(tmat, -cam_ang.x, -cam_ang.y, 0.0); convert_md2_frame_to_base(model_verts, &mdl, frame, 0.2); frame += 0.1; reset_mat16f(modelmat); rotate_mat16f(modelmat, M_PI * 1.5, 0.0, 0.0); translate_mat16f(modelmat, 0.0, 5.0, 0.0); translate_mat16f(modelmat, -cam_pos.x, -cam_pos.y, -cam_pos.z); rotate_mat16f(modelmat, -cam_ang.x, -cam_ang.y, 0.0); for(i = 0; i < vnum * 2; i++) transform_vec3f(&map_vertex[i].world, map_vertex[i].local, tmat); for(i = 0; i < 4; i++) transform_vec3f(&floor[i].world, floor[i].local, tmat); for(i = 0; i < mdl.header.num_vertices; i++) transform_vec3f(&model_verts[i].world, model_verts[i].local, modelmat); clear_bitmap(buffer); clear_to_color(zbuffer, ZBUFFER_PRECISION); bind_texture(texture); VEC2F p = vec2f(cam_pos.x, cam_pos.z); VEC2F v = vec2f(cam_dir.x, cam_dir.z); traverse_tree(head, p, v, map_vec2f, map_vertex); bind_texture(skin); for(i = 0; i < mdl.header.num_tris; i++) { update_tri_normal(&model_tris[i], model_verts); model_tris[i].n = NORMALIZED_VEC3F(model_tris[i].n); if(cull_backface(&model_tris[i], model_verts)) render_tri(&model_tris[i], model_verts); } bind_texture(texture2); TRI temp; temp.a = 0; temp.b = 1; temp.c = 2; temp.tex[0] = vec2f(0.0, 0.0); temp.tex[1] = vec2f(20.0, 0.0); temp.tex[2] = vec2f(20.0, 20.0); render_tri(&temp, floor); temp.a = 2; temp.b = 3; temp.c = 0; temp.tex[0] = vec2f(20.0, 20.0); temp.tex[1] = vec2f(20.0, 0.0); temp.tex[2] = vec2f(0.0, 0.0); render_tri(&temp, floor); textprintf_ex(buffer, font, 10, 10, makecol(255, 255, 255), 0, "FPS: %d", fps); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); frame_count++; } destroy_bitmap(texture2); destroy_tree(head); free_md2(&mdl); free(model_tris); free(model_verts); free(map_vertex); free(map_vec2f); free(map_segment); destroy_bitmap(skin); destroy_bitmap(texture); destroy_bitmap(zbuffer); destroy_bitmap(buffer); deinit_renderer(); return 0; }
void known_load_map(map_t* map, char *word) { if (find_map(s_known_words, word)) { load_map(map, word); } }
void clcmd_map(int s, char *arg) { if ( arg ) load_map(arg); }
int main() { unsigned char pMap[] = { 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1 }; int pOutBuffer[12]; auto a_star_res = A_Star::FindPath(0, 0, 1, 2, pMap, 4, 3, pOutBuffer, 12); unsigned char pMap2[] = { 0, 0, 1, 0, 1, 1, 1, 0, 1 }; int pOutBuffer2[7]; //auto res2 = FindPath(2, 0, 0, 2, pMap2, 3, 3, pOutBuffer2, 7); unsigned char pMap3[] = { 1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,1, 1,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1 }; int pOutBuffer3[50]; //auto res3 = FindPath(0, 0, 9, 4, pMap3, 10, 5, pOutBuffer3, 20); unsigned char pMap5[] = { 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1 }; int pOutBuffer5[12]; //auto res5 = FindPath(0, 0, 1, 2, pMap5, 4, 3, pOutBuffer5, 12); unsigned char pMap7[] = { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1 }; int pOutBuffer7_1[12]; int pOutBuffer7_2[12]; unsigned char huge_map_500[500*500]; load_map("500_500.txt", huge_map_500); int pOutBuffer_500[2000]; unsigned char huge_map_750[750 * 750]; load_map("750_750.txt", huge_map_750); int pOutBuffer_750[2000]; //unsigned char huge_map_1000[1000 * 1000]; //load_map("1000_1000.txt", huge_map_1000); //int pOutBuffer_1000[2000]; auto res_500 = FindPath(10, 10, 24, 24, huge_map_500, 25, 25, pOutBuffer_500, 2000); auto res_750 = FindPath(0, 0, 749, 749, huge_map_750, 750, 750, pOutBuffer_750, 3000); //auto res_1000 = FindPath(0, 0, 999, 999, huge_map_1000, 1000, 1000, pOutBuffer_1000, 2000); constexpr int width = 100; constexpr int height = 100; int size = width * height; int pOutBuffer_X[10000]; unsigned char map_X[width * height]; std::fill_n(map_X, size, 0x01); std::random_device rd; // only used once to initialise (seed) engine std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case) std::uniform_int_distribution<int> uni(0, height - 1); // guaranteed unbiased auto rand_x = uni(rng); auto rand_y = uni(rng); auto target_x = uni(rng); auto target_y = uni(rng); auto res_x = A_Star::FindPath(0, 0, width - 1, height - 1, map_X, width, height, pOutBuffer_X, 10000); //for (int i = 0; i < 10; ++i) //{ // rand_x = uni(rng); // rand_y = uni(rng); // target_x = uni(rng); // target_y = uni(rng); // res_x = FindPath(rand_x, rand_y, target_x, target_y, map_X, width, height, pOutBuffer_X, 10000); // std::cout << "Rand " << rand_x << " " << rand_y << " Target >> " << target_x << " " << target_y; // if (res_x != -1) // { // std::cout << " Found!" << std::endl; // } // else // { // std::cout << " No path!" << std::endl; // } //} unsigned char forum_map[] = { 0,0,0,0,0,1,0,0,0, 0,0,0,0,0,1,0,0,0, 0,1,1,1,1,1,1,1,0, 0,1,0,0,0,0,0,1,0, 0,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0 }; unsigned char forum_map_mirrored[] = { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int forum_normal[20]; int forum_mirrored[20]; auto forum_normal_res = A_Star::FindPath(4, 4, 5, 0, forum_map, 9, 6, forum_normal, 20); auto forum_mirrrored_res = FindPath(4, 4, 3, 0, forum_map_mirrored, 9, 6, forum_mirrored, 20); unsigned char cross[] = { 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1 }; int cross_out[10]; int cross_out_two[10]; unsigned char pattern_one[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 }; int pattern_one_out[50]; int pattern_one_out_two[50]; auto cross_res = A_Star::FindPath(0, 0, 4, 4, cross, 5, 5, cross_out, 20); auto cross_res_mirrored = FindPath(4, 4, 0, 0, cross, 5, 5, cross_out_two, 20); assert(cross_res == cross_res_mirrored); auto pattern_res = A_Star::FindPath(0, 6, 4, 3, pattern_one, 7, 7, pattern_one_out, 50); auto pattern_res_mirrored = A_Star::FindPath(4, 3, 0, 6, pattern_one, 7, 7, pattern_one_out_two, 50); assert(pattern_res == pattern_res_mirrored); unsigned char turn_test[] = { 1,1,1,1,1,0,1,1, 0,1,0,0,1,0,1,0, 1,1,0,1,1,0,1,1, 1,0,0,1,0,0,0,1, 1,1,0,1,1,0,1,1, 0,1,0,0,1,0,1,0, 1,1,0,1,1,0,1,1, 1,0,0,1,0,0,0,1, 1,1,0,1,1,1,1,1 }; int turn_test_buffer[50]; auto turn_test_res = A_Star::FindPath(3, 4, 1, 8, turn_test, 8, 9, turn_test_buffer, 50); unsigned char fail_test[] = { 0,1,1,1,0, 0,1,0,1,0, 0,0,1,1,0, 1,1,1,0,1 }; int shit_buffer[10]; int shit_buffer2[10]; auto fail_test_2 = A_Star::FindPath(0, 3, 1, 1, fail_test, 5, 4, shit_buffer2, 10); auto fail_test_1 = A_Star::FindPath(0, 3, 1, 1, fail_test, 5, 4, shit_buffer, 5); //TestEdgeCases(); TestInvalidLongPath(); TestInvalidPath(); TestValidLongPath(); TestValidOnePath(); TestValidPath(); unsigned char same_length_test[] = { 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1 }; int same_length_buffer[100]; int same_length_buffer_two[100]; auto res6 = A_Star::FindPath(0, 0, 1, 2, pMap5, 4, 3, pOutBuffer5, 12); assert(res6 == 3); auto res7 = A_Star::FindPath(3, 2, 0, 0, pMap7, 4, 3, pOutBuffer7_1, 12); assert(res7 == 5); auto res7_1 = A_Star::FindPath(0, 0, 3, 2, pMap7, 4, 3, pOutBuffer7_2, 12); assert(res7_1 == 5); auto res8 = A_Star::FindPath(2, 0, 0, 2, pMap2, 3, 3, pOutBuffer2, 12); assert(res8 == -1); auto res9 = A_Star::FindPath(9, 4, 0, 0, pMap3, 10, 5, pOutBuffer3, 5); assert(res9 == 31); auto res10 = A_Star::FindPath(0, 0, 9, 4, pMap3, 10, 5, pOutBuffer3, 5); int same_length_res = A_Star::FindPath(0, 0, 5, 5, same_length_test, 6, 6, same_length_buffer, 100); //This one has two paths -> One long one short, must overlap at some point and are overwriting their previous parents. int same_length_res_opposite = A_Star::FindPath(5, 5, 0, 0, same_length_test, 6, 6, same_length_buffer_two, 100); //Index 3 & 9 are looping -> Must be where they overlap? assert(same_length_res == same_length_res_opposite); unsigned char git_test[] = { 1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,0,0,0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1, 1,1,0,0,0,0,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 4 0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, // 10 1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, // 15 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1, // 20 1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 24 }; print_map(git_test, 39, 25, 21, 20, 0, 0); int git_buffer[200]; int git_buffer_2[200]; int git_buffer_3[200]; int git_buffer_4[200]; int git_buffer_5[200]; int git_buffer_6[200]; int git_buffer_7[200]; int git_buffer_8[200]; auto git_buffer_res = A_Star::FindPath(0, 0, 20, 20, git_test, 39, 25, git_buffer, 200); //Should be 154 auto git_buffer_res_1 = A_Star::FindPath(20, 20, 0, 0, git_test, 39, 25, git_buffer_2, 200); //Should be 154 assert(git_buffer_res == git_buffer_res_1); auto git_buffer_res_2 = A_Star::FindPath(38, 0, 0, 24, git_test, 39, 25, git_buffer_3, 200); //Should be 62 auto git_buffer_res_3 = A_Star::FindPath(0, 24, 38, 0, git_test, 39, 25, git_buffer_4, 200); //Should be 62 assert(git_buffer_res_2 == git_buffer_res_3); auto north = A_Star::FindPath(19, 0, 19, 24, git_test, 39, 25, git_buffer_5, 200); //Should be 60 auto south = A_Star::FindPath(19, 24, 19, 0, git_test, 39, 25, git_buffer_6, 200); //Should be 60 assert(north == south); auto east = A_Star::FindPath(0, 12, 38, 12, git_test, 39, 25, git_buffer_7, 200); //Should be 78 auto west = A_Star::FindPath(38, 12, 0, 12, git_test, 39, 25, git_buffer_8, 200); //Should be 78 assert(east == west); assert(git_buffer_res == 154); assert(git_buffer_res_1 == 154); int short_test_buffer_north[15]; int short_test_buffer_east[15]; int short_test_buffer_south[15]; int short_test_buffer_west[15]; unsigned char short_test[] = { 1,1,1,1,1, 1,0,0,0,1, 1,0,0,0,1, 1,0,0,0,1, 1,0,0,0,1, 1,0,0,0,1, 1,0,0,1,1, 1,0,0,1,0, 1,0,0,1,1, 1,0,0,0,1, 1,1,1,1,1 }; //5 width 10 auto final_test_north = A_Star::FindPath(2, 0, 2, 10, short_test, 5, 11, short_test_buffer_north, 50); auto final_test_east = A_Star::FindPath(4, 5, 0, 5, short_test, 5, 11, short_test_buffer_east, 50); auto final_test_south = A_Star::FindPath(2, 10, 2, 0, short_test, 5, 11, short_test_buffer_south, 50); auto final_test_west = A_Star::FindPath(0, 5, 4, 5, short_test, 5, 11, short_test_buffer_west, 50); assert(final_test_north == 14); assert(final_test_south == 14); assert(final_test_east == 14); assert(final_test_west == 14); const unsigned char filkry_map[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //starts at 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //10 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, //20 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, //30 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, //40 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, //50 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, //60 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, //70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //90 }; int filkry_buffer_one[20]; int filkry_buffer_two[20]; int filkry_buffer_three[20]; int filkry_buffer_four[20]; //Should be 11 auto filkry_res = A_Star::FindPath(4, 8, 4, 1, filkry_map, 10, 10, filkry_buffer_one, 20); auto filkry_res_2 = A_Star::FindPath(4, 1, 4, 8, filkry_map, 10, 10, filkry_buffer_two, 20); assert(filkry_res == 11); assert(filkry_res_2 == 11); //should be 17 (Works normal but not mirrored) auto f_2 = A_Star::FindPath(5, 3, 4, 1, filkry_map, 10, 10, filkry_buffer_three, 20); auto f_3 = A_Star::FindPath(4, 1, 5, 3, filkry_map, 10, 10, filkry_buffer_four, 20); assert(f_2 == 17); assert(f_3 == 17); unsigned char another_test[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; int another_test_buffer[14]; auto sigh_res = A_Star::FindPath(2, 3, 7, 3, another_test, 8, 7, another_test_buffer, 14); unsigned char other_git_map[] = { 1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 4 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 10 1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 15 1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 20 };// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 std::vector<int> res; res.resize(600); int start_x = 0; int start_y = 0; int tgt_x = 32; int tgt_y = 2; int rv = A_Star::FindPath(start_x, start_y, tgt_x, tgt_y, other_git_map, 39, 20, res.data(), res.size()); unsigned char big_map_10[] = { 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,0, 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; int big_map_buffer[100]; int big_map_buffer_mirrored[100]; int big_map_buffer_other[100]; int big_map_a_star[100]; auto big_map_res = A_Star::FindPath(1, 1, 35, 12, big_map_10, 39, 22, big_map_buffer, 256); auto big_map_res_mirrored = A_Star::FindPath(35, 12, 1, 1, big_map_10, 39, 22, big_map_buffer_mirrored, 256); auto a_star_big = A_Star::FindPath(1, 1, 35, 12, big_map_10, 39, 22, big_map_a_star, 256); std::cout << "Return (should be 95): " << big_map_res << "\n" << "pOutBuffer: "; for (int i = 0; i < big_map_res && i < 256; i++) std::cout << big_map_buffer[i] << " "; std::cout << "\n\n"; std::cout << "Return (should be 95): " << a_star_big << "\n" << "pOutBuffer: "; for (int i = 0; i < a_star_big && i < 256; i++) std::cout << big_map_a_star[i] << " "; std::cout << "\n\n"; for (int i = 0; i < a_star_big; ++i) { if (big_map_a_star[i] != big_map_buffer_other[i]) { auto ok = true; } } TestEdgeCases(); TestInvalidLongPath(); TestInvalidPath(); TestValidLongPath(); TestValidOnePath(); return 0; }
void main_init() { int i; float starting_speed = 0.0; init_robot(); flag = 0; robot_state = malloc(sizeof (float) *3); for (i = 0; i < LEN_PIC_BUFFER; i++) { set_vel_2_array(pic_buffer[i], starting_speed, starting_speed); } write(pic_fd, pic_message_reset_steps_acc, PACKET_TIMING_LENGTH + 1); tcflush(pic_fd, TCOFLUSH); sync(); steps_anomaly = 0; #ifdef TEST_KALMAN float v=0; float w=0; set_robot_speed(&v,&w); #endif #ifdef OB_AV init_probstavoid_module(); #endif #ifdef CARTESIAN_REGULATOR viapoints[0][0]=38; viapoints[0][1]=119; viapoints[0][2]=0; viapoints[1][0]=98; viapoints[1][1]=161; viapoints[1][2]=0; viapoints[2][0]=187; viapoints[2][1]=179; viapoints[2][2]=0; viapoints[3][0]=158; viapoints[3][1]=238; viapoints[3][2]=0; viapoints[4][0]=187; viapoints[4][1]=268; viapoints[4][2]=0; curr_via=0; via_done=0; #endif #ifdef HOKUYO init_urg_laser(&urg,ON_DEMAND); #endif #ifdef JOYSTICK init_joystick(); #endif #ifdef EKF_LOC load_map("ekf_map.txt"); init_ekf(); #ifdef HOKUYO_SENSOR for (i=0; i< NUM_SENS; i++){ ANGLE_IDX[i]=urg_rad2index(urg,ANGLE_H[i]); printf("angle: %f \tidx: %d\n",ANGLE_H[i],urg_rad2index(urg,ANGLE_H[i])); } #endif xpost.x=50; xpost.y=45; xpost.th=M_PI/2; xpred.x=0; xpred.y=0; xpred.th=0; #endif }
int main(){ //setup log file fpLog = fopen("log.txt", "w"); if(fpLog == NULL){ printf("Failed to open log file\n"); } //seed random srand(time(NULL)); //set up frame limiting clock_t s_cycle, e_cycle; s_cycle = clock(); //get amount of time to init game fprintf(fpLog, "Initializing...\n"); //log allegro_init_install(); //allegro inits Game game; game_init(&game); //initialize game struct TMX_map map; load_map(&game, &map); //load first map Sprite player, car; player_init(&game, &player, &map); //initialize player struct car_init(&game, &car, &map, 32, 32, 5); //initialize car struct gen_npcs(&game, &map); //generate and initialize npcs e_cycle = clock(); //get length of initialization fprintf(fpLog, "Initialization done in %f seconds.\n", (double)(e_cycle - s_cycle) / 1000); //show instructions on how to play display_instructions(&game); //set active sprite game.active_sprite = &player; fprintf(fpLog, "Beginning main loop.\n"); while(game.running){ //to limit frames we have a set refresh rate //to maintain this refresh rate we subtract the //time elapsed over the entire cycle //to do this we get the time at the start of the cycle //and the end to get the difference s_cycle = clock(); //exit sequence exit_sequence(&game); //check if we enter the car enter_car(&game, &player, &car, &map); //toggle debugging if(key[KEY_F1] && !game.debug_cd){ game.debug = !game.debug; printf(game.debug ? "DEBUGGING ENABLED\n" : "DEBUGGING DISABLED\n"); game.debug_cd = 10; }else{ game.debug_cd -= game.debug_cd ? 1 : 0; } //resets game if(key[KEY_F5]){ game_init(&game); load_map(&game, &map); player_init(&game, &player, &map); //initialize player struct car_init(&game, &car, &map, 32, 32, 5); gen_npcs(&game, &map); } //toggle music if(key[KEY_M]){ game.music ? stop_sample(game.bgMusic) : play_sample(game.bgMusic, 255, 128, 1000, 1); } //clear buffer clear_to_color(game.buffer, makecol(0, 0, 0)); //show map masked_blit(map.map, game.buffer, game.cam_x, game.cam_y, 0, 0, game.screen_w, game.screen_h); //pan camera pan_camera(&game); //do mouse click mouse_click(&game, game.active_sprite); npc_sequence(&game, &map); //display the player if we're not in the car if (!game.in_car){ sprite_sequence(&game, &player, &map, !game.in_car); if (key[KEY_SPACE] && !player.bullet_cd){ sprite_shoot(&game, &player); player.bullet_cd = 10; }else{ player.bullet_cd -= player.bullet_cd ? 1 : 0; } }else{ free(player.bullets); player.bullets = NULL; player.bullet_count = 0; } //show car sprite_sequence(&game, &car, &map, game.in_car); //display all overlays blit_overlays(&game); //show hud show_hud(&game, &player); //display buffer to screen stretch_blit(game.buffer, screen, 0, 0, game.buffer->w, game.buffer->h, 0, 0, game.screen_w * STRETCH_FACTOR, game.screen_h * STRETCH_FACTOR); //countdown timer game_tick(&game, &map); e_cycle = clock(); /*maintain consistent framerate by calculating delay of processing, using max because we don't want negative rest*/ printf("\rIteration took %f%20s", (double) (e_cycle - s_cycle), " "); rest(max(game.delay - (double) (e_cycle - s_cycle), 0)); } fprintf(fpLog, "Running exit scripts...\n"); //destroy all bitmaps destroy_bitmaps(&game, &player, &map, &car); fprintf(fpLog, "Exiting...\n"); return 0; }END_OF_MAIN();
void CGame::init_game(char *mapname) { CObject *o; game_timmer=0; game_state=0; start_delay=default_start_delay; if (!load_map(mapname)) throw; init_quick_tables(); char TANGLEWO_FONT_PATH[256]; insert_rootdir_prefix("fonts/tanglewo.ttf", TANGLEWO_FONT_PATH); font=TTF_OpenFont(TANGLEWO_FONT_PATH,16); player1_car=IMG_Load("graphics/car1.bmp"); player2_car=IMG_Load("graphics/car2.bmp"); player_tiles.Add(new CTile(0,0,32,32,player1_car,true)); player_tiles.Add(new CTile(0,32,32,32,player1_car,true)); player_tiles.Add(new CTile(0,64,32,32,player1_car,true)); player_tiles.Add(new CTile(0,96,32,32,player1_car,true)); player_tiles.Add(new CTile(0,128,32,32,player1_car,true)); player_tiles.Add(new CTile(0,160,32,32,player1_car,true)); player_tiles.Add(new CTile(0,192,32,32,player1_car,true)); player_tiles.Add(new CTile(0,224,32,32,player1_car,true)); player_tiles.Add(new CTile(0,256,32,32,player1_car,true)); player_tiles.Add(new CTile(0,0,32,32,player2_car,true)); player_tiles.Add(new CTile(0,32,32,32,player2_car,true)); player_tiles.Add(new CTile(0,64,32,32,player2_car,true)); player_tiles.Add(new CTile(0,96,32,32,player2_car,true)); player_tiles.Add(new CTile(0,128,32,32,player2_car,true)); player_tiles.Add(new CTile(0,160,32,32,player2_car,true)); player_tiles.Add(new CTile(0,192,32,32,player2_car,true)); player_tiles.Add(new CTile(0,224,32,32,player2_car,true)); player_tiles.Add(new CTile(0,256,32,32,player2_car,true)); enemy_cars=IMG_Load("graphics/enemycars.bmp"); enemy_tiles.Add(new CTile(0,0,32,32,enemy_cars,true)); enemy_tiles.Add(new CTile(0,32,32,32,enemy_cars,true)); enemy_tiles.Add(new CTile(0,64,32,32,enemy_cars,true)); enemy_tiles.Add(new CTile(0,96,32,64,enemy_cars,true)); fuel_sfc=IMG_Load("graphics/fuel.bmp"); if (start_delay!=default_start_delay) { /* There is a SEMAPHORE */ o=new CEnemyRacerCarObject((dx/2)-30,dy-176,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)+14,dy-176,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)-30,dy-224,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)+14,dy-224,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)-30,dy-272,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)+14,dy-272,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)-30,dy-320,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)+14,dy-320,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)-30,dy-368,enemy_tiles[0],start_delay,this); objects.Add(o); o=new CEnemyRacerCarObject((dx/2)+14,dy-368,enemy_tiles[0],start_delay,this); objects.Add(o); } /* if */ empty_sfc=IMG_Load("graphics/empty.bmp"); fuelscores_sfc=IMG_Load("graphics/fuel_scores.bmp"); // start_sfc=IMG_Load("graphics/start.bmp"); checkpoint_sfc=IMG_Load("graphics/checkpoint.bmp"); goal_sfc=IMG_Load("graphics/goal.bmp"); obstacles_sfc=IMG_Load("graphics/obstacles.bmp"); pause_sfc=IMG_Load("graphics/pause.bmp"); explosion_sfc=IMG_Load("graphics/explosion.bmp"); extra_tiles.Add(new CTile(0,0,32,32,fuel_sfc,true)); /* 0 */ extra_tiles.Add(new CTile(0,0,empty_sfc->w/2,empty_sfc->h,empty_sfc,false)); /* 1 */ extra_tiles.Add(new CTile(0,0,fuelscores_sfc->w/2,fuelscores_sfc->h/4,fuelscores_sfc,false)); extra_tiles.Add(new CTile(0,fuelscores_sfc->h/4,fuelscores_sfc->w/2,fuelscores_sfc->h/4,fuelscores_sfc,false)); extra_tiles.Add(new CTile(0,fuelscores_sfc->h/2,fuelscores_sfc->w/2,fuelscores_sfc->h/4,fuelscores_sfc,false)); extra_tiles.Add(new CTile(0,3*(fuelscores_sfc->h/4),fuelscores_sfc->w/2,fuelscores_sfc->h/4,fuelscores_sfc,false)); extra_tiles.Add(new CTile(0,0,obstacles_sfc->w/3,obstacles_sfc->h/3,obstacles_sfc,true)); /* 6 */ extra_tiles.Add(new CTile(0,(obstacles_sfc->h/3),obstacles_sfc->w/3,obstacles_sfc->h/3,obstacles_sfc,true)); extra_tiles.Add(new CTile(0,2*(obstacles_sfc->h/3),obstacles_sfc->w/3,obstacles_sfc->h/3,obstacles_sfc,true)); extra_tiles.Add(new CTile(0,0,pause_sfc->w/2,pause_sfc->h,pause_sfc,false)); /* 9 */ extra_tiles.Add(new CTile(0,0,checkpoint_sfc->w/2,checkpoint_sfc->h,checkpoint_sfc,false)); /* 10 */ extra_tiles.Add(new CTile(0,0,goal_sfc->w/2,goal_sfc->h,goal_sfc,false)); /* 11 */ explosion_tiles.Add(new CTile(0,0,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,64,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,128,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,192,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,256,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,320,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,384,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,448,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,512,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,576,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,640,64,64,explosion_sfc,false)); explosion_tiles.Add(new CTile(0,704,64,64,explosion_sfc,false)); MAX_FUEL=2500; FUEL_RECHARGE=400; FUEL_LOSS=225; CAR_INTERVAL=38; if (game_mode==1) { MAX_FUEL=1800; FUEL_RECHARGE=300; FUEL_LOSS=150; CAR_INTERVAL=24; } /* if */ if (game_mode==2) { MAX_FUEL=1300; FUEL_RECHARGE=275; FUEL_LOSS=75; CAR_INTERVAL=16; } /* if */ if (game_mode==3) { MAX_FUEL=1250; FUEL_RECHARGE=200; FUEL_LOSS=100; CAR_INTERVAL=12; } /* if */ S_takefuel=Sound_create_sound("sd:/apps/roadfighter-wii/sound/takefuel.wav"); S_redlight=Sound_create_sound("sd:/apps/roadfighter-wii/sound/redlight.wav"); S_greenlight=Sound_create_sound("sd:/apps/roadfighter-wii/sound/greenlight.wav"); S_crash=Sound_create_sound("sd:/apps/roadfighter-wii/sound/car_crash.wav"); S_carstart=Sound_create_sound("sd:/apps/roadfighter-wii/sound/car_start.wav"); S_fuelempty=Sound_create_sound("sd:/apps/roadfighter-wii/sound/fuelempty.wav"); S_caradvance=Sound_create_sound("sd:/apps/roadfighter-wii/sound/car_pass.wav"); S_carengine=Sound_create_sound("sd:/apps/roadfighter-wii/sound/car_running.wav"); S_carskid=Sound_create_sound("sd:/apps/roadfighter-wii/sound/car_brake.wav"); S_water=Sound_create_sound("sd:/apps/roadfighter-wii/sound/water.wav"); S_collision=Sound_create_sound("sd:/apps/roadfighter-wii/sound/collision.wav"); S_truck=Sound_create_sound("sd:/apps/roadfighter-wii/sound/truck.wav"); fastcar_counter=0; esc_pressed=false; backspace_pressed=false; paused=false; } /* CGame::init_game */
SPWAW_ERROR snapload (int fd, SPWAW_SNAPSHOT *dst, STRTAB *stabptr) { SPWAW_ERROR rc = SPWERR_OK; STRTAB *stab = stabptr; long pos; SNAP_HEADER mhdr; SNAP_SOURCE shdr; SNAP_INFO ihdr; SNAP snap; CBIO cbio; CNULLARG (dst); if (!stabptr) stab = (STRTAB *)dst->stab; pos = bseekget (fd); memset (&snap, 0, sizeof (snap)); rc = snaploadhdrs (fd, &mhdr, &shdr, &ihdr); ERRORGOTO ("snaploadhdrs()", handle_error); if (mhdr.oobdat) { rc = SPWOOB_new (&(dst->oobdat)); ERRORGOTO ("SPWOOB_new()", handle_error); dst->freeoobdat = true; bseekset (fd, pos + mhdr.oobdat); rc = SPWOOB_load (dst->oobdat, fd); ERRORGOTO ("SPWOOB_load()", handle_error); } if (!stabptr) { bseekset (fd, pos + mhdr.stab); rc = STRTAB_fdload (stab, fd); ERRORGOTO ("STRTAB_fdload()", handle_error); } dst->src.path = STRTAB_getstr (stab, shdr.path); dst->src.file = STRTAB_getstr (stab, shdr.file); dst->src.date = *((FILETIME *)&(shdr.date)); bseekset (fd, mhdr.snap.data + pos); /* We are now backwards compatible with version 11 and older */ if (mhdr.version <= SNAP_VERSION_V11) { rc = snapshot_load_v11_snap (fd, &mhdr, &snap); ROE ("snapshot_load_v11_snap(snapshot game data)"); } else { cbio.data = (char *)&snap; cbio.size = mhdr.snap.size; cbio.comp = &(mhdr.snap.comp); if (!cbread (fd, cbio, "snapshot game data")) FAILGOTO (SPWERR_FRFAILED, "cbread(snapshot game data) failed", handle_error); } load_snap (&snap, stab, dst); bseekset (fd, pos + mhdr.map); rc = load_map (fd, &(dst->raw.game.map)); ERRORGOTO ("load_map(map)", handle_error); bseekset (fd, pos + mhdr.oobp1); rc = load_oob (fd, &(dst->raw.OOBp1), stab, mhdr.version); ERRORGOTO ("load_oob(oobP1)", handle_error); bseekset (fd, pos + mhdr.oobp2); rc = load_oob (fd, &(dst->raw.OOBp2), stab, mhdr.version); ERRORGOTO ("load_oob(OOBp2)", handle_error); dst->type = (SPWAW_BATTLE_TYPE)ihdr.type; return (SPWERR_OK); handle_error: snapclean (dst, stabptr); return (rc); }
int main() { int exit = 0, i, j; VEC3F pos = vec3f(0.0, 0.0, 1.0), ang = ZERO_VEC3F; MAT16F mat; int vnum, pnum; VERTEX *vertex; POLY3D *poly; init(); load_map("quake_map.txt", &vertex, &poly, &vnum, &pnum, (1.0 / 1000.0)); //printf("%d", poly[144].vind[0]); while(!exit) { if(key[KEY_ESC]) { exit = 1; } if(key[KEY_LEFT]) { pos.x -= MOTION_SPEED; } if(key[KEY_RIGHT]) { pos.x += MOTION_SPEED; } if(key[KEY_UP]) { pos.z += MOTION_SPEED; } if(key[KEY_DOWN]) { pos.z -= MOTION_SPEED; } ang.x += 0.01; ang.y += 0.01; ang.z += 0.01; reset_mat16f(mat); rotate_x_mat16f(mat, ang.x); rotate_y_mat16f(mat, ang.y); rotate_z_mat16f(mat, ang.z); translate_mat16f(mat, pos.x, pos.y, pos.z); for(i = 0; i < vnum; i++) { transform_vec3f(&vertex[i].trans, vertex[i].object, mat); project_vertex(&vertex[i]); } clear_to_color(buffer, 0); /* for(i = 0; i < vnum; i++) if(vertex[i].trans.z > 0.01) putpixel(buffer, vertex[i].sx, vertex[i].sy, makecol(255, 255, 255)); */ for(i = 0; i < pnum; i++) { for(j = 0; j < poly[i].vnum / 3; j++) { line(buffer, vertex[poly[i].vind[j * 3]].sx, vertex[poly[i].vind[j * 3]].sy, vertex[poly[i].vind[j * 3 + 1]].sx, vertex[poly[i].vind[j * 3 + 1]].sy, makecol(255, 255, 255)); line(buffer, vertex[poly[i].vind[j * 3 + 1]].sx, vertex[poly[i].vind[j * 3 + 1]].sy, vertex[poly[i].vind[j * 3 + 2]].sx, vertex[poly[i].vind[j * 3 + 2]].sy, makecol(255, 255, 255)); line(buffer, vertex[poly[i].vind[j * 3 + 2]].sx, vertex[poly[i].vind[j * 3 + 2]].sy, vertex[poly[i].vind[j * 3]].sx, vertex[poly[i].vind[j * 3]].sy, makecol(255, 255, 255)); } } blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); } for(i = 0; i < pnum; i++) free(poly[i].vind); free(poly); free(vertex); deinit_engine(); return 0; }
Mapdata::Mapdata() { load_map(); } // Mapdata()
int main() { SIrrlichtCreationParameters pars; pars.DriverType=EDT_OPENGL; pars.WindowSize=dimension2d<s32>(800,600); pars.Bits=32; pars.AntiAlias=true; pars.Stencilbuffer=true; pars.Doublebuffer = true; pars.Fullscreen=false; pars.Vsync=false; pars.EventReceiver=&receiver; device = createDeviceEx(pars); //device = createDevice(EDT_OPENGL, dimension2d<u32>(800, 600), 32, false, false, false, &receiver); if (!device) return 1; driver = device->getVideoDriver(); driver->setTextureCreationFlag(ETCF_ALWAYS_32_BIT, true); smgr = device->getSceneManager(); smgr->setShadowColor(SColor(127,0,0,0)); load_map(); load_player(); int fps = 0; int prev_fps = -1; stringw the_title; camera = smgr->addCameraSceneNode();//FPS(); camera->setPosition(vector3df(-50,50,-150)); device->getCursorControl()->setVisible(false); then = device->getTimer()->getTime(); while(device->run()) { now = device->getTimer()->getTime(); //check_input(); then = now; driver->beginScene(true, true, SColor(255, 255, 255, 255)); smgr->drawAll(); driver->endScene(); fps = driver->getFPS(); if (fps != prev_fps) { the_title = L"The Game | "; the_title += driver->getName(); the_title += " | FPS:"; the_title += fps; device->setWindowCaption(the_title.c_str()); } } device->drop(); return 0; }
t3_bool t3_highlight_detect(const char *line, size_t line_length, t3_bool first, int flags, t3_highlight_lang_t *lang, t3_highlight_error_t *error) { const char *error_message; int error_offset; int ovector[30]; pcre *pcre; if (line == NULL || lang == NULL) { if (error != NULL) error->error = T3_ERR_BAD_ARG; return t3_false; } lang->name = NULL; lang->lang_file = NULL; if ((pcre = pcre_compile("-\\*-\\s*(?:mode:\\s*)([^\\s;]);?.*-\\*-", PCRE_CASELESS, &error_message, &error_offset, NULL)) == NULL) { _t3_highlight_set_error_simple(error, T3_ERR_INTERNAL, flags); return t3_false; } if (pcre_exec(pcre, NULL, line, line_length, 0, 0, ovector, sizeof(ovector) / sizeof(ovector[0])) > 0) goto pattern_succeeded; pcre_free(pcre); if ((pcre = pcre_compile("\\s(?:vim?|ex): .*[: ]syntax=([^\\s:]+)", 0, &error_message, &error_offset, NULL)) == NULL) { _t3_highlight_set_error_simple(error, T3_ERR_INTERNAL, flags); return t3_false; } if (pcre_exec(pcre, NULL, line, line_length, 0, 0, ovector, sizeof(ovector) / sizeof(ovector[0])) > 0) goto pattern_succeeded; pcre_free(pcre); if (first) { t3_config_t *map, *language; const char *regex; if ((map = load_map(flags, error)) == NULL) return t3_false; for (language = t3_config_get(t3_config_get(map, "lang"), NULL); language != NULL; language = t3_config_get_next(language)) { if ((regex = t3_config_get_string(t3_config_get(language, "first-line-regex"))) == NULL) continue; if ((pcre = pcre_compile(regex, 0, &error_message, &error_offset, NULL)) == NULL) continue; if (pcre_exec(pcre, NULL, line, line_length, 0, 0, ovector, sizeof(ovector) / sizeof(ovector[0])) < 0) { pcre_free(pcre); continue; } pcre_free(pcre); lang->name = t3_config_take_string(t3_config_get(language, "name")); lang->lang_file = t3_config_take_string(t3_config_get(language, "lang-file")); t3_config_delete(map); return t3_true; } t3_config_delete(map); } if (error != NULL) error->error = T3_ERR_SUCCESS; return t3_false; pattern_succeeded: { char *matched_name; t3_bool result; pcre_free(pcre); if ((matched_name = malloc(ovector[3] - ovector[2] + 1)) == NULL) return t3_false; memcpy(matched_name, line + ovector[2], ovector[3] - ovector[2]); matched_name[ovector[3] - ovector[2]] = 0; result = match_xname("name-regex", matched_name, flags, lang, error); free(matched_name); return result; } }
int main() { int exit = 0; int snum; LINE_LOOP *map = load_map("map.txt", &snum, 0.2); init(); glEnable(GL_LIGHTING); glShadeModel(GL_FLAT); float global_ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); glEnable(GL_LIGHT0); // Create light components float ambientLight[] = { 0.7f, 0.7f, 0.7f, 1.0f }; float diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f }; float specularLight[] = { 0.0f, 0.0f, 0.0f, 1.0f }; float position[] = { -1.5f, 30.0f, 0.0f, 1.0f }; // Assign created components to GL_LIGHT0 glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight); //glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight); glLightfv(GL_LIGHT0, GL_POSITION, position); float cam_x = 0.0, cam_y = 2.0, cam_z = 30.0, cam_ax = 0.0, cam_ay = 0.0; while(!exit) { VECTOR cam_dir = vector(SPEED * cos(M_PI * 0.5 - cam_ay * M_PI / 180.0), SPEED * sin(cam_ay * M_PI / 180.0 - M_PI * 0.5)); int mx, my; get_mouse_mickeys(&mx, &my); //position_mouse(240, 320); cam_ay += mx * 0.03; cam_ax -= my * 0.03; if(cam_ax > 60) cam_ax = 60; if(cam_ax < -40) cam_ax = -40; if(keypressed()) { if(key[KEY_ESC]) { exit = 1; } if(key[KEY_W]) { cam_x += cam_dir.x; cam_z += cam_dir.y; } if(key[KEY_S]) { cam_x -= cam_dir.x; cam_z -= cam_dir.y; } if(key[KEY_A]) { cam_x += cam_dir.y; cam_z += -cam_dir.x; } if(key[KEY_D]) { cam_x -= cam_dir.y; cam_z -= -cam_dir.x; } if(key[KEY_LEFT]) { cam_ay -= 0.09; } if(key[KEY_RIGHT]) { cam_ay += 0.09; } if(key[KEY_PGDN]) { cam_ax -= 0.09; } if(key[KEY_PGUP]) { cam_ax += 0.09; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLightfv(GL_LIGHT0, GL_POSITION, position); transform(-cam_x, -cam_y, -cam_z, -cam_ax, cam_ay, 0.0); glBegin(GL_QUADS); glNormal3f(0.0, 1.0, 0.0); glColor3ub(255, 0, 0); glVertex3f(-300.0, 0.0, 300.0); glColor3ub(0, 255, 0); glVertex3f(300.0, 0.0, 300.0); glColor3ub(0, 0, 255); glVertex3f(300.0, 0.0, -300.0); glColor3ub(255, 255, 0); glVertex3f(-300.0, 0.0, -300.0); draw_map_3d(map, snum); glEnd(); allegro_gl_flip(); } free_map(map, snum); readkey(); return 0; }
void DrawCredits() { unsigned char end = 0; int counter = 0; redraw = 1; refresh = 1; while(!end) { vsync(); if(redraw) { ResetVideo(); setupFont(); SetFontColors(15, RGB(3, 3, 3), RGB(0, 6, 0), 0); SetFontColors(13, RGB(3, 3, 3), RGB(1, 6, 6), 0); set_xres(512, xres_flags); #ifndef CDROM1 set_map_data(MB512_map, 64, 30); set_tile_data(MB512_bg); load_tile(0x1000); load_map(0, 0, 0, 0, 64, 30); load_palette(0, MB512_pal, 1); #else set_screen_size(SCR_SIZE_64x32); cd_loaddata(GPHX_OVERLAY, OFS_back512_PAL_bin, palCD, SIZE_back512_PAL_bin); load_palette(0, palCD, 1); cd_loadvram(GPHX_OVERLAY, OFS_back512_DATA_bin, 0x1000, SIZE_back512_DATA_bin); cd_loadvram(GPHX_OVERLAY, OFS_back512_BAT_bin, 0, SIZE_back512_BAT_bin); #endif Center224in240(); redraw = 0; refresh = 1; disp_on(); } if(refresh) { RefreshCredits(); refresh = 0; } set_font_pal(14); if(counter == 1) put_string("Artemio Urbina ", HPOS+2, 8); if(counter == 60*4) put_string("@Artemio (twitter) ", HPOS+2, 8); if(counter == 60*8) put_string("*****@*****.**", HPOS+2, 8); if(counter == 60*16) counter = 0; counter++; controller = joytrg(0); if (controller & JOY_II) end = 1; if (controller & JOY_SEL) { DrawN(); redraw = 1; } } }
int main(int argc, char *argv[]) { int i; char buf[512]; SDL_Surface *screen = NULL, *message = NULL; SDL_PixelFormat fmt; TTF_Font *tmp_font; SDL_Color text_color_black = {0,0,0}; SDL_Color text_color_white = {255, 255, 255}; //Mix_Music *music = NULL; //Mix_Chunk *scratch = NULL; Uint32 timer_start = 0, timer_last_frame = 0; struct game game; // initialisation if(init_game(&game)) return 1; screen = SDL_GetVideoSurface(); fmt = *(screen->format); /////////////// // main loop // /////////////// timer_start = SDL_GetTicks(); timer_last_frame = SDL_GetTicks(); while(!game.quit) { // update time game.timer_delta = ((double)(SDL_GetTicks() - (double)timer_last_frame) / 1000); timer_last_frame = SDL_GetTicks(); /////////// // Input // /////////// read_input(&game); /////////// // Logic // /////////// if(game.finished) { //game.menu = MAPBROWSER; sscanf(game.map, "%d", &i); i++; sprintf(game.map, "%d", i); game.reset = 1; game.update = 1; game.finished = 0; } // Ingame if(game.menu == INGAME) { if(!game.paused || game.reset) { if(game.pause_screen) game.pause_screen = 0; // reset game if(game.reset) { if(!load_map(&game)) { printf("Invalid map!\n"); game.menu = MAINMENU; } game.reset = 0; game.paused = 0; game.update = 1; game.moves = 0; game.keys = 0; } // loop through all objects for(i=0; i<game.num_objects; i++) { // save old position game.object[i].x_Prev = game.object[i].x; game.object[i].y_Prev = game.object[i].y; // move object move(i, &game); // configure cursor if(!strcmp(game.object[i].type, "player")) { set_cursor (&game, i); } // check if screen refresh is needed if( (int)game.object[i].x != (int)game.object[i].x_Prev || (int)game.object[i].y != (int)game.object[i].y_Prev) { game.update = 1; } } // set camera to player for(i=0; i<game.num_objects; i++) { if(!strcmp(game.object[i].type, "player")) { game.camera.x = (game.object[i].x + game.object[i].w / 2) - game.screen_width / 2; game.camera.y = (game.object[i].y + game.object[i].h / 2) - game.screen_height / 2; } } if(game.camera.x < 0) game.camera.x = 0; if(game.camera.x + game.camera.w > game.level_width) game.camera.x = game.level_width - game.camera.w; if(game.camera.y < 0) game.camera.y = 0; if(game.camera.y + game.camera.h > game.level_height) game.camera.y = game.level_height - game.camera.h; } } // Editor else if(game.menu == EDITOR) { game.num_buttonlist = 0; if(game.mouse.x_input != game.mouse.x_prev || game.mouse.y_input != game.mouse.y_prev) process_buttons(&game); game.paused = 0; if(game.reset) { if(!game.map[0])// && !game.enter_mapname) new_map(&game); else load_map(&game); // remove "player" from toolbox // if the map contains a player tile game.tool_object[PLAYER].visible = 1; for(i=0; i<game.num_objects; i++) if(!strcmp(game.object[i].type, "player")) game.tool_object[PLAYER].visible = 0; game.reset = 0; } set_map_properties(&game); scroll_map(&game); drag_objects(&game); handle_tools(&game); if(game.enter_mapname) enter_mapname(&game); if(strcmp(game.map_prev, game.map)) { if(game.save_as) SDL_FreeSurface(game.save_as); game.save_as = TTF_RenderUTF8_Blended(game.font_yo_frankie, game.map, text_color_white); strcpy(game.map_prev, game.map); game.update = 1; } } // Mainmenu else if(game.menu == MAINMENU) { game.num_buttonlist = 0; if(game.mouse.x_input != game.mouse.x_prev || game.mouse.y_input != game.mouse.y_prev) process_buttons(&game); // reset cursor for(i=1; i<5; i++) { game.mouse.clip[i].x = 0; game.mouse.clip[1].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[2].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[3].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[4].y = 0; game.mouse.point_dir = 0; } } // Mapbrowser else if(game.menu == MAPBROWSER) { process_list(&game); // reset cursor for(i=1; i<5; i++) { game.mouse.clip[i].x = 0; game.mouse.clip[1].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[2].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[3].y = 0; game.mouse.clip[i].x = 0; game.mouse.clip[4].y = 0; game.mouse.point_dir = 0; } } if(game.mouse.x_input != game.mouse.x_prev || game.mouse.y_input != game.mouse.y_prev) { game.mouse.x_prev = game.mouse.x_input; game.mouse.y_prev = game.mouse.y_input; //if(SDL_GetTicks() % 2 == 0) game.update = 1; } //////////// // Render // //////////// // don't update screen if it is not required if(game.update) { //printf("updating screen\n"); //SDL_SetAlpha(wall_surface, SDL_SRCALPHA, 0); //printf("%d | %d » %d | %d || %d\n", game.mouse.x_prev, game.mouse.y_prev, game.mouse.x, game.mouse.y, game.mouse.click); if(game.menu == INGAME) { render_game(&game); message = SDL_CreateRGBSurface(0, 300, 50, fmt.BitsPerPixel, fmt.Rmask, fmt.Gmask, fmt.Bmask, fmt.Amask); SDL_SetAlpha(message, SDL_SRCALPHA, 150); SDL_FillRect(message, &message->clip_rect, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF)); apply_surface(0, game.screen_height - message->h, message, screen, NULL); SDL_FreeSurface(message); sprintf(buf, "Moves: %d Keys: %d", game.moves, game.keys); message = TTF_RenderUTF8_Blended(game.font_yo_frankie, buf, text_color_black); apply_surface(5, game.screen_height - message->h - 5, message, screen, NULL); SDL_FreeSurface(message); } else if(game.menu == EDITOR) { render_game(&game); /*tmp_font = TTF_OpenFont("data/fonts/yo_frankie.ttf", 18); message = TTF_RenderUTF8_Blended(tmp_font, "By Sören Wegener", text_color_black); apply_surface(game.screen_width / 2 - message->w / 2, 150, message, screen, NULL); TTF_CloseFont(tmp_font); SDL_FreeSurface(message);*/ render_toolbox(&game); render_buttons(&game); if(game.enter_mapname) { i = 450; if(game.save_as && game.save_as->w > 430) i = game.save_as->w + 20; message = SDL_CreateRGBSurface(0, i, 70, fmt.BitsPerPixel, fmt.Rmask, fmt.Gmask, fmt.Bmask, fmt.Amask); SDL_SetAlpha(message, SDL_SRCALPHA, 180); SDL_FillRect(message, &message->clip_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00)); apply_surface(game.screen_width / 2 - message->w / 2, game.screen_height / 2 - message->h / 2, message, screen, NULL); SDL_FreeSurface(message); message = TTF_RenderUTF8_Blended(game.font_yo_frankie, "Enter Mapname and press Enter", text_color_white); apply_surface(game.screen_width / 2 - message->w / 2, game.screen_height / 2 - message->h / 2 - 15, message, screen, NULL); if(game.save_as) apply_surface(game.screen_width / 2 - game.save_as->w / 2, game.screen_height / 2 - game.save_as->h / 2 + 15, game.save_as, screen, NULL); } } else if(game.menu == MAINMENU) { SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF)); render_buttons(&game); tmp_font = TTF_OpenFont("data/fonts/yo_frankie.ttf", 56); message = TTF_RenderUTF8_Blended(tmp_font, "<Lustiger Spielname hier>", text_color_black); apply_surface(game.screen_width / 2 - message->w / 2, 50, message, screen, NULL); TTF_CloseFont(tmp_font); SDL_FreeSurface(message); tmp_font = TTF_OpenFont("data/fonts/yo_frankie.ttf", 18); message = TTF_RenderUTF8_Blended(tmp_font, "By Sören Wegener", text_color_black); apply_surface(game.screen_width / 2 - message->w / 2, 150, message, screen, NULL); TTF_CloseFont(tmp_font); SDL_FreeSurface(message); tmp_font = TTF_OpenFont("data/fonts/yo_frankie.ttf", 14); message = TTF_RenderUTF8_Blended(tmp_font, "Yo Frankie font created by Pablo Vazquez and converted by Mango Jambo using FontForge 2.0", text_color_black); apply_surface(0, game.screen_height - message->h, message, screen, NULL); TTF_CloseFont(tmp_font); SDL_FreeSurface(message); } else if(game.menu == MAPBROWSER) { SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF)); render_list(&game); } render_cursor(&game); // refresh screen SDL_Flip(screen); game.update = 0; } // needed to prevent 100% CPU usage SDL_Delay(0); } cleanup(&game); return 0; }
int main(int argc, char *argv[]) { DATAFILE *datf; BITMAP *scrFlip; BITMAP *scrMap; PALETTE pal; WINDOW *winInfo; long frames = 0L; float start_time, end_time; MAP *map, *overlay; int x = 0, y = 0; int old_x = -1, old_y = -1; int dx = 1, dy = 1; int view_w, view_h; int do_idle = 1; char s[128]; // Default screen resolution to 320x200. screen_width = 320; screen_height = 200; // Read command line args. Set screen size accordingly. if (argc > 2) { screen_width = atoi(argv[1]); screen_height = atoi(argv[2]); } right_size = 0; bottom_size = 0; printf("screen: %dX%d\n", screen_width, screen_height); // Initialize Allegro. Great library! allegro_init(); install_timer(); install_keyboard(); // Set graphics mode. if (set_gfx_mode(GFX_AUTODETECT, screen_width, screen_height, 0, 0) == -1) { printf("Cannot set video mode to %d, %d.\n", screen_width, screen_height); return 1; } // load comic font from ex4. datf = load_datafile_object("ex.dat", "comic12"); if (datf == NULL) { allegro_exit(); printf("Error loading ex.dat\n"); return 1; } text_mode(-1); // load map //printf("loading map\n"); map = load_map("tile1.wmp", "tile1.spr", pal); if (map == NULL) { allegro_exit(); printf("Error loading map file.\n"); return 1; } // load overlay //printf("loading overlay\n"); overlay = load_map("tile1ovr.wmp", NULL, NULL); if (overlay == NULL) { allegro_exit(); printf("Error loading overlay file.\n"); return 1; } map_settileset(overlay, map->tileset); // Allocate buffers for our rendering. //printf("allocating buffers\n"); scrFlip = create_bitmap(SCREEN_W, SCREEN_H); clear(scrFlip); scrMap = create_bitmap(SCREEN_W + map->t_width*2, SCREEN_H + map->t_height*2); // set palette //printf("setting palette\n"); gui_setpalette(pal); // Build rgb_table. text_mode(makecol8(0, 0, 0)); textout_centre(screen, font, "Building RGB table.", SCREEN_W>>1, 10, 100); create_rgb_table(&rgb_table, pal, rgb_table_callback); rgb_map = &rgb_table; // Build lighting table. text_mode(makecol8(0, 0, 0)); textout_centre(screen, font, "Building lighting table.", SCREEN_W>>1, 10, 100); create_light_table(&light_table, pal, 64, 64, 64, rgb_table_callback); // Build translucency table. text_mode(makecol8(0, 0, 0)); textout_centre(screen, font, "Building translucency table.", SCREEN_W>>1, 10, 100); create_trans_table(&trans_table, pal, 128, 128, 128, rgb_table_callback); color_map = &trans_table; // initialize gui gui_initialize(&light_table, &trans_table); // set map and overlay color tables map_settables(map, &trans_table, &light_table); map_settables(overlay, &trans_table, &light_table); // create info window winInfo = gui_create_window(128, 200, WB_THICK, WD_TRANSLUCENT); gui_move_window(winInfo, SCREEN_W-winInfo->window.w, 0); // set up vars. view_w = scrMap->w/map->t_width; view_h = scrMap->h/map->t_height; // setup time_to_blit interrupt. LOCK_VARIABLE(time_to_blit); LOCK_FUNCTION(time_to_blit_timer); install_int_ex(time_to_blit_timer, BPS_TO_TIMER(30)); missed_frames = 0; // main loop. start_time = clock(); while (1) { idle_time = 0; if (do_idle) while (!time_to_blit) idle_proc(); // lock it in at around 30 fps. time_to_blit = 0; if (idle_time < lowest_idle) lowest_idle = idle_time; if (idle_time > highest_idle) highest_idle = idle_time; // render map if (map_getx_tile(map, x) != old_x || map_gety_tile(map, y) != old_y) { render_map(map, scrMap, 0, 0, x, y, view_w, view_h); render_map(overlay, scrMap, 0, 0, x, y, view_w, view_h); old_x = map_getx_tile(map, x); old_y = map_gety_tile(map, y); } blit(scrMap, scrFlip, map_getx_offset(map, x), map_gety_offset(map, y), 0, 0, SCREEN_W-right_size, SCREEN_H-bottom_size); gui_clear_window(winInfo, makecol8(0, 0, 0)); gui_textout_centre_window(winInfo, "Map Demo", 2, makecol8(255, 0, 0), -1); sprintf(s, "X: %d, Y: %d", x, y); gui_textout_centre_window(winInfo, s, 14, makecol8(0, 0, 255), -1); sprintf(s, "DX: %d, DY: %d", dx, dy); gui_textout_centre_window(winInfo, s, 24, makecol8(0, 0, 255), -1); sprintf(s, "X Ofs: %d", map_getx_offset(map, x)); gui_textout_centre_window(winInfo, s, 34, makecol8(0, 0, 255), -1); sprintf(s, "Y Ofs: %d", map_gety_offset(map, y)); gui_textout_centre_window(winInfo, s, 44, makecol8(0, 0, 255), -1); sprintf(s, "Idle: %d", idle_time); gui_textout_centre_window(winInfo, s, 64, makecol8(0, 255, 255), -1); sprintf(s, "Missed: %d", missed_frames); gui_textout_centre_window(winInfo, s, 74, makecol8(0, 255, 255), -1); gui_draw_window(winInfo, scrFlip); // blit it //vsync(); blit(scrFlip, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); // check keys if (key[KEY_SPACE]) { break; } if (key[KEY_LSHIFT]) do_idle = 0; else do_idle = 1; if (key[KEY_CONTROL]) gui_set_window_styles(winInfo, -1, WD_BLIT); else gui_set_window_styles(winInfo, -1, WD_TRANSLUCENT); if (key[KEY_PGDN]) { dx--; if (dx < 1) dx = 1; dy--; if (dy < 1) dy = 1; } if (key[KEY_PGUP]) { dx++; dy++; } if (key[KEY_RIGHT]) { x+=dx; if (x > (map->w_width-1) - SCREEN_W) { x-=dx; } } if (key[KEY_DOWN]) { y+=dy; if (y > (map->w_height-1) - SCREEN_H) { y-=dy; } } if (key[KEY_LEFT]) { x-=dx; if (x < 0) { x = 0; } } if (key[KEY_UP]) { y-=dy; if (y < 0) { y = 0; } } // Increment frame counter. frames++; } end_time = clock(); // Clean up. unload_datafile_object(datf); destroy_map(map); overlay->tileset=NULL; destroy_map(overlay); destroy_bitmap(scrFlip); destroy_bitmap(scrMap); // Close down allegro. allegro_exit(); // Report. printf("Tile Map, Copyright 1997 by Scott Deming.\n"); printf("\nHow'd we do?\n"); printf("===============================================================================\n"); printf(" Time: %3.2f\n", (float) ((end_time-start_time) / 100)); printf("Frames: %lu\n", frames); printf(" FPS: %3.2f\n", (float) (float) frames / (float) ((end_time-start_time) / 100)); printf("Missed: %d\n", missed_frames); printf(" Idle: %d (lowest was %d, highest %d)\n", idle_time, lowest_idle, highest_idle); printf("Screen: %dX%d\n", screen_width, screen_height); printf("-------------------------------------------------------------------------------\n"); printf("Note: If \"Idle\" starts to get close to zero then things should be done to\n"); printf(" speed things up. When idle proc hits zero, we'll start missing frames\n"); printf(" (indicated by \"Missed\") and things can start to get a bit jerky.\n"); printf(" If \"Missed\" is greater than 0, start optimizing.\n"); printf(" If you turned off the 30 fps timer halt then your lowest idle will be 0.\n"); return 0; }
int main() { int exit = 0, a_flag = -1;//, val = 0; NODE *head = NULL; VECTOR a, b; VECTOR p = vector(320.0, 240.0), v; float alpha = 0.0; int snum; LINE_LOOP *map = load_map("map.txt", &snum, 0.2); init(); a = vector(0.0, 0.0); b = vector(1.0, 0.0); head = (NODE *)malloc(sizeof(NODE)); head->val = val; head->a = a; head->b = b; head->n = NORMALIZED_NORMAL(a, b); head->parent = NULL; head->left = NULL; head->right = NULL; val++; compile_map(head, map, snum); while(!exit) { if(key[KEY_ESC]) { exit = 1; } if(key[KEY_SPACE]) { printf("\n"); key[KEY_SPACE] = 0; } if(key[KEY_LEFT]) { alpha -= 0.03; } if(key[KEY_RIGHT]) { alpha += 0.03; } if(key[KEY_W]) { p.y -= SPEED; } if(key[KEY_S]) { p.y += SPEED; } if(key[KEY_A]) { p.x -= SPEED; } if(key[KEY_D]) { p.x += SPEED; } v = vector(20.0 * cos(alpha), 20.0 * sin(alpha)); if(mouse_b == 1) { a.x = mouse_x; a.y = mouse_y; a_flag = 1; } if(mouse_b == 2 && a_flag > 0) { b.x = mouse_x; b.y = mouse_y; a_flag = 0; add_node(head, &val, a, b); val++; } clear_to_color(buffer, makecol(128, 128, 128)); //draw_tree(buffer, p, v, head, 320, 240, 10, makecol(128, 0, 0)); first = 1; traverse_tree(buffer, head, p, v); printf("\n\n"); if(a_flag == 0) vector_line(buffer, a, b, makecol(0, 0, 128)); if(a_flag == 1) vector_line(buffer, a, vector(mouse_x, mouse_y), makecol(0, 0, 128)); circlefill(buffer, mouse_x, mouse_y, 2, 0); vector_point(buffer, p, 10, makecol(0, 128, 0)); vector_line(buffer, p, VECTOR_SUM(p, v), makecol(0, 0, 0)); vector_line(buffer, p, VECTOR_SUM(p, USCALE_VECTOR(VECTOR_NORMAL(v), 200.0)), makecol(0, 0, 0)); vector_line(buffer, p, VECTOR_SUM(p, USCALE_VECTOR(VECTOR_NORMAL(v), -200.0)), makecol(0, 0, 0)); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); } free_map(map, snum); destroy_tree(head); destroy_bitmap(buffer); return 0; }
int main() { int exit = 0, a_flag = -1;//, val = 0; int vnum, snum, i; VEC2F *map_vertex; WALL_SEGMENT *map_segment; NODE *head = NULL; VEC2F p = vec2f(0.0, 0.0), v; float alpha = 0.0; load_map("map.txt", &map_vertex, &map_segment, &vnum, &snum, 1.0); //realloc_bullshit(&map_vertex, 20); //map_vertex[16] = vec2f(20.0, 20.0); init(); head = (NODE *)malloc(sizeof(NODE)); head->val = val; head->a = map_segment[0].a; head->b = map_segment[0].b; head->n = NORMALIZED_NORMAL_VEC2F(map_vertex[map_segment[0].a], map_vertex[map_segment[0].b]); head->parent = NULL; head->left = NULL; head->right = NULL; val++; for(i = 1; i < snum; i++) { add_node(head, &val, map_segment[i].a, map_segment[i].b, &map_vertex, &vnum); val++; } //compile_map(head, map, snum); while(!exit) { if(key[KEY_ESC]) { exit = 1; } if(key[KEY_SPACE]) { printf("\n"); key[KEY_SPACE] = 0; } if(key[KEY_LEFT]) { alpha -= 0.03; } if(key[KEY_RIGHT]) { alpha += 0.03; } if(key[KEY_W]) { p.y -= SPEED; } if(key[KEY_S]) { p.y += SPEED; } if(key[KEY_A]) { p.x -= SPEED; } if(key[KEY_D]) { p.x += SPEED; } v = vec2f(20.0 * cos(alpha), 20.0 * sin(alpha)); clear_to_color(buffer, makecol(128, 128, 128)); //draw_tree(buffer, p, v, head, 320, 240, 10, makecol(128, 0, 0)); traverse_tree(buffer, head, p, v, map_vertex); printf("\n\n"); /* if(a_flag == 0) vec2f_line(buffer, a, b, makecol(0, 0, 128)); if(a_flag == 1) ve2f_line(buffer, a, vector(mouse_x, mouse_y), makecol(0, 0, 128)); circlefill(buffer, mouse_x, mouse_y, 2, 0); vec2f_point(buffer, p, 10, makecol(0, 128, 0)); */ vec2f_line(buffer, p, VEC2F_SUM(p, v), makecol(0, 0, 0)); vec2f_line(buffer, p, VEC2F_SUM(p, USCALE_VEC2F(VEC2F_NORMAL(v), 200.0)), makecol(0, 0, 0)); vec2f_line(buffer, p, VEC2F_SUM(p, USCALE_VEC2F(VEC2F_NORMAL(v), -200.0)), makecol(0, 0, 0)); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); } free(map_vertex); free(map_segment); destroy_tree(head); destroy_bitmap(buffer); return 0; }
void MapSource::generateMaps() { GoogleProjection proj; if(tiled) { ScreenPos topLeft = (proj.fromLLToPixel(w,n,zoom_start)) , bottomRight = (proj.fromLLToPixel(e,s,zoom_start)) ; topLeft.x /= 256; topLeft.y /= 256; bottomRight.x /= 256; bottomRight.y /= 256; int x_fetch_freq, y_fetch_freq, x_fetches, y_fetches; if(multirqst) { // Gives a value approx equal to 0.1 lat/lon in southern UK x_fetch_freq = (int)(pow(2.0,zoom_start-11)); y_fetch_freq = (int)(pow(2.0,zoom_start-11)); x_fetches = ((bottomRight.x-topLeft.x) / x_fetch_freq)+1, y_fetches = ((bottomRight.y-topLeft.y) / y_fetch_freq)+1; } else { x_fetch_freq = bottomRight.x - topLeft.x; y_fetch_freq = bottomRight.y - topLeft.y; x_fetches = 1; y_fetches = 1; } fprintf(stderr,"topLeft: %d %d\n",topLeft.x,topLeft.y); fprintf(stderr,"bottomRight: %d %d\n",bottomRight.x,bottomRight.y); fprintf(stderr,"xfetches yfetches: %d %d\n",x_fetches, y_fetches); for(int xfetch=0; xfetch<x_fetches; xfetch++) { for (int yfetch=0; yfetch<y_fetches; yfetch++) { cerr<<"XFETCH="<<xfetch<<" YFETCH="<<yfetch<<endl; EarthPoint bottomL_LL = proj.fromPixelToLL( (topLeft.x+xfetch*x_fetch_freq)*256, ((topLeft.y+yfetch*y_fetch_freq) +y_fetch_freq)*256, zoom_start), topR_LL = proj.fromPixelToLL( ( (topLeft.x+xfetch*x_fetch_freq)+x_fetch_freq)*256, (topLeft.y+yfetch*y_fetch_freq) *256, zoom_start), bottomR_LL = proj.fromPixelToLL( ((topLeft.x+xfetch*x_fetch_freq)+ x_fetch_freq)*256, ((topLeft.y+yfetch*y_fetch_freq) +y_fetch_freq)*256, zoom_start), topL_LL = proj.fromPixelToLL( (topLeft.x+xfetch*x_fetch_freq)*256, (topLeft.y+yfetch*y_fetch_freq) *256, zoom_start); double w1 = min(bottomL_LL.x-0.01,topL_LL.x-0.01), s1 = min(bottomL_LL.y-0.01,bottomR_LL.y-0.01), e1 = max(bottomR_LL.x+0.01,topR_LL.x+0.01), n1 = max(topL_LL.y+0.01,topR_LL.y+0.01); parameters p; if(getSource()=="api") { std::ostringstream str; str<<w1<<","<<s1<<"," <<e1<<","<<n1; p["url"] = url; p["file"] = ""; p["bbox"] = str.str(); cerr<<"URL="<<str.str()<<endl; } else if (getSource()=="osm") { p["file"] = osmfile; } Map m (width, height); p["type"] ="osm"; load_map(m,xmlfile); setOSMLayers(m,p); if(srtm) { addSRTMLayers(m,w1,s1,e1,n1); } // lonToX() and latToY() give *pixel* coordinates // See email Chris Schmidt 12/02/09 double metres_per_pixel = (20037508.34/pow(2.0, 7+zoom_start)); for(int z=zoom_start; z<=zoom_end; z++) { EarthPoint bl,tr; int ZOOM_FCTR = (int)(pow(2.0,z-zoom_start)); for(int tileX= (topLeft.x+xfetch*x_fetch_freq)*ZOOM_FCTR; tileX< (topLeft.x+xfetch*x_fetch_freq+x_fetch_freq) *ZOOM_FCTR; tileX++) { for(int tileY=(topLeft.y+yfetch*y_fetch_freq) *ZOOM_FCTR; tileY<(topLeft.y+yfetch*y_fetch_freq+y_fetch_freq) *ZOOM_FCTR; tileY++) { cerr<<"x: " << tileX << " y: " << tileY <<" z: " << z << endl; image_32 buf(m.width(),m.height()); double metres_w =( (tileX*256.0) * metres_per_pixel ) - 20037814.088; double metres_s = 20034756.658 - ((tileY*256.0) * metres_per_pixel ); double metres_e = metres_w + (metres_per_pixel*256); double metres_n = metres_s + (metres_per_pixel*256); box2d<double> bb (metres_w-32*metres_per_pixel, metres_s-32*metres_per_pixel, metres_e+32*metres_per_pixel, metres_n+32*metres_per_pixel); m.zoom_to_box(bb); agg_renderer<image_32> r(m,buf); r.apply(); string filename=""; std::ostringstream str; str<< z<< "."<<tileX<<"." << tileY << ".png"; save_to_file<image_data_32>(buf.data(), "tmp.png","png"); FILE *in=fopen("tmp.png","r"); FILE *out=fopen(str.str().c_str(),"w"); gdImagePtr image, image2; image=gdImageCreateTrueColor(256,256); image2=gdImageCreateFromPng(in); gdImageCopy(image,image2,0,0,32,32,256,256); gdImagePng(image,out); gdImageDestroy(image2); gdImageDestroy(image); fclose(out); fclose(in); } } metres_per_pixel /= 2; } } } } else { // standard rendering Map m(width,height); parameters p; p["type"] = "osm"; p["file"] = osmfile; load_map(m,xmlfile); setOSMLayers(m,p); box2d<double> latlon= (hasBbox()) ? box2d<double>(w,s,e,n): m.getLayer(0).envelope(); EarthPoint bottomL_LL = GoogleProjection::fromLLToGoog(latlon.minx(),latlon.miny()), topR_LL = GoogleProjection::fromLLToGoog(latlon.maxx(),latlon.maxy()); box2d<double> bb = box2d<double>(bottomL_LL.x,bottomL_LL.y, topR_LL.x,topR_LL.y); m.zoom_to_box(bb); image_32 buf (m.width(), m.height()); agg_renderer<image_32> r(m,buf); r.apply(); save_to_file<image_data_32>(buf.data(),outfile,"png"); } }
void change_map (const char *mapname) { #ifndef MAP_EDITOR remove_all_bags(); remove_all_mines(); #endif //MAP_EDITOR set_all_intersect_update_needed(main_bbox_tree); object_under_mouse=-1;//to prevent a nasty crash, while looking for bags, when we change the map #ifndef MAP_EDITOR2 #ifdef EXTRA_DEBUG ERR(); #endif close_dialogue(); // close the dialogue window if open close_storagewin(); //if storage is open, close it destroy_all_particles(); ec_delete_all_effects(); #ifdef NEW_SOUND stop_all_sounds(); #endif //NEW_SOUND missiles_clear(); if (!el_load_map(mapname)) { char error[255]; safe_snprintf(error, sizeof(error), cant_change_map, mapname); LOG_TO_CONSOLE(c_red4, error); LOG_TO_CONSOLE(c_red4, empty_map_str); LOG_ERROR(cant_change_map, mapname); load_empty_map(); } else { locked_to_console = 0; } load_map_marks(); #ifdef NEW_SOUND get_map_playlist(); setup_map_sounds(get_cur_map(mapname)); #endif // NEW_SOUND have_a_map=1; //also, stop the rain weather_clear(); if ( get_show_window (map_root_win) ) { hide_window(map_root_win); show_window(game_root_win); } #else // !MAP_EDITOR2 destroy_all_particles(); #ifdef NEW_SOUND stop_all_sounds(); #endif //NEW_SOUND if (!load_map(mapname)) { char error[255]; safe_snprintf(error, sizeof(error), cant_change_map, mapname); LOG_TO_CONSOLE(c_red4, error); LOG_TO_CONSOLE(c_red4, empty_map_str); LOG_ERROR(cant_change_map, mapname); load_empty_map(); } #ifdef NEW_SOUND get_map_playlist(); setup_map_sounds(get_cur_map(mapname)); #endif // NEW_SOUND have_a_map=1; #endif //MAP_EDITOR2 change_minimap(); #ifdef PAWN run_pawn_map_function ("change_map", "s", mapname); #endif }
int main(int argc, char *argv[]) { if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) { printf("Can't initialize SDL: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } atexit(SDL_Quit); SDL_Surface *screen, *text, *save_message; SDL_Event event; TTF_Font *font; int i, done = 0, mouse_x = 0, mouse_y = 0; unsigned int frames = SDL_GetTicks() + FLIMIT; unsigned int *frame_limit; frame_limit = &frames; int *mouse_x_ptr, *mouse_y_ptr; mouse_x_ptr = &mouse_x; mouse_y_ptr = &mouse_y; int show_save_msg = 0; screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_DOUBLEBUF | SDL_HWSURFACE); //screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_DOUBLEBUF | SDL_FULLSCREEN); if(NULL == screen) { printf("Can't set video mode: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } /* set window title */ SDL_WM_SetCaption("2D SIMULATION", NULL); /* disable cursor */ SDL_ShowCursor(SDL_DISABLE); /* load new cursor */ load_cursor(); /* load the map and fill tiles array */ load_map(); /* load tileset */ load_tileset(); /* load player */ load_player_image(); /* setup font */ TTF_Init(); SDL_Color text_color = {255, 255, 255}; font = TTF_OpenFont("media/fonts/slkscrb.ttf", 8); /* game loop */ while(!done) { while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: done = 1; break; case SAVE_EVENT: show_save_msg = 0; //printf("SDL_USEREVENT: %i\n", SAVE_EVENT); break; case SDL_MOUSEMOTION: *mouse_x_ptr = event.motion.x; *mouse_y_ptr = event.motion.y; break; case SDL_MOUSEBUTTONDOWN: switch(event.button.button) { case 1: //destroy_block(screen, event.button.x, event.button.y); input.mleft = 1; break; case 3: //place_block(event.button.x, event.button.y, &player); input.mright = 1; break; default: break; } break; case SDL_MOUSEBUTTONUP: switch(event.button.button) { /* removed because if player falls down, it deletes always the block below the player */ case 1: input.mleft = 0; break; case 3: input.mright = 0; break; default: break; } break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: done = 1; break; case SDLK_a: input.left = 1; break; case SDLK_d: input.right = 1; break; case SDLK_SPACE: input.jump = 1; break; case SDLK_1: player.selected = DIRT; break; case SDLK_2: player.selected = GRASS; break; case SDLK_3: player.selected = SAND; break; case SDLK_4: player.selected = ROCK; break; case SDLK_5: player.selected = WATER5; break; case SDLK_6: player.selected = OIL; break; case SDLK_F12: save_map(); SDL_AddTimer (2000, msg_event, NULL); show_save_msg = 1; break; default: break; } break; case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_a: input.left = 0; break; case SDLK_d: input.right = 0; break; default: break; } break; } } move_player(&player); // and camera move_sand(); simulate_water(); simulate_oil(); place_and_destroy_blocks(screen, event.button.x, event.button.y, &player); //input.mleft = 0; // uncomment for click once to delete one block //input.mright = 0; // uncomment for click once to place one block draw(screen, mouse_x_ptr, mouse_y_ptr, &player, text, font, text_color, show_save_msg, save_message); delay(frame_limit); *frame_limit = SDL_GetTicks() + FLIMIT; } /* free tiles/mass/new_mass array in reverse order */ for(i = 0; i < map.h; i++) { free(map.tiles[i]); free(map.water_mass[i]); free(map.new_water_mass[i]); free(map.oil_mass[i]); free(map.new_oil_mass[i]); } free(map.tiles); free(map.water_mass); free(map.new_water_mass); free(map.oil_mass); free(map.new_oil_mass); SDL_FreeSurface(tileset); SDL_FreeSurface(player_image); SDL_FreeSurface(cursor); SDL_FreeSurface(text); SDL_FreeSurface(save_message); return 0; }
int main (int argc, char *argv[]) { int i; progname = argv[0]; while ((i = getopt (argc, argv, "hvu:m:f:g:o:")) != -1) { switch (i) { case 'v': verbosity = 1; break; case 'h': usage(); return 2; case 'm': assert (sscanf(optarg, "%d,%d", &split_rem, &split_mod) == 2); assert (split_mod > 0 && split_mod <= 1000 && split_rem >= 0 && split_rem < split_mod); break; case 'f': table_format = get_dump_format(optarg); if (!table_format) { fprintf (stderr, "fatal: unsupported table dump format: %s\n", optarg); return 2; } break; case 'g': groups_fname = optarg; break; case 'o': output_format = atol (optarg); break; case 'u': username = optarg; break; } } if (optind >= argc || optind + 2 < argc) { usage(); return 2; } src_fname = argv[optind]; if (username && change_user (username) < 0) { fprintf (stderr, "fatal: cannot change user to %s\n", username ? username : "******"); return 1; } src_fd = open (src_fname, O_RDONLY); if (src_fd < 0) { fprintf (stderr, "cannot open %s: %m\n", src_fname); return 1; } if (!table_format) { table_format = get_dump_format (fname_last (src_fname)); if (!table_format) { fprintf (stderr, "fatal: cannot determine table type from filename %s\n", src_fname); } } if (optind + 1 < argc) { targ_fname = argv[optind+1]; targ_fd = open (targ_fname, O_WRONLY | O_APPEND | O_CREAT, 0644); if (targ_fd < 0) { fprintf (stderr, "cannot create %s: %m\n", targ_fname); return 1; } } else { targ_fname = "stdout"; targ_fd = 1; } switch (table_format) { case TF_AUDIO: Args_per_line = au_END; start_binlog(SEARCH_SCHEMA_V1, "audio_search"); while (read_record() > 0) { process_audio_row(); } break; case TF_VIDEO: Args_per_line = vi_END; start_binlog(SEARCH_SCHEMA_V1, "video_search"); while (read_record() > 0) { process_video_row(); } break; case TF_APPS: Args_per_line = ap_END; start_binlog(SEARCH_SCHEMA_V1, "apps_search"); while (read_record() > 0) { process_applications_row(); } break; case TF_GROUPS: Args_per_line = gr_END; start_binlog(SEARCH_SCHEMA_V1, "group_search"); while (read_record() > 0) { process_groups_row(); } break; case TF_EVENTS: Args_per_line = gr_END; start_binlog(SEARCH_SCHEMA_V1, "event_search"); while (read_record() > 0) { process_events_row(); } break; case TF_BLOG_POSTS: Args_per_line = bp_END; start_binlog(SEARCH_SCHEMA_V1, "blog_posts_search"); while (read_record() > 0) { process_blog_posts_row(); } break; case TF_MEMLITE: Args_per_line = ml_END; start_binlog(SEARCH_SCHEMA_V1, "member_name_search"); while (read_record() > 0) { process_memlite_row(); } break; case TF_MARKET_ITEMS: Args_per_line = mi_END; start_binlog(SEARCH_SCHEMA_V1, "market_search"); while (read_record() > 0) { process_market_row(); } break; case TF_QUESTIONS: Args_per_line = qu_END; start_binlog(SEARCH_SCHEMA_V1, "question_search"); while (read_record() > 0) { process_questions_row(); } break; case TF_TOPICS: load_map (1); Args_per_line = to_END; start_binlog(SEARCH_SCHEMA_V1, "topic_search"); while (read_record() > 0) { process_topics_row(); } break; case TF_MINIFEED: Args_per_line = mf_END; start_binlog(SEARCH_SCHEMA_V1, "status_search"); while (read_record() > 0) { process_minifeed_row(); } break; default: fprintf (stderr, "unknown table type\n"); exit(1); } flush_out(); if (targ_fd != 1) { if (fdatasync(targ_fd) < 0) { fprintf (stderr, "error syncing %s: %m", targ_fname); exit (1); } close (targ_fd); } if (map_size > 0 && map_changes > 0 && groups_fname) { map_fd = open (groups_fname, O_WRONLY | O_CREAT | O_TRUNC, 0640); if (map_fd < 0) { fprintf (stderr, "cannot create map file %s: %m\n", groups_fname); exit (1); } assert (write (map_fd, Map, map_size) == map_size); close (map_fd); if (verbosity > 0) { fprintf (stderr, "%d bytes written to map file %s\n", map_size, groups_fname); } } if (verbosity > 0) { output_stats(); } return 0; }
int main(int argc, const char *argv[]) { if (argc < 2) { help(argv[0]); return 1; } int fn_arg = 0; const char *map_fn_arg = 0; int action = 0; int i; for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { help(argv[0]); return 0; } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { version(); return 0; } else if (!strcmp(argv[i], "-l") || !strcmp(argv[i], "--list")) { action = A_LIST; } else if (!strcmp(argv[i], "-E") || !strcmp(argv[i], "--ignore-errors")) { ignore_errors = true; } else if (!strcmp(argv[i], "-H") || !strcmp(argv[i], "--human-readable")) { human_readable = true; } else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--edit")) { action = A_EDIT; } else if (!strcmp(argv[i], "-f")) { i++; map_fn_arg = argv[i]; } else if (!strncmp(argv[i], "--from-file=", 12)) { map_fn_arg = argv[i] + 12; } else if (argv[i][0] != '-') { fn_arg = i; } else { printf("Unknown argument: %s\n", argv[i]); help(argv[0]); return 1; } } if (action == 0 && map_fn_arg == 0) { help(argv[0]); return 1; } FILE *img_f = fopen(argv[fn_arg], "r+b"); if (img_f == 0) { printf("Can't open file: %s\n", argv[fn_arg]); errno_print(); return 1; } struct _LwVM *LwVM = malloc(sizeof(*LwVM)); fseek(img_f, 0L, SEEK_SET); if (fread(LwVM, 1, sizeof(*LwVM), img_f) != 4096) { printf("Can't read file: %s\n", argv[fn_arg]); errno_print(); cleanup(img_f, LwVM); return 1; } bool pt_no_crc = !memcmp(LwVM->type, LwVMType_noCRC, sizeof(*LwVMType_noCRC)); if (memcmp(LwVM->type, LwVMType, sizeof(*LwVMType)) != 0 && !pt_no_crc) { printf("LwVM has unknown type or was damaged, "); if (ignore_errors) printf("continuing anyway...\n"); else { printf("exiting...\n"); cleanup(img_f, LwVM); return 1; } } if (map_fn_arg) { struct stat st; if (stat(map_fn_arg, &st) != 0) { printf("Can't stat file: %s\n", map_fn_arg); errno_print(); cleanup(img_f, LwVM); return 1; } FILE *map_f = fopen(map_fn_arg, "r"); if (map_f == 0) { printf("Can't open map: %s\n", map_fn_arg); errno_print(); cleanup(img_f, LwVM); return 1; } char *map = malloc(st.st_size); if (fread(map, 1, st.st_size, map_f) != st.st_size) { printf("Can't read map: %s\n", map_fn_arg); errno_print(); cleanup(img_f, LwVM); fclose(map_f); return 1; } fclose(map_f); int map_load_status = load_map(LwVM, map); if (map_load_status) { printf("Map parse failed.\n"); cleanup(img_f, LwVM); return 1; } printf("Map load success.\n"); write_lwvm(img_f, LwVM); cleanup(img_f, LwVM); return 0; } if (action == A_LIST) { print_pt(LwVM, pt_no_crc); } else if (action == A_EDIT) { int status = edit_pt(LwVM, pt_no_crc); if (status == SAVE_CHANGES) { return write_lwvm(img_f, LwVM); } } cleanup(img_f, LwVM); return 0; }
void process_message_from_server(unsigned char *in_data, int data_lenght) { //see what kind of data we got switch (in_data[PROTOCOL]) { case RAW_TEXT: { // do filtering and ignoring data_lenght=filter_or_ignore_text(&in_data[3],data_lenght-3)+3; if(data_lenght > 3) { //how to display it if(interface_mode!=interface_opening) put_text_in_buffer(&in_data[3],data_lenght-3,0); else put_text_in_buffer(&in_data[3],data_lenght-3,54); //lets log it write_to_log(&in_data[3],data_lenght-3); } } break; case SMALL_WINDOW_TEXT: { add_text_to_small_text_buffer(in_data+3, data_lenght-3); display_small_text_window(); } break; case ADD_NEW_ACTOR: { add_actor_from_server(&in_data[3]); } break; case ADD_NEW_ENHANCED_ACTOR: { add_enhanced_actor_from_server(&in_data[3]); } break; case ADD_ACTOR_COMMAND: { add_command_to_actor(*((short *)(in_data+3)),in_data[5]); } break; case REMOVE_ACTOR: { destroy_actor(*((short *)(in_data+3))); } break; case KILL_ALL_ACTORS: { destroy_all_actors(); } break; case NEW_MINUTE: { game_minute=*((short *)(in_data+3)); new_minute(); } break; case LOG_IN_OK: { interface_mode=interface_game; previously_logged_in=1; } break; case HERE_YOUR_STATS: { get_the_stats((Sint16 *)(in_data+3)); } break; case SEND_PARTIAL_STAT: { get_partial_stat(*((Uint8 *)(in_data+3)),*((Sint32 *)(in_data+4))); } break; case GET_KNOWLEDGE_LIST: { get_knowledge_list(*(Uint16 *)(in_data+1)-1, in_data+3); } break; case GET_NEW_KNOWLEDGE: { get_new_knowledge(*(Uint16 *)(in_data+3)); } break; case HERE_YOUR_INVENTORY: { get_your_items(in_data+3); } break; case GET_NEW_INVENTORY_ITEM: { get_new_inventory_item(in_data+3); } break; case REMOVE_ITEM_FROM_INVENTORY: { remove_item_from_inventory(*((Uint8 *)(in_data+3))); } break; case INVENTORY_ITEM_TEXT: { put_small_text_in_box(&in_data[3],data_lenght-3,6*51+100,items_string); if(!(get_show_window(items_win)||get_show_window(trade_win))) { put_text_in_buffer(&in_data[3],data_lenght-3,0); } } break; case GET_KNOWLEDGE_TEXT: { put_small_text_in_box(&in_data[3],data_lenght-3,6*51+150,knowledge_string); } break; case CHANGE_MAP: { current_sector=-1; if(map_file_name[0]!=0) save_map(map_file_name); object_under_mouse=-1;//to prevent a nasty crash, while looking for bags, when we change the map close_dialogue(); // close the dialogue window if open destroy_all_particles(); if(!load_map(&in_data[4])){ // creating map if it does not exist int size=(in_data[3]&0x1f)<<4; new_map(size,size); dungeon=(in_data[3]&0x20)?1:0; strcpy(map_file_name,&in_data[4]); save_map(map_file_name); } kill_local_sounds(); #ifndef NO_MUSIC playing_music=0; #endif //NO_MUSIC get_map_playlist(); have_a_map=1; //also, stop the rain seconds_till_rain_starts=-1; seconds_till_rain_stops=-1; is_raining=0; rain_sound=0;//kill local sounds also kills the rain sound weather_light_offset=0; rain_light_offset=0; } break; case GET_TELEPORTERS_LIST: { add_teleporters_from_list(&in_data[3]); } break; case PLAY_MUSIC: { if(!no_sound)play_music(*((short *)(in_data+3))); } break; case PLAY_SOUND: { if(!no_sound)add_sound_object(*((short *)(in_data+3)),*((short *)(in_data+5)),*((short *)(in_data+7)),*((char *)(in_data+9)),*((short *)(in_data+10))); } break; case TELEPORT_OUT: { add_particle_sys_at_tile("./particles/teleport_in.part",*((short *)(in_data+3)),*((short *)(in_data+5))); if(!no_sound)add_sound_object(snd_tele_out,*((short *)(in_data+3)),*((short *)(in_data+5)),1,0); } break; case TELEPORT_IN: { add_particle_sys_at_tile("./particles/teleport_in.part",*((short *)(in_data+3)),*((short *)(in_data+5))); if(!no_sound)add_sound_object(snd_tele_in,*((short *)(in_data+3)),*((short *)(in_data+5)),1,0); } break; case LOG_IN_NOT_OK: { sprintf(log_in_error_str,"%s: %s",reg_error_str,invalid_pass); } break; case REDEFINE_YOUR_COLORS: { strcpy(log_in_error_str,redefine_your_colours); } break; case YOU_DONT_EXIST: { sprintf(log_in_error_str,"%s: %s",reg_error_str,char_dont_exist); } break; case CREATE_CHAR_NOT_OK: { sprintf(create_char_error_str,"%s: %s",reg_error_str,char_name_in_use); return; } break; case CREATE_CHAR_OK: { login_from_new_char(); } break; case YOU_ARE: { yourself=*((short *)(in_data+3)); } break; case START_RAIN: { seconds_till_rain_starts=*((Uint8 *)(in_data+3)); seconds_till_rain_stops=-1; } break; case STOP_RAIN: { seconds_till_rain_stops=*((Uint8 *)(in_data+3)); seconds_till_rain_starts=-1; } break; case THUNDER: { add_thunder(rand()%5,*((Uint8 *)(in_data+3))); } break; case SYNC_CLOCK: { server_time_stamp=*((int *)(in_data+3)); client_time_stamp=SDL_GetTicks(); client_server_delta_time=server_time_stamp-client_time_stamp; } break; case PONG: { Uint8 str[160]; sprintf(str,"%s: %i MS",server_latency, SDL_GetTicks()-*((Uint32 *)(in_data+3))); log_to_console(c_green1,str); } break; case UPGRADE_NEW_VERSION: { log_to_console(c_red1,update_your_client); log_to_console(c_red1,(char*)web_update_address); } break; case UPGRADE_TOO_OLD: { log_to_console(c_red1,client_ver_not_supported); log_to_console(c_red1,(char*)web_update_address); this_version_is_invalid=1; } break; case GET_NEW_BAG: { put_bag_on_ground(*((Uint16 *)(in_data+3)),*((Uint16 *)(in_data+5)),*((Uint8 *)(in_data+7))); } break; case GET_BAGS_LIST: { add_bags_from_list(&in_data[3]); } break; case SPAWN_BAG_PARTICLES: { add_particle_sys_at_tile("./particles/bag_in.part",*((Uint16 *)(in_data+3)),*((Uint16 *)(in_data+5))); } break; case GET_NEW_GROUND_ITEM: { get_bag_item(in_data+3); } break; case HERE_YOUR_GROUND_ITEMS: { get_bags_items_list(&in_data[3]); } break; case CLOSE_BAG: { hide_window(ground_items_win); } break; case REMOVE_ITEM_FROM_GROUND: { remove_item_from_ground(in_data[3]); } break; case DESTROY_BAG: { remove_bag(in_data[3]); } break; case NPC_TEXT: { put_small_text_in_box(&in_data[3],data_lenght-3,dialogue_menu_x_len-70,dialogue_string); display_dialogue(); if(in_data[3]>=127 && in_data[4]>=127) { add_questlog(&in_data[4],data_lenght-4); } } break; case SEND_NPC_INFO: { my_strcp(npc_name,&in_data[3]); cur_portrait=in_data[23]; } break; case NPC_OPTIONS_LIST: { build_response_entries(&in_data[3],*((Uint16 *)(in_data+1))); } break; case GET_TRADE_ACCEPT: { if(!in_data[3])trade_you_accepted=1; else trade_other_accepted=1; } break; case GET_TRADE_REJECT: { if(!in_data[3])trade_you_accepted=0; else trade_other_accepted=0; } break; case GET_TRADE_EXIT: { hide_window(trade_win); } break; case GET_YOUR_TRADEOBJECTS: { get_your_trade_objects(in_data+3); } break; case GET_TRADE_OBJECT: { put_item_on_trade(in_data+3); } break; case REMOVE_TRADE_OBJECT: { remove_item_from_trade(in_data+3); } break; case GET_TRADE_PARTNER_NAME: { get_trade_partner_name(&in_data[3],*((Uint16 *)(in_data+1))-1); } break; case GET_ACTOR_DAMAGE: { get_actor_damage(*((Uint16 *)(in_data+3)),in_data[5]); } break; case GET_ACTOR_HEAL: { get_actor_heal(*((Uint16 *)(in_data+3)),in_data[5]); } break; case ACTOR_UNWEAR_ITEM: { unwear_item_from_actor(*((Uint16 *)(in_data+3)),in_data[5]); } break; case ACTOR_WEAR_ITEM: { actor_wear_item(*((Uint16 *)(in_data+3)),in_data[5],in_data[6]); } break; case NPC_SAY_OVERTEXT: { add_displayed_text_to_actor( get_actor_ptr_from_id( *((Uint16 *)(in_data+3)) ), in_data+5 ); } break; case BUDDY_EVENT: { if(in_data[3]==1) add_buddy(&in_data[5],in_data[4],data_lenght-5); else if(in_data[3]==0) del_buddy(&in_data[4],data_lenght-4); } break; // BARREN MOON NEW MESSAGES case THIS_IS_ACTIVE_SECTOR: active_sector=*((Uint16 *)(in_data+3)); break; case GET_TILE_DATA: get_tile_data(in_data+3); break; case GET_3D_OBJECTS: get_3d_objects(in_data+3); break; case GET_2D_OBJECTS: get_2d_objects(in_data+3); break; case GET_LIGHT_OBJECTS: get_light_objects(in_data+3); break; case GET_PARTICLE_OBJECTS: get_particle_objects(in_data+3); break; case GET_3D_OBJECTS_FULL_ROTATION: get_3d_objects_full_rotation(in_data+3); break; case GET_CHECKSUMS: { actor *actor=pf_get_our_actor(); get_checksums(in_data+3, sector_get(actor->x_pos,actor->y_pos)); break; } case ADD_3D_OBJECT: add_3d_object(in_data+3); break; case ADD_3D_OBJECT_FULL_ROTATION: add_3d_object_fullrotation(in_data+3); break; case DELETE_3D_OBJECT: delete_3d_object(in_data+3); break; case REPLACE_3D_OBJECT: replace_3d_object(in_data+3); break; case ADD_2D_OBJECT: add_2d_object(in_data+3); break; case DELETE_2D_OBJECT: delete_2d_object(in_data+3); break; case REPLACE_2D_OBJECT: replace_2d_object(in_data+3); break; case ADD_LIGHT: add_lights(in_data+3); break; case DELETE_LIGHT: delete_light(in_data+3); break; case ADD_PARTICLE: add_particle(in_data+3); break; case DELETE_PARTICLE: delete_particle(in_data+3); break; case REPLACE_PARTICLE: replace_particle(in_data+3); break; default: { /* Unknown data type?? */; } break; } }
int main(int argc, char **argv) { options_t opt; FILE *fp; HashFile *hf; /* process command line arguments of the form -arg */ opt.directories = 0; opt.verbose = 0; opt.append_mode = 0; opt.prepend_mode = 0; opt.basename = 0; opt.header = NULL; opt.footer = NULL; opt.archive = NULL; opt.map = NULL; for (argc--, argv++; argc > 0; argc--, argv++) { if (**argv != '-' || strcmp(*argv, "--") == 0) break; if (strcmp(*argv, "-a") == 0 && argc > 1) { opt.archive = argv[1]; argv++; argc--; } if (strcmp(*argv, "-A") == 0) opt.append_mode = 1; if (strcmp(*argv, "-O") == 0) opt.prepend_mode = 1; if (strcmp(*argv, "-d") == 0) opt.directories = 1; if (strcmp(*argv, "-v") == 0) opt.verbose = 1; if (strcmp(*argv, "-b") == 0) opt.basename = 1; if (strcmp(*argv, "-m") == 0 && argc > 1) { /* Name mapping */ opt.map = load_map(argv[1]); if (!opt.map) { fprintf(stderr, "Failed to load map '%s'\n", argv[1]); return 1; } argv++; argc--; } if (strcmp(*argv, "-h") == 0 && argc > 1) { /* Common header */ hf->headers = (HashFileSection *) realloc(hf->headers, (hf->nheaders+1) * sizeof(HashFileSection)); opt.header = argv[1]; hf->nheaders++; argv++; argc--; } if (strcmp(*argv, "-f") == 0 && argc > 1) { /* Common footer */ hf->footers = (HashFileSection *) realloc(hf->footers, (hf->nfooters+1) * sizeof(HashFileSection)); opt.footer = argv[1]; hf->nfooters++; argv++; argc--; } } if (argc < 1 && !opt.archive) { fprintf(stderr, "Usage: hash_tar [options] [tarfile] > tarfile.hash\n"); fprintf(stderr, " -a fname Tar archive filename: use if reading from stdin\n"); fprintf(stderr, " -A Force no archive name (eg will concat to archive itself)\n"); fprintf(stderr, " -O Set arc. offset to size of hash (use when prepending)\n"); fprintf(stderr, " -v Verbose mode\n"); fprintf(stderr, " -d Index directory names (useless?)\n"); fprintf(stderr, " -h name Set tar entry 'name' to be a file header\n"); fprintf(stderr, " -f name Set tar entry 'name' to be a file footer\n"); fprintf(stderr, " -b Use only the filename portion of a pathname\n"); fprintf(stderr, " -m fname Reads lines of 'old new' and renames entries before indexing."); return 1; } /* Load the tar file index into memory */ hf = HashFileCreate(0, HASH_DYNAMIC_SIZE); if (argc < 1) { if (!opt.archive) { fprintf(stderr, "If reading from stdin you must use the " "\"-a archivename\" option\n"); return 1; } accumulate(hf, stdin, opt.archive, &opt); } else { /* Single file mode */ if (opt.append_mode) { if (argc >= 2) { fprintf(stderr, "Can only use append_mode with a single " "tar file\n"); return 1; } } /* Iterate over all tar files */ while (argc >= 1) { FILE *fp = fopen(argv[0], "rb"); if (fp == NULL) { perror(argv[0]); return 1; } accumulate(hf, fp, argv[0], &opt); fclose(fp); argc--; argv++; } } /* * Find the header/footer if specified. For now we only support one of * each. */ link_footers(hf, &opt); /* Construct the hash */ construct_hash(hf); /* Save hash */ save_hash(hf, &opt); /* Tidy up */ free(files); return 0; }