void pathfinder(vector<vector<int>>& matrix, vector<vector<int>>& counter, int& max, int& size, int i, int j, int n, int m){
     int ref = counter[i][j] + 1;
     if(counter[i][j] > max) max = counter[i][j];
     if(i > 0 && matrix[i-1][j] > matrix[i][j] && counter[i-1][j] < ref){
         if(counter[i-1][j] == 0) size--;
         counter[i-1][j] = ref;
         pathfinder(matrix, counter, max, size, i-1, j, n, m);
     }
     if(i < n-1 && matrix[i+1][j] > matrix[i][j] && counter[i+1][j] < ref){
         if(counter[i+1][j] == 0) size--;
         counter[i+1][j] = ref;
         pathfinder(matrix, counter, max, size, i+1, j, n, m);
     }
     if(j > 0 && matrix[i][j-1] > matrix[i][j] && counter[i][j-1] < ref){
         if(counter[i][j-1] == 0) size--;
         counter[i][j-1] = ref;
         pathfinder(matrix, counter, max, size, i, j-1, n, m);
     }
     if(j < m-1 && matrix[i][j+1] > matrix[i][j] && counter[i][j+1] < ref){
         if(counter[i][j+1] == 0) size--;
         counter[i][j+1] = ref;
         pathfinder(matrix, counter, max, size, i, j+1, n, m);
     }
     return;
 }
Ejemplo n.º 2
0
void solve(int n,int m,int **p){
    printf("Running matrRecursive\n");
    int **b;      /*Declares a board to store the summary for each number of the board. */
    int i,j,smax=0,jmax;   /*Declares 2 variables for the loops,one for the maximum sum,and one to be used finding the path. */
    b=malloc(n*sizeof(int *));   /*Commiting the "pointer" part of the board */
    if (b==NULL){
        printf("Error,not enough memory available.");
        return;
    }
    for (i=0;i<n;i++){
        b[i]=malloc(m*sizeof(int)); /*Finish commiting the board. */
        if (b[i]==NULL){  
            printf("Error,not enough memory available.");
            return;
        }
        for(j=0;j<m;j++){   /*Initialise every object on the board as 0. */
            b[i][j]=0;
        }
    }
    for (j=0;j<m;j++){   /*Goes through the first line finding the maximum summary and where it is.*/
        if(matrRecursive(p,b,0,j,n,m)>smax){
            jmax=j;
            smax=b[0][jmax];
        }
    }
    printf("Max sum is %d.\n",smax);
    pathfinder(p,b,jmax,n,m);   /*Calling a function that finds and prints the path.*/
    for (i=0;i<n;i++){         /*Freeing the board.*/
        free(b[i]);
    }
    free(b);
}
Ejemplo n.º 3
0
bool UnitBase::SearchPathWithAStar() {
	Coord destinationCoord;

	if(target && target.getObjPointer() != NULL) {
	    if(itemID == Unit_Carryall && target.getObjPointer()->getItemID() == Structure_Refinery) {
            destinationCoord = target.getObjPointer()->getLocation() + Coord(2,0);
	    } else if(itemID == Unit_Frigate && target.getObjPointer()->getItemID() == Structure_StarPort) {
            destinationCoord = target.getObjPointer()->getLocation() + Coord(1,1);
	    } else {
            destinationCoord = target.getObjPointer()->getClosestPoint(location);
	    }
	} else {
		destinationCoord = destination;
	}

	AStarSearch pathfinder(currentGameMap, this, location, destinationCoord);
	pathList = pathfinder.getFoundPath();

	if(pathList.empty() == true) {
        nextSpotFound = false;
        return false;
	} else {
	    return true;
	}
}
int main()
{
    typedef boost::geometry::model::point
        <
            double, 2, martian<boost::geometry::degree> 
        > mars_point;

    // Declare two points 
    // (Source: http://nssdc.gsfc.nasa.gov/planetary/mars_mileage_guide.html)
    // (Other sources: Wiki and Google give slightly different coordinates, resulting
    //  in other distance, 20 km off)
    mars_point viking1(-48.23, 22.54); // Viking 1 landing site in Chryse Planitia
    mars_point pathfinder(-33.55, 19.33); // Pathfinder landing site in Ares Vallis

    double d = boost::geometry::distance(viking1, pathfinder); // Distance in radians on unit-sphere

    // Using the Mars mean radius
    // (Source: http://nssdc.gsfc.nasa.gov/planetary/factsheet/marsfact.html)
    std::cout << "Distance between Viking1 and Pathfinder landing sites: " 
        << d * 3389.5 << " km" << std::endl;

    // We would get 832.616 here, same order as the 835 (rounded on 5 km) listed
    // on the mentioned site 

#ifdef OPTIONALLY_ELLIPSOIDAL
    // Optionally the distance can be calculated more accurate by an Ellipsoidal approach,
    // giving 834.444 km
    d = boost::geometry::distance(viking1, pathfinder,
        boost::geometry::strategy::distance::andoyer<mars_point>
            (boost::geometry::detail::ellipsoid<double>(3396.2, 3376.2)));
    std::cout << "Ellipsoidal distance: " << d << " km" << std::endl;
#endif

    return 0;
}
Ejemplo n.º 5
0
/* Callback to execute the pathfinder */
void GridView::DoPathfind(Fl_Widget *pButton)
{
    // Refresh the grid first
    RefreshGrid();
    
    AStar pathfinder(*grid);
    
    Path path;

    // Depending on which button was pressed to trigger this, call either with
    // or without using heuristic
    if (!std::strcmp(pButton->label(), "Pathfind!"))
        path = pathfinder.buildFromWaypoints(waypoints);
    else
        path = pathfinder.buildWithHeuristic(waypoints);

    for (int y = 0; y < grid->getHeight(); ++y)
        for (int x = 0; x < grid->getWidth(); ++x) {
            // If this point is on the path, set the button's color to green
            if (std::find(path.begin(), path.end(), Point(x, y)) != path.end()) {
                squares[Point(x, y)]->color(FL_GREEN);
            }
        }
        
    // Set result label
    if (path.size() == 0) {
        result_output->value("Couldn't find path");
        result_output->color(FL_RED);
    } else {
        result_output->value("Success!");
        result_output->color(FL_GREEN);
    }
}
Ejemplo n.º 6
0
int _tmain(int argc, _TCHAR* argv[])
{
	//On lance la recherche de chemin
	sf::RenderWindow window(sf::VideoMode(1024 , 768), "Pathfinding A*");
	//Espace de jeu
	World world;
	//On instancie le pathFinder
	PathFinding pathfinder(world);
	//On lance la recherche de chemin
	pathfinder.findPath(Vecteur(30,40), Vecteur(250,150));
	//On créé une liste Vecteur et on récupère le chemin du pathfinder
	std::vector<Vecteur> path(pathfinder.getPath());

	//On affiche les coordonées des points du chemin
	std::vector<Vecteur>::reverse_iterator it = path.rbegin();
	/*for(; it != path.rend(); it++)
		std::cout << (*it)->x << " " << (*it)->y << std::endl;*/
	//On créé les obstacles
	sf::RectangleShape rect1(sf::Vector2f(50, 300));
	rect1.setFillColor(sf::Color::Black);
	rect1.setPosition(200, 0);
	sf::RectangleShape rect2(sf::Vector2f(50, 200));
	rect2.setFillColor(sf::Color::Black);
	rect2.setPosition(350, 200);

	sf::Clock clock;
	
	//Boucle d'affichage
	while (window.isOpen())
    {
		if(clock.getElapsedTime().asSeconds() > 0.5)
		{
			clock.restart();
			int y = rand() % 140 + 10 ;
			int x = rand() % 240 + 10 ;
			pathfinder.findPath(Vecteur(30,40), Vecteur(x,y));
		}
		//Enlever l'affichage la frame précédent
		window.clear(sf::Color::White);
		sf::Event event;
		//Gesion de l'évènement "fermer la fenêtre"
		while (window.pollEvent(event))
			if (event.type == sf::Event::Closed)
                window.close();
		//On dessine nos cercles
		pathfinder.draw(window);
		//On dessine les obstacles
		//window.draw(rect1);
		//window.draw(rect2);
		//Afficher nos objets
        window.display();
	}
	return 0;
}
 int longestIncreasingPath(vector<vector<int>>& matrix) {
     int max = 1, n = matrix.size();
     if(n == 0) return 0;
     int m = matrix[0].size(), size = n * m, temp;
     
     vector<vector<int>> counter(n, vector<int>(m, 0));
     for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++){
             if(size == 0) break;
             temp = counter[i][j];
             if(temp != 0 || (i > 0 && matrix[i-1][j] < temp) || (i < n - 1 && matrix[i+1][j] < temp) 
                 || (j > 0 && matrix[i][j-1] < temp) || (j < m - 1 && matrix[i][j+1] < temp)){
                 continue;
             }
             counter[i][j] = 1;
             pathfinder(matrix, counter, max, --size, i, j, n, m);
         }
         if(size == 0) break;
     }
     
     return max;
 }
Ejemplo n.º 8
0
void solve(int n,int m,int **p){
   printf("Running iterative\n");
   int **b;                   /*Declares a board to store the summary for each number of the board. */
   int i,j,jmax,smax=0;        /*Declares 2 variables for the loops,one for the maximum sum,and one to be used finding the path. */
   b=malloc(n*sizeof(int *));  /*Commiting the "pointer" part of the board */
   if (b==NULL){
        printf("Error,not enough memory available.");
        return;
   }
   for (i=0;i<n;i++){        
       b[i]=malloc(m*sizeof(int));    /*Finish commiting the board. */
       if (b[i]==NULL){
           printf("Error,not enough memory available.");
           return;
       }
       for(j=0;j<m;j++){
           b[i][j]=p[i][j];     /*Initially copying the number board on the summary board to do less loops,not having to touch the last line. */
       }
   }
   for(i=n-2;i>=0;i--){     /*Starts from the bottom upwards,and ,using iterative, fills the summary board. */
       for (j=0;j<m;j++){
           iterative(b,i,j,m);
       }       
   }
   for (j=0;j<m;j++){       /*Finds the maximum summary and it's position using the summary board. */
        if(b[0][j]>smax){
            jmax=j;
            smax=b[0][jmax];
        }
    }
    printf("Max sum is %d.\n",smax);
    pathfinder(p,b,jmax,n,m);/*Calls a function to find and print the path. */
    for (i=0;i<n;i++){     /*Freeing the summary board. */
        free(b[i]);
    }
    free(b);
   
}   
Ejemplo n.º 9
0
DirectionE RepulseBehaviour::nextMove(const Coord& currentPosition, std::tr1::shared_ptr<scenario::Scenario> scenario) {
	if (!_target) return STAY;

	Coord targetCoord(_target->position().x / 30, _target->position().y / 30);

	int x, y;

	if (targetCoord.x < int(scenario->sizeW() / 2)) {
		x = scenario->sizeW() - 2;
	} else {
		x = 1;
	}

	if (targetCoord.y < int(scenario->sizeH() / 2)) {
		y = scenario->sizeH() - 2;
	} else {
		y = 1;
	}

	Coord dest(x, y);

	std::vector<Coord> path;
	AI::AStar pathfinder(scenario, DistanceFromTarget(_target, _evilGhost));
	pathfinder.findPath(path, currentPosition, dest);

	Coord delta = path[1] - path[0];

	DirectionE d = STAY;

	if (delta.x == -1) d = LEFT;
	else if (delta.x == 1) d = RIGHT;
	else if (delta.y == -1) d = UP;
	else if (delta.y == 1) d = DOWN;

	return d;
}
Ejemplo n.º 10
0
Archivo: ai.cpp Proyecto: ejrh/hex
void Ai::update_unit_stack(UnitStack& stack) {
    UnitStack::pointer enemy = get_nearest_enemy(stack);
    Point tile_pos(stack.position);
    if (enemy) {
        BOOST_LOG_TRIVIAL(info) << "Saw enemy: " << enemy->id;
        tile_pos = enemy->position;
    } else {
        tile_pos.x += (rand() % 5) - (rand() % 5);
        tile_pos.y += (rand() % 5) - (rand() % 5);
    }

    MovementModel movement_model(&game);
    Pathfinder pathfinder(&game.level, &movement_model);
    pathfinder.start(stack, stack.position, tile_pos);
    pathfinder.complete();
    Path new_path;
    pathfinder.build_path(new_path);

    if (new_path.size() > 10)
        new_path.resize(10);

    if (new_path.empty())
        return;

    UnitStack::pointer target_stack = game.level.tiles[new_path.back()].stack;
    if (target_stack) {
        return;
    }

    IntSet selected_units;
    for (unsigned int i = 0; i < stack.units.size(); i++) {
        selected_units.insert(i);
    }

    dispatcher->receive(create_message(UnitMove, stack.id, selected_units, new_path, 0));
}
Ejemplo n.º 11
0
	//#################### PUBLIC METHODS ####################
std::vector<ObjectCommand_Ptr> MinimusGotoPositionYoke::generate_commands(InputState& input)
{
	const Database& db = *m_objectManager->database();
	NavManager_CPtr navManager = db.get("db://NavManager", navManager);
	shared_ptr<std::vector<CollisionPolygon_Ptr> > polygons = db.get("db://OnionPolygons", polygons);
	OnionTree_CPtr tree = db.get("db://OnionTree", tree);

	// Check to make sure the yoke's still active.
	if(m_state != YOKE_ACTIVE)
	{
		return std::vector<ObjectCommand_Ptr>();
	}

	ICmpMovement_CPtr cmpMovement = m_objectManager->get_component(m_objectID, cmpMovement);		assert(cmpMovement != NULL);
	ICmpSimulation_CPtr cmpSimulation = m_objectManager->get_component(m_objectID, cmpSimulation);	assert(cmpSimulation != NULL);

	const Vector3d& source = cmpSimulation->position();

	if(!m_path)
	{
		int mapIndex = m_objectManager->bounds_manager()->lookup_bounds_index(cmpSimulation->bounds_group(), cmpSimulation->posture());
		NavDataset_CPtr navDataset = navManager->dataset(mapIndex);
		NavMesh_CPtr navMesh = navDataset->nav_mesh();
		GlobalPathfinder pathfinder(navMesh, navDataset->adjacency_list(), navDataset->path_table());

		int suggestedSourcePoly = cmpMovement->cur_nav_poly_index();
		int sourcePoly = NavMeshUtil::find_nav_polygon(source, suggestedSourcePoly, *polygons, tree, navMesh);
		if(sourcePoly == -1)	{ m_state = YOKE_FAILED; return std::vector<ObjectCommand_Ptr>(); }
		int destPoly = NavMeshUtil::find_nav_polygon(m_dest, -1, *polygons, tree, navMesh);
		if(destPoly == -1)		{ m_state = YOKE_FAILED; return std::vector<ObjectCommand_Ptr>(); }

		// FIXME: It's wasteful to copy the array of links each time (even though it's an array of pointers).
		m_links = navMesh->links();

		m_path.reset(new std::list<int>);
		bool pathFound = pathfinder.find_path(source, sourcePoly, m_dest, destPoly, *m_path);
		if(!pathFound)			{ m_state = YOKE_FAILED; return std::vector<ObjectCommand_Ptr>(); }
	}

	// FIXME:	The way this yoke decides that it's traversed a link isn't sufficient.
	//			I've devised a better way of doing it, but it's not yet implemented.

	// Step 1:	If the path is non-empty, go to the next link that we haven't already passed.
	Vector3d dir;
	while(!m_path->empty())
	{
		const Vector3d& linkIn = m_links[m_path->front()]->source_position();
		const Vector3d& linkOut = m_links[m_path->front()]->dest_position();
		dir = linkIn - source;
		if(dir.length() >= 0.1 && source.distance(linkOut) >= 0.1)
		{
			dir.normalize();
			break;
		}
		else
		{
			m_path->pop_front();
		}
	}

	if(!m_path->empty())
	{
		std::vector<ObjectCommand_Ptr> commands;
		commands.push_back(ObjectCommand_Ptr(new CmdBipedWalk(m_objectID, dir)));
		commands.push_back(ObjectCommand_Ptr(new CmdBipedSetLook(m_objectID, dir)));
		return commands;
	}

	// Step 2:	If the path is empty, go straight to the actual destination.
	dir = m_dest - source;
	if(dir.length() >= 0.1)
	{
		dir.normalize();

		std::vector<ObjectCommand_Ptr> commands;
		commands.push_back(ObjectCommand_Ptr(new CmdBipedWalk(m_objectID, dir)));
		commands.push_back(ObjectCommand_Ptr(new CmdBipedSetLook(m_objectID, dir)));
		return commands;
	}
	else
	{
		// We've reached the destination.
		m_state = YOKE_SUCCEEDED;
		return std::vector<ObjectCommand_Ptr>();
	}
}
Ejemplo n.º 12
0
void MoveAction::findPath()
{
    bool hexGrid = false;
    // Create Pathfinder

	// Get path as list of nodes
	std::list<GridNode *> * nodes;

	GridNode * startNode = level_->grid()->nodeAtPoint(start_);
	GridNode * endNode = level_->grid()->nodeAtPoint(end_);

	if(hexGrid) {
        PathfinderHex pathfinder(level_->grid());
        nodes = pathfinder.run(startNode, endNode);
	}
	else {
        PathfinderSquare pathfinder(level_->grid());
        nodes = pathfinder.run(startNode, endNode);
	}
    // Print the path to log
	//Logger::ss << "Path: ";
	for (std::list<GridNode *>::iterator iterator = nodes->begin(), end = nodes->end(); iterator != end; ++iterator) {
	    //Logger::ss << "(" << (**iterator).row() << ", " << (**iterator).column() << ") ";
	    //Logger::ss << (*iterator)->toString() << " ";
	}
	//Logger::write(Logger::ss);
    //Logger::write(Logger::ss << "# of nodes: " << nodes->size());

	// Convert node path into Movement path
    while(nodes->size() > 1) {
	    if(nodes->size() >= 2) {
            // TODO(2013-09-20/JM): Add code to filter straight line paths into a single movement

            GridNode * startNode = nodes->front();
            if(nodes->empty()) {
                //Logger::write(Logger::ss << "Uh oh, list is empty dude!\n");
                break;
            }
            nodes->pop_front();
            if(nodes->empty()) {
                //Logger::write(Logger::ss << "Uh oh, list is empty dude!\n");
                break;
            }
            GridNode * endNode = nodes->front();

            // Create movement vector
            Vector vector = Vector(startNode->centerPoint(), endNode->centerPoint());

            // Create movement
            //Logger::write(Logger::ss << "Start Point: " << startNode->centerPoint().toString());
            //Logger::write(Logger::ss << "End Point: " << endNode->centerPoint().toString());
            Movement * thisMovement = new Movement(vector, startNode->centerPoint(), endNode->centerPoint());

            path_->push_back(thisMovement);
        }
	    else {
            // shouldn't ever run this
            break;
	    }
	}

    // Check if entity is located at the cneter point of the start grid
    /*
    GridNode * startGrid = level_->grid()->nodeAtPoint(start_);
    Point startGridCenterPoint = startGrid->centerPoint();
    Movement * firstMovement = *path_->begin();

    if(startGridCenterPoint != start_) {
        Vector vector = Vector(start_, firstMovement->destination());
        firstMovement->setVector(vector);
        firstMovement->setStart(start_);
    }
*/

	// Set current movement to beginning
	current_ = path_->begin();
	if(!path_->empty()) {
	    //Logger::write(Logger::ss << "MoveAction::firstMovement(): " << (*current_)->toString());
	}
	//Logger::write(Logger::ss << "Path created: " << path_->size() << " movements");

	// reset grid
	level_->grid()->resetPathfinding();
}
Ejemplo n.º 13
0
int char_moveto(int cn, int x, int y, int flag, int x2, int y2)
{
	int dir, in;
	unsigned long long prof;

	if (ch[cn].x==x && ch[cn].y==y && flag!=1 && flag!=3)
	{
		return( 1);
	}

	if (ch[cn].cerrno==ERR_FAILED)
	{
		ch[cn].cerrno = ERR_NONE;
		return( -1);
	}

	if (ch[cn].unreach>globs->ticker && ch[cn].unreachx==x && ch[cn].unreachy==y)
	{
		return(-1);
	}

	prof = prof_start();
	dir  = pathfinder(cn, x, y, flag, x2, y2);
	prof_stop(1, prof);

	if (dir==-1)
	{
		ch[cn].unreach  = globs->ticker + TICKS;
		ch[cn].unreachx = x;
		ch[cn].unreachy = y;
		return(-1);
	}
	if (dir==0)
	{
		return( 0);
	}

	switch(dir)
	{
	case DX_RIGHTDOWN:
		if (ch[cn].dir!=DX_RIGHTDOWN)
		{
			act_turn_rightdown(cn);
			return( 0);
		}
		act_move_rightdown(cn);
		return( 0);
	case DX_RIGHTUP:
		if (ch[cn].dir!=DX_RIGHTUP)
		{
			act_turn_rightup(cn);
			return( 0);
		}
		act_move_rightup(cn);
		return( 0);
	case DX_LEFTDOWN:
		if (ch[cn].dir!=DX_LEFTDOWN)
		{
			act_turn_leftdown(cn);
			return( 0);
		}
		act_move_leftdown(cn);
		return( 0);
	case DX_LEFTUP:
		if (ch[cn].dir!=DX_LEFTUP)
		{
			act_turn_leftup(cn);
			return( 0);
		}
		act_move_leftup(cn);
		return( 0);
	case DX_RIGHT:
		if (ch[cn].dir!=DX_RIGHT)
		{
			act_turn_right(cn);
			return( 0);
		}
		if ((in = map[(ch[cn].x + 1) + (ch[cn].y) * MAPX].it)!=0 && !it[in].active && it[in].driver==2)
		{
			act_use(cn);
			return( 0);
		}
		act_move_right(cn);
		return( 0);
	case DX_LEFT:
		if (ch[cn].dir!=DX_LEFT)
		{
			act_turn_left(cn);
			return( 0);
		}
		if ((in = map[(ch[cn].x - 1) + (ch[cn].y) * MAPX].it)!=0 && !it[in].active && it[in].driver==2)
		{
			act_use(cn);
			return( 0);
		}
		act_move_left(cn);
		return( 0);
	case DX_DOWN:
		if (ch[cn].dir!=DX_DOWN)
		{
			act_turn_down(cn);
			return( 0);
		}
		if ((in = map[(ch[cn].x) + (ch[cn].y + 1) * MAPX].it)!=0 && !it[in].active && it[in].driver==2)
		{
			act_use(cn);
			return( 0);
		}
		act_move_down(cn);
		return( 0);
	case DX_UP:
		if (ch[cn].dir!=DX_UP)
		{
			act_turn_up(cn);
			return( 0);
		}
		if ((in = map[(ch[cn].x) + (ch[cn].y - 1) * MAPX].it)!=0 && !it[in].active && it[in].driver==2)
		{
			act_use(cn);
			return( 0);
		}
		act_move_up(cn);
		return( 0);
	}
	return(-1);
}
Ejemplo n.º 14
0
Archivo: player.c Proyecto: yzzyx/adv
/*
 * monster_goto_position(m, x, y)
 *
 * Try to make monster walk to x, y
 * Returns 1 if it's possible, or 0 otherwise
 */
int
monster_goto_position(PyObject *monster, int x, int y)
{
	int monster_x, monster_y;
	node_t *active_path;

	/* don't walk outside of map */
	if (x < SPRITE_SIZE/2) x = SPRITE_SIZE/2;
	if (y < SPRITE_SIZE/2) y = SPRITE_SIZE/2;
	if (x >= global_GS.current_map->width - SPRITE_SIZE/2)
		x = global_GS.current_map->width - SPRITE_SIZE/2;
	if (y >= global_GS.current_map->height - SPRITE_SIZE/2)
		y = global_GS.current_map->height - SPRITE_SIZE/2;

	/* check if target position is even a valid position */
	if (global_GS.current_map->raytrace_map
		[x+y*global_GS.current_map->width] != 0) {
		return 0;
	}

	monster_x = py_getattr_int(monster, ATTR_X);
	monster_y = py_getattr_int(monster, ATTR_Y);

	/* Check if we already have an active path */
	active_path = (node_t*)py_getattr_int(monster, ATTR_INT_ACTIVE_PATH);
	if (active_path) {
		while (active_path->child) {
			active_path = active_path->child;
		}

		/* We've already got a path to this place, don't
		 * do anything
		 */
		if (active_path->x == x && active_path->y == y)
			return 0;

		/* We need a new path, get rid of the old one */
		pathfinder_free_path(active_path);
	}

	if (map_has_line_of_sight(monster_x, monster_y, x, y)) {

		/* We can walk directly to this point,
		 * so create a path to it
		 */
		active_path = calloc(1,sizeof(*active_path));
		active_path->child = NULL;
		active_path->parent = NULL;
		active_path->x = x;
		active_path->y = y;

		py_setattr_int(monster, ATTR_INT_ACTIVE_PATH, (long)active_path);
		py_setattr_int(monster, ATTR_IN_MOVEMENT, 1);
		return 0;
	}


	/* Note that we're working with grid-coordinates in the pathfinder,
	 * to speed things up, and make it less resource-hungry
	 */
	active_path = pathfinder(global_GS.current_map->pathfinder, monster,
	    monster_x / SPRITE_SIZE, monster_y / SPRITE_SIZE,
	    x / SPRITE_SIZE, y / SPRITE_SIZE);

	if (!active_path) {
		printf("No path from %d,%d to %d,%d\n",
		    monster_x, monster_y, x, y);
		return 0;
	}

	/* Convert path from grid-coordinates to real coordinates */
	node_t *node;
	for (node = active_path; node != NULL; node = node->child) {
		node->x = node->x * SPRITE_SIZE + SPRITE_SIZE/2;
		node->y = node->y * SPRITE_SIZE + SPRITE_SIZE/2;
	}

	/* FIXME - prune path */

	py_setattr_int(monster, ATTR_INT_ACTIVE_PATH, (long)active_path);
	py_setattr_int(monster, ATTR_IN_MOVEMENT, 1);
	return 0;
}
Ejemplo n.º 15
0
vector<PathData> M2MFstAligner::write_alignment(const VectorFst<LogArc> &ifst,
        int nbest)
{
    //Generic alignment generator
    VectorFst<StdArc> fst;
    Map(ifst, &fst, LogToStdMapper());

    for (StateIterator<VectorFst<StdArc> > siter(fst); !siter.Done();
            siter.Next()) {
        StdArc::StateId q = siter.Value();
        for (MutableArcIterator<VectorFst<StdArc> > aiter(&fst, q);
                !aiter.Done(); aiter.Next()) {
            //Prior to decoding we make several 'heuristic' modifications to the weights:
            // 1. A multiplier is applied to any multi-token substrings
            // 2. Any LogWeight::Zero() arc weights are reset to '99'.
            //    We are basically resetting 'Infinity' values to a 'smallest non-Infinity'
            //     so that the ShortestPath algorithm actually produces something no matter what.
            // 3. Any arcs that consist of subseq1:subseq2 being the same length and subseq1>1
            //       are set to '99' this forces shortestpath to choose arcs where one of the
            //       following conditions holds true
            //      * len(subseq1)>1 && len(subseq2)!=len(subseq1)
            //      * len(subseq2)>1 && len(subseq1)!=len(subseq2)
            //      * len(subseq1)==len(subseq2)==1
            //I suspect these heuristics can be eliminated with a better choice of the initialization
            // function and maximization function, but this is the way that m2m-aligner works, so
            // it makes sense for our first cut implementation.
            //In any case, this guarantees that M2MFstAligner produces results identical to those
            // produced by m2m-aligner - but with a bit more reliability.
            //UPDATE: this now produces a better alignment than m2m-aligner.
            //  The maxl heuristic is still in place.  The aligner will produce *better* 1-best alignments
            //  *without* the maxl heuristic below, BUT this comes at the cost of producing a less
            //  flexible corpus.  That is, for a small training corpus like nettalk, if we use the
            //  best alignment we wind up with more 'chunks' and thus get a worse coverage for unseen
            //  data.  Using the aignment lattices to train the joint ngram model solves this problem.
            //  Oh baby.  Can't wait to for everyone to see the paper!
            //NOTE: this is going to fail if we encounter any alignments in a new test item that never
            // occurred in the original model.
            StdArc
            arc = aiter.Value();
            int
            maxl = get_max_length(isyms->Find(arc.ilabel));
            if (maxl == -1) {
                arc.weight = 999;
            }
            else {
                //Optionally penalize m-to-1 / 1-to-m links.  This produces
                // WORSE 1-best alignments, but results in better joint n-gram
                // models for small training corpora when using only the 1-best
                // alignment.  By further favoring 1-to-1 alignments the 1-best
                // alignment corpus results in a more flexible joint n-gram model
                // with regard to previously unseen data.
                //if( penalize==true ){
                arc.weight = alignment_model[arc.ilabel].Value() * maxl;
                //}else{
                //For larger corpora this is probably unnecessary.
                //arc.weight = alignment_model[arc.ilabel].Value();
                //}
            }
            if (arc.weight == LogWeight::Zero())
                arc.weight = 999;
            if (arc.weight != arc.weight)
                arc.weight = 999;
            aiter.SetValue(arc);
        }
    }

    VectorFst<StdArc> shortest;
    ShortestPath(fst, &shortest, nbest);
    RmEpsilon(&shortest);
    //Skip empty results.  This should only happen
    // in the following situations:
    //  1. seq1_del=false && len(seq1)<len(seq2)
    //  2. seq2_del=false && len(seq1)>len(seq2)
    //In both 1.and 2. the issue is that we need to
    // insert a 'skip' in order to guarantee at least
    // one valid alignment path through seq1*seq2, but
    // user params didn't allow us to.
    //Probably better to insert these where necessary
    // during initialization, regardless of user prefs.
    if (shortest.NumStates() == 0) {
        vector<PathData> dummy;
        return dummy;
    }
    FstPathFinder
    pathfinder(skipSeqs);
    pathfinder.isyms = isyms;
    pathfinder.findAllStrings(shortest);
    return pathfinder.paths;
}
/*
  .2msec for 256x256 grid
*/
int main()
{
  CL_SetupCore::init();

  srand(time(NULL));
  Field<int> field(80, 50);

  unsigned int start_time = CL_System::get_time();
  unsigned int end_time;

  for(int y = 0; y < field.get_height(); ++y)
    for(int x = 0; x < field.get_width(); ++x)
      {
        field(x,y) = (rand()%100) > 40 ? 0 : 1;
      }

  DijkstraPathfinder pathfinder(&field);

  Pos start;
  Pos end;

  for(int count = 0; count < 1000; ++count)
    {
  start.x = rand()%field.get_width();
  start.y = rand()%field.get_height();
  
  end.x = rand()%field.get_width();
  end.y = rand()%field.get_height();

      pathfinder.init(start, end);
      //pathfinder.display();

      //int i = 0;
      //std::cout << "Start: " << start.x << " " << start.y << std::endl;
      //std::cout << "End:   " << end.x << " " << end.y << std::endl;

      while(!pathfinder.finished())
        {
          //for(int i = 0; i < 10 && !pathfinder.finished(); ++i)
          pathfinder.process_one_open_node();

          //getchar();
        }
      if (1)
        {
          std::cout << "c" << std::endl;
          pathfinder.display();
          getchar();
        }
 
      //pathfinder.display();
      
      /*
        if (pathfinder.get_state() != DijkstraPathfinder::PATH_FOUND)
        {
        std::cout << "No Path could be found" << std::endl;
        }
        else
        {
        std::cout << "Found path" << std::endl;
        std::vector<Pos>& path = pathfinder.get_path();
        for (std::vector<Pos>::iterator i = path.begin(); i != path.end(); ++i)
        {
        std::cout << "[" << i->x << ", " << i->y << "] ";
        }       
        std::cout << std::endl;
        }
      */

      //      getchar();
      //std::cout << "round: " << ++i << std::endl;
    }
  end_time = CL_System::get_time();
  std::cout << "Msec: " << end_time - start_time << std::endl;

  CL_SetupCore::deinit();
}
Ejemplo n.º 17
0
// Pathfinder Thread
LPTHREAD_START_ROUTINE PATHFINDER_Proc(char *)
{
	EERIE_BACKGROUND * eb = ACTIVEBKG;
	PathFinder pathfinder(eb->nbanchors, eb->anchors,
	                      MAX_LIGHTS, (EERIE_LIGHT **)GLight,
	                      MAX_DYNLIGHTS, (EERIE_LIGHT **)PDL);

	bExitPathfinderThread = false;

	while (!bExitPathfinderThread)
	{
		QueryPerformanceCounter(&Pstart_chrono);

		if (WaitForSingleObject(PATHFINDER_MUTEX, PATHFINDER_MUTEX_WAIT) == WAIT_TIMEOUT)
			continue;

		PATHFINDER_WORKING = 1;

		if (EERIE_PATHFINDER_Get_Next_Request(&pr) && pr.isvalid)
		{

			PATHFINDER_REQUEST curpr;
			memcpy(&curpr, &pr, sizeof(PATHFINDER_REQUEST));
			CURPATHFINDIO = curpr.ioid;
			PATHFINDER_WORKING = 2;

			if (CURPATHFINDIO->ident == 43)
				CURPATHFINDIO->ident = 43;

			if (curpr.ioid && curpr.ioid->_npcdata)
			{
				unsigned long flags(MINOS_REGULAR);
				unsigned char found(0);
				float heuristic(PATHFINDER_HEURISTIC_MAX);

				pathfinder.SetCylinder(curpr.ioid->physics.cyl.radius, curpr.ioid->physics.cyl.height);

				if (curpr.ioid->_npcdata->behavior & BEHAVIOUR_FIGHT)
					flags |= MINOS_TACTIC;

				if (curpr.ioid->_npcdata->behavior & (BEHAVIOUR_SNEAK | BEHAVIOUR_HIDE))
					flags |= MINOS_STEALTH;

				if ((curpr.ioid->_npcdata->behavior & BEHAVIOUR_MOVE_TO)
				        || (curpr.ioid->_npcdata->behavior & BEHAVIOUR_GO_HOME))
				{
					float distance(EEDistance3D(&ACTIVEBKG->anchors[curpr.from].pos, &ACTIVEBKG->anchors[curpr.to].pos));

					if (distance < PATHFINDER_DISTANCE_MAX)
						heuristic = PATHFINDER_HEURISTIC_MIN + PATHFINDER_HEURISTIC_RANGE * (distance / PATHFINDER_DISTANCE_MAX);

					pathfinder.SetHeuristic(heuristic);
					found = pathfinder.Move(flags,
					                        curpr.from, curpr.to,
					                        curpr.returnnumber, curpr.returnlist);
				}
				else if (curpr.ioid->_npcdata->behavior & BEHAVIOUR_WANDER_AROUND)
				{
					if (curpr.ioid->_npcdata->behavior_param < PATHFINDER_DISTANCE_MAX)
						heuristic = PATHFINDER_HEURISTIC_MIN + PATHFINDER_HEURISTIC_RANGE * (curpr.ioid->_npcdata->behavior_param / PATHFINDER_DISTANCE_MAX);

					pathfinder.SetHeuristic(heuristic);
					found = pathfinder.WanderAround(flags,
					                                curpr.from, curpr.ioid->_npcdata->behavior_param,
					                                curpr.returnnumber, curpr.returnlist);
				}
				else if (curpr.ioid->_npcdata->behavior & (BEHAVIOUR_FLEE | BEHAVIOUR_HIDE))
				{
					if (curpr.ioid->_npcdata->behavior_param < PATHFINDER_DISTANCE_MAX)
						heuristic = PATHFINDER_HEURISTIC_MIN + PATHFINDER_HEURISTIC_RANGE * (curpr.ioid->_npcdata->behavior_param / PATHFINDER_DISTANCE_MAX);

					pathfinder.SetHeuristic(heuristic);
					float safedist = curpr.ioid->_npcdata->behavior_param + EEDistance3D(&curpr.ioid->target, &curpr.ioid->pos);

					found = pathfinder.Flee(flags,
					                        curpr.from,
					                        curpr.ioid->target,
					                        safedist, 
					                        curpr.returnnumber,
					                        curpr.returnlist);
				}
				else if (curpr.ioid->_npcdata->behavior & BEHAVIOUR_LOOK_FOR)
				{
					float distance(EEDistance3D(&curpr.ioid->pos, &curpr.ioid->target));

					if (distance < PATHFINDER_DISTANCE_MAX)
						heuristic = PATHFINDER_HEURISTIC_MIN + PATHFINDER_HEURISTIC_RANGE * (distance / PATHFINDER_DISTANCE_MAX);

					pathfinder.SetHeuristic(heuristic);
					found = pathfinder.LookFor(flags, curpr.from,
					                           curpr.ioid->target, curpr.ioid->_npcdata->behavior_param,
					                           curpr.returnnumber, curpr.returnlist);
				}
			}
		}

		CURPATHFINDIO = NULL;

		PATHFINDER_WORKING = 0;

		ReleaseMutex(PATHFINDER_MUTEX);
		QueryPerformanceCounter(&Pend_chrono);
		BENCH_PATHFINDER += (unsigned long)(Pend_chrono.QuadPart - Pstart_chrono.QuadPart);
		Sleep(PATHFINDER_UPDATE_INTERVAL);
	}

	//fix leaks memory but freeze characters
	//	pathfinder.Clean();

	PATHFINDER_WORKING = 0;

	ExitThread(0);

	return 0;
}