Exemple #1
0
void copyByIndex(const std::vector<T>& vals,
                 std::vector<T>& newVals,
                 const std::tr1::unordered_set<size_t> &indices) {
  Contained contained(indices);
  for (size_t i=0; i<vals.size(); ++i)
    if (contained(i)) newVals.push_back(vals[i]);
}
Exemple #2
0
static int init_astar_object (astar_t* astar, const char *grid, int *solLength, int boundX, int boundY, int start, int end)
{
	
	*solLength = -1;
	struct coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;

	if (start >= size || start < 0 || end >= size || end < 0)
		return 0;

	struct coord_t startCoord = getCoord (bounds, start);
	struct coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return 0;

	astar->solutionLength = solLength;
	astar->bounds = bounds;
	astar->start = start;
	astar->goal = end;
	astar->grid = grid;

	astar->open = createQueue();
	if (!astar->open)
		return 0;

	astar->closed = (char*)malloc (size);
	if (!astar->closed) {
		freeQueue (astar->open);
		return 0;
	}

	astar->gScores = (double*)malloc (size * sizeof (double));
	if (!astar->gScores) {
		freeQueue (astar->open);
		free (astar->closed);
		return 0;
	}

	astar->cameFrom = (node*)malloc (size * sizeof (int));
	if (!astar->cameFrom) {
		freeQueue (astar->open);
		free (astar->closed);
		free (astar->gScores);
		return 0;
	}

	memset (astar->closed, 0, size);

	astar->gScores[start] = 0;
	astar->cameFrom[start] = -1;

	insert (astar->open, astar->start, estimateDistance (startCoord, endCoord));

	return 1;
}
Exemple #3
0
/*************************************************************************
 *
 *N  bounding_select
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *    This function reads the bounding rectangle table to weed out the
 *    local primitives.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Parameters:
 *A
 *    path      <input> == (char *) path to the bounding rectangle table.
 *    mapextent <input> == (extent_type) map extent to compare.
 *    dec_degrees <input> == (int) flag to indicate if data is in decimal
 *                                 degrees.
 *    bounding_select <output> == (set_type) set of bounding rectangle ids.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   History:
 *H
 *    Barry Michaels   May 1991                           DOS Turbo C
 *E
 *************************************************************************/
set_type bounding_select( char *path, extent_type mapextent,
			  int dec_degrees )
{
   vpf_table_type table;
   set_type set;
   rspf_int32 i, count;
   extent_type box, pextent;
   double x1,y1,x2,y2;
   row_type row;
   int XMIN_,YMIN_,XMAX_,YMAX_;

   /* Project all extents to plate-carree for cartesian comparisons */
   /* (decimal degree coordinate systems) */

   x1 = mapextent.x1; y1 = mapextent.y1;
   x2 = mapextent.x2; y2 = mapextent.y2;
   if (dec_degrees) {
      set_plate_carree_parameters( central_meridian(x1,x2), 0.0, 1.0 );
      pcarree_xy(&x1,&y1);
      pcarree_xy(&x2,&y2);
   }
   pextent.x1 = x1; pextent.y1 = y1;
   pextent.x2 = x2; pextent.y2 = y2;

   table = vpf_open_table(path,disk,"rb",NULL);
   XMIN_ = table_pos("XMIN",table);
   YMIN_ = table_pos("YMIN",table);
   XMAX_ = table_pos("XMAX",table);
   YMAX_ = table_pos("YMAX",table);
   set = set_init(table.nrows+1);
   for (i=1;i<=table.nrows;i++) {
      row = read_next_row(table);
      get_table_element(XMIN_,row,table,&box.x1,&count);
      get_table_element(YMIN_,row,table,&box.y1,&count);
      get_table_element(XMAX_,row,table,&box.x2,&count);
      get_table_element(YMAX_,row,table,&box.y2,&count);
      free_row(row,table);

      x1 = box.x1; y1 = box.y1;
      x2 = box.x2; y2 = box.y2;
      if (dec_degrees) {
	 pcarree_xy(&x1,&y1);
	 pcarree_xy(&x2,&y2);
      }
      box.x1 = x1; box.y1 = y1;
      box.x2 = x2; box.y2 = y2;

      if ( contained(box,pextent) || contained(pextent,box) ) {
	 set_insert(i,set);
      }
   }
   vpf_close_table(&table);

   return set;
}
Exemple #4
0
void removeByIndex(std::vector<T>& vals,
                   const std::tr1::unordered_set<size_t> &indices) {
  Contained contained(indices);
  int last = 0;
  for (size_t i=0; i<vals.size(); ++i, ++last) {
    while (contained(i)) ++i;
    if (i >= vals.size()) break;
    vals[last] = vals[i];
  }
  vals.resize(last);
}
Exemple #5
0
void seissol::writer::ReceiverWriter::addPoints(  std::vector<glm::dvec3> const&    points,
                                                  MeshReader const&                 mesh,
                                                  seissol::initializers::Lut const& ltsLut,
                                                  seissol::initializers::LTS const& lts,
                                                  GlobalData const*                 global ) {
  int rank = seissol::MPI::mpi.rank();
  unsigned numberOfPoints = points.size();
  std::vector<short> contained(numberOfPoints);
  std::vector<unsigned> meshIds(numberOfPoints);
  
  /// \todo Find a nicer solution that is not so hard-coded.
  std::vector<unsigned> quantities{0, 1, 2, 3, 4, 5, 6, 7, 8};

  logInfo(rank) << "Finding meshIds for receivers...";
  initializers::findMeshIds(points.data(), mesh, numberOfPoints, contained.data(), meshIds.data());
#ifdef USE_MPI
  logInfo(rank) << "Cleaning possible double occurring receivers for MPI...";
  initializers::cleanDoubles(contained.data(), numberOfPoints);
#endif

  logInfo(rank) << "Mapping receivers to LTS cells...";
  for (unsigned point = 0; point < numberOfPoints; ++point) {
    if (contained[point] == 1) {
      unsigned meshId = meshIds[point];
      unsigned cluster = ltsLut.cluster(meshId);

      for (unsigned c = m_receiverClusters.size(); c <= cluster; ++c) {
        m_receiverClusters.emplace_back(global, quantities, m_samplingInterval, syncInterval());
      }

      writeHeader(point, points[point]);
      m_receiverClusters[cluster].addReceiver(meshId, point, points[point], mesh, ltsLut, lts);
    }
  }
}
Exemple #6
0
static void split_st(parsecontext& pc, const std::string& s, const std::string& delim, char quote, std::vector<std::string>& ret)
{
    if( pc.i == s.size() || contained(s[pc.i], delim) )
    {
        if(pc.tmp.length() != 0)
        {
            ret.push_back(pc.tmp);
        }
        pc.tmp = "";
        if(pc.i == s.size())
        {
            // Parse end
            return;
        }else
        {
            pc.i++;
            split_st(pc, s, delim, quote, ret);
        }
    }else if(s[pc.i] == '\\')
    {
        pc.i++;
        split_ibs0(pc, s, delim, quote, ret);
    }else if(s[pc.i] == quote)
    {
        pc.i++;
        split_inq(pc, s, delim, quote, ret);
    }else
    {
        pc.tmp += s[pc.i];
        pc.i++;
        split_st(pc, s, delim, quote, ret);
    }
}
Exemple #7
0
/**
 * Split specified string with specified delimiter
 *
 * @param s Input string
 * @param delim Delimiter string
 * @return vector of string
 *
 * @note Each characters in delim is considered as delimiter character
 */
std::vector<std::string> split(const std::string& s, const std::string& delim)
{
    std::vector<std::string> strings;
    std::string tmp;

    for(int i = 0; i < s.size(); ++i)
    {
        if(contained(s[i], delim))
        {
            if(tmp.length() != 0)
            {
                strings.push_back(tmp);
            }
            tmp = "";
        }else
        {
            tmp += s[i];
        }
    }

    if(tmp.length() != 0)
    {
        strings.push_back(tmp);
    }

    return strings;
}
TEST(PositionTest, IfOnePositionCompletelyContainedInOtherThenTheyOverlap){
	Position container(Vector2(0, 0), 50, 50);
	Position contained(Vector2(25, 25), 10, 10);

	EXPECT_TRUE(container.overlaps(contained));
	EXPECT_TRUE(contained.overlaps(container));
}
bool MultiBlockManagement3D::findAllLocalRepresentations (
            plint iX, plint iY, plint iZ, std::vector<plint>& foundId,
            std::vector<plint>& foundX, std::vector<plint>& foundY,
            std::vector<plint>& foundZ ) const
{
    bool hasBulkCell = false;
    // First, search in all blocks which are local to the current processor,
    // including in the envelopes.
    for (pluint iBlock=0; iBlock < localInfo.getBlocks().size(); ++iBlock) {
        plint blockId = localInfo.getBlocks()[iBlock];
        SmartBulk3D bulk(sparseBlock, envelopeWidth, blockId);
        if (contained(iX, iY, iZ, bulk.computeEnvelope()))
        {
            if (contained(iX, iY, iZ, bulk.getBulk())) {
                hasBulkCell = true;
                foundId.insert(foundId.begin(), blockId);
                foundX.insert(foundX.begin(), bulk.toLocalX(iX));
                foundY.insert(foundY.begin(), bulk.toLocalY(iY));
                foundZ.insert(foundZ.begin(), bulk.toLocalZ(iZ));
            }
            else {
                foundId.push_back(blockId);
                foundX.push_back(bulk.toLocalX(iX));
                foundY.push_back(bulk.toLocalY(iY));
                foundZ.push_back(bulk.toLocalZ(iZ));
            }
        }
    }
    // Here's a subtlety: with periodic boundary conditions, one may need to take into
    //   account a cell which is not inside the boundingBox, because it's at the opposite
    //   boundary. Therefore, this loop checks all blocks which overlap with the current
    //   one by periodicity.
    for (pluint iOverlap=0; iOverlap<localInfo.getPeriodicOverlapWithRemoteData().size();
         ++iOverlap)
    {
        Overlap3D overlap = localInfo.getPeriodicOverlapWithRemoteData()[iOverlap].overlap;
        if (contained(iX,iY,iZ, overlap.getOriginalCoordinates())) {
            plint overlapId = overlap.getOverlapId();
            foundId.push_back(overlapId);
            SmartBulk3D bulk(sparseBlock, envelopeWidth, overlapId);
            foundX.push_back(bulk.toLocalX(iX-overlap.getShiftX()));
            foundY.push_back(bulk.toLocalY(iY-overlap.getShiftY()));
            foundZ.push_back(bulk.toLocalZ(iZ-overlap.getShiftZ()));
        }
    }
    return hasBulkCell;
}
Exemple #10
0
/* Figure out if we've underrun, and act if appropriate. */
void DSoundBuf::CheckUnderrun( int iCursorStart, int iCursorEnd )
{
	/* If the buffer is full, we can't be underrunning. */
	if( m_iBufferBytesFilled >= m_iBufferSize )
		return;

	/* If nothing is expected to be filled, we can't underrun. */
	if( iCursorStart == iCursorEnd )
		return;

	/* If we're already in a recovering-from-underrun state, stop. */
	if( m_iExtraWriteahead )
		return;

	int iFirstByteFilled = m_iWriteCursor - m_iBufferBytesFilled;
	wrap( iFirstByteFilled, m_iBufferSize );

	/* If the end of the play cursor has data, we haven't underrun. */
	if( m_iBufferBytesFilled > 0 && contained(iFirstByteFilled, m_iWriteCursor, iCursorEnd) )
		return;

	/* Extend the writeahead to force fill as much as required to stop underrunning.
	 * This has a major benefit: if we havn't skipped so long we've passed a whole
	 * buffer (64k = ~350ms), this doesn't break stride.  We'll skip forward, but
	 * the beat won't be lost, which is a lot easier to recover from in play. */
	/* XXX: If this happens repeatedly over a period of time, increase writeahead. */
	/* XXX: What was I doing here?  This isn't working.  We want to know the writeahead
	 * value needed to fill from the current iFirstByteFilled all the way to iCursorEnd. */
	// int iNeededWriteahead = (iCursorStart + writeahead) - m_iWriteCursor;
	int iNeededWriteahead = iCursorEnd - iFirstByteFilled;
	wrap( iNeededWriteahead, m_iBufferSize );
	if( iNeededWriteahead > m_iWriteAhead )
	{
		m_iExtraWriteahead = iNeededWriteahead - m_iWriteAhead;
		m_iWriteAhead = iNeededWriteahead;
	}

	int iMissedBy = iCursorEnd - m_iWriteCursor;
	wrap( iMissedBy, m_iBufferSize );

	CString s = ssprintf( "underrun: %i..%i (%i) filled but cursor at %i..%i; missed it by %i",
		iFirstByteFilled, m_iWriteCursor, m_iBufferBytesFilled, iCursorStart, iCursorEnd, iMissedBy );

	if( m_iExtraWriteahead )
		s += ssprintf( "; extended writeahead by %i to %i", m_iExtraWriteahead, m_iWriteAhead );

	s += "; last: ";
	for( int i = 0; i < 4; ++i )
		s += ssprintf( "%i, %i; ", m_iLastCursors[i][0], m_iLastCursors[i][1] );

	LOG->Trace( "%s", s.c_str() );
}
Exemple #11
0
int
main ()
{
  char *first = "first";
  char *second = "we should find the first inside the second";

  printf ("%s :: %s\ncontained %s\n", first, second,
      contained (first, second) ? "yes" : "no");

  first = "first";
  second = "we shouldn't find it inside the second";

  printf ("%s :: %s\ncontained %s\n", first, second,
      contained (first, second) ? "yes" : "no");

  first = NULL;
  printf ("%s :: %s\ncontained %s\n", first, second,
      contained (first, second) ? "yes" : "no");

  first = "";
  printf ("%s :: %s\ncontained %s\n", first, second,
      contained (first, second) ? "yes" : "no");
}
Exemple #12
0
static  void split_ibs1(parsecontext& pc, const std::string& s, const std::string& delim, char quote, std::vector<std::string>& ret)
{
    if(pc.i == s.size())
    {
        throw "Parse error";
    }
    else if(s[pc.i] == quote || s[pc.i] == '\\' || contained(s[pc.i], delim))
    {
        pc.tmp += s[pc.i];
        pc.i++;
        split_inq(pc, s, delim, quote, ret);
    }else
    {
        throw "Parse error";
    }
}
void LocalMultiBlockInfo3D::computeAllPeriodicOverlaps (
        SparseBlockStructure3D const& sparseBlock )
{
    for (pluint iBlock=0; iBlock<myBlocks.size(); ++iBlock) {
        plint blockId = myBlocks[iBlock];
        Box3D bulk;
        sparseBlock.getBulk(blockId, bulk);
        // Speed optimization: execute the test for periodicity
        //   only for bulk-domains which touch the bounding box.
        if (!contained (
                    bulk.enlarge(1), sparseBlock.getBoundingBox() ) )
        {
            computePeriodicOverlaps(sparseBlock, blockId);
        }
    }
}
Exemple #14
0
// constructor
// computes biconnected componets of original graph
// does not create a copy graph
ExpansionGraph::ExpansionGraph(const Graph &G) :
	m_compNum(G), m_adjComponents(G), m_vCopy(G,nullptr)
{
	m_vOrig.init(*this,nullptr);
	m_vRep .init(*this,nullptr);
	m_eOrig.init(*this,nullptr);

	// compute biconnected components
	int numComp = biconnectedComponents(G,m_compNum);

	// for each component, build list of contained edges
	m_component.init(numComp);

	for(edge e : G.edges)
		m_component[m_compNum[e]].pushBack(e);

	// for each vertex v, build list of components containing v
	NodeSetSimple contained(G);
	for(int i = 0; i < numComp; ++i)
	{
		SListConstIterator<edge> it;
		for(edge e : m_component[i])
		{
			node v = e->source();
			if (contained.isMember(v) == false) {
				contained.insert(v);
				m_adjComponents[v].pushBack(i);
			}

			v = e->target();
			if (contained.isMember(v) == false) {
				contained.insert(v);
				m_adjComponents[v].pushBack(i);
			}
		}

		contained.clear();
	}
}
Exemple #15
0
int main(int argc, char * argv[])
{
  setlocale(LC_ALL, "");

  struct wordlist wl;
  if (init_wl(&wl))
    return 1;
  if (argc < 2)
    return usage(argv[0]);

  switch(argv[1][0])
    {
      case 's':
        return single(&wl, argc, argv);
      case 'm':
        return multi(&wl, argc, argv);
      case 'r':
        return random(&wl, argc, argv);
      case 'c':
        return contained(&wl, argc, argv);
      default:
        return usage(argv[0]);
    }
}
void
MergeTreeParser::MergeTreeVisitor::finalizeComponent(
		float                        /*value*/,
		PixelList::const_iterator    begin,
		PixelList::const_iterator    end) {

	bool changed = (begin != _prevBegin || end != _prevEnd);

	_prevBegin = begin;
	_prevEnd   = end;

	if (!changed)
		return;

	LOG_ALL(mergetreeparserlog) << "found a new component" << std::endl;

	size_t size = end - begin;
	bool validSize  = (size >= _minSize && (_maxSize == 0 || size < _maxSize));

	if (!validSize)
		return;

	// get all prospective children of this component

	std::vector<Crag::CragNode> children;
	int level = 0;
	while (!_roots.empty() && contained(_extents[_roots.top()], std::make_pair(begin, end))) {

		children.push_back(_roots.top());
		level = std::max(level, _crag.getLevel(_roots.top()) + 1);
		_roots.pop();
	}

	if (_maxMerges >= 0 && level > _maxMerges) {

		for (auto c = children.rbegin(); c != children.rend(); c++)
			_roots.push(*c);
		return;
	}

	LOG_ALL(mergetreeparserlog) << "add it to crag" << std::endl;

	// create a node (all nodes from a 2D merge-tree are slice nodes)
	Crag::CragNode node = _crag.addNode(Crag::SliceNode);
	_extents[node] = std::make_pair(begin, end);

	// connect it to children
	for (Crag::CragNode child : children)
		_crag.addSubsetArc(child, node);

	bool isLeafNode = (level == 0);
	LOG_ALL(mergetreeparserlog) << "is" << (isLeafNode ? "" : " not") << " a leaf node" << std::endl;

	// extract and set volume

	util::box<unsigned int, 3> boundingBox;

	for (PixelList::const_iterator i = begin; i != end; i++)
		boundingBox.fit(
				util::box<unsigned int, 3>(
						util::point<unsigned int, 3>(
								i->x(),     i->y(),     0),
						util::point<unsigned int, 3>(
								i->x() + 1, i->y() + 1, 1)));

	std::shared_ptr<CragVolume> volume = std::make_shared<CragVolume>(
			boundingBox.width(),
			boundingBox.height(),
			boundingBox.depth(),
			false);

	for (PixelList::const_iterator i = begin; i != end; i++)
		(*volume)[i->project<3>() - boundingBox.min()] = true;

	util::point<float, 3> volumeOffset = _offset + boundingBox.min()*_resolution;

	volume->setResolution(_resolution);
	volume->setOffset(volumeOffset);
	_volumes.setVolume(node, volume);

	// put the new node on the stack
	_roots.push(node);
}
Exemple #17
0
int *astar_unopt_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	astar_t astar;
	coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;


	if (start >= size || start < 0 || end >= size || end < 0)
		return NULL;

	coord_t startCoord = getCoord (bounds, start);
	coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return NULL;

	queue *open = createQueue();
	char closed [size];
	double gScores [size];
	int cameFrom [size];

	astar.solutionLength = solLength;
	*astar.solutionLength = -1;
	astar.bounds = bounds;
	astar.start = start;
	astar.goal = end;
	astar.grid = grid;
	astar.open = open;
	astar.closed = closed;
	astar.gScores = gScores;
	astar.cameFrom = cameFrom;

	memset (closed, 0, sizeof(closed));

	gScores[start] = 0;
	cameFrom[start] = -1;

	insert (open, start, estimateDistance (startCoord, endCoord));

	while (open->size) {
		int node = findMin (open)->value; 
		coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (open);
			return recordSolution (&astar);
		}

		deleteMin (open);
		closed[node] = 1;

		for (int dir = 0; dir < 8; dir++)
		{
			coord_t newCoord = adjustInDirection (nodeCoord, dir);
			int newNode = getIndex (bounds, newCoord);

			if (!contained (bounds, newCoord) || !grid[newNode])
				continue;

			if (closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (open);
	return NULL;
}
Exemple #18
0
int *astar_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	*solLength = -1;
	astar_t astar;
	coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;


	if (start >= size || start < 0 || end >= size || end < 0)
		return NULL;

	coord_t startCoord = getCoord (bounds, start);
	coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return NULL;

	queue *open = createQueue();
	char closed [size];
	double gScores [size];
	int cameFrom [size];

	astar.solutionLength = solLength;
	astar.bounds = bounds;
	astar.start = start;
	astar.goal = end;
	astar.grid = grid;
	astar.open = open;
	astar.closed = closed;
	astar.gScores = gScores;
	astar.cameFrom = cameFrom;

	memset (closed, 0, sizeof(closed));

	gScores[start] = 0;
	cameFrom[start] = -1;

	insert (open, start, estimateDistance (startCoord, endCoord));
	while (open->size) {
		int node = findMin (open)->value; 
		coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (open);
			return recordSolution (&astar);
		}

		deleteMin (open);
		closed[node] = 1;

		direction from = directionWeCameFrom (&astar, 
						      node,
						      cameFrom[node]);

		directionset dirs = 
			forcedNeighbours (&astar, nodeCoord, from) 
		      | naturalNeighbours (from);

		for (int dir = nextDirectionInSet (&dirs); dir != NO_DIRECTION; dir = nextDirectionInSet (&dirs))
		{
			int newNode = jump (&astar, dir, node);
			coord_t newCoord = getCoord (bounds, newNode);

			// this'll also bail out if jump() returned -1
			if (!contained (bounds, newCoord))
				continue;

			if (closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (open);
	return NULL;
}
Exemple #19
0
// is this coordinate within the map bounds, and also walkable?
static int isEnterable (astar_t *astar, coord_t coord)
{
	node node = getIndex (astar->bounds, coord);
	return contained (astar->bounds, coord) && 
		astar->grid[node];
}
Exemple #20
0
int *astar_unopt_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	astar_t astar;

	if (!init_astar_object (&astar, grid, solLength, boundX, boundY, start, end))
		return NULL;


	//coord_t bounds;
	//struct coord_t;// bounds;//endCoord;
	//bounds = {boundX, boundY};
	//endCoord = getCoord (bounds, end);
	
	struct coord_t bounds, endCoord;
	bounds.x = boundX; bounds.y = boundY;
	endCoord = getCoord(bounds, end);

	while (astar.open->size) {
		int dir;
		int node = findMin (astar.open)->value; 
		struct coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (astar.open);
			free (astar.closed);
			free (astar.gScores);

			int *rv = recordSolution (&astar);

			free (astar.cameFrom);

			return rv;
		}

		deleteMin (astar.open);
		astar.closed[node] = 1;

		for (dir = 0; dir < 8; dir++)
		{
			struct coord_t newCoord = adjustInDirection (nodeCoord, dir);
			int newNode = getIndex (bounds, newCoord);

			if (!contained (bounds, newCoord) || !grid[newNode])
				continue;

			if (astar.closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (astar.open);
	free (astar.closed);
	free (astar.gScores);
	free (astar.cameFrom);
	return NULL;
}
Exemple #21
0
int *astar_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	astar_t astar;
	if (!init_astar_object (&astar, grid, solLength, boundX, boundY, start, end))
		return NULL;

	struct coord_t bounds = {boundX, boundY};
	struct coord_t endCoord = getCoord (bounds, end);

	while (astar.open->size) {
		int dir;
		int node = findMin (astar.open)->value; 
		struct coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (astar.open);
			free (astar.closed);
			free (astar.gScores);

			int *rv = recordSolution (&astar);

			free (astar.cameFrom);

			return rv;
		}

		deleteMin (astar.open);
		astar.closed[node] = 1;

		direction from = directionWeCameFrom (&astar, 
						      node,
						      astar.cameFrom[node]);

		directionset dirs = 
			forcedNeighbours (&astar, nodeCoord, from) 
		      | naturalNeighbours (from);

		for (dir = nextDirectionInSet (&dirs); dir != NO_DIRECTION; dir = nextDirectionInSet (&dirs))
		{
			int newNode = jump (&astar, dir, node);
			struct coord_t newCoord = getCoord (bounds, newNode);

			// this'll also bail out if jump() returned -1
			if (!contained (bounds, newCoord))
				continue;

			if (astar.closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (astar.open);
	free (astar.closed);
	free (astar.gScores);
	free (astar.cameFrom);

	return NULL;
}
Exemple #22
0
static void
__r_insert_node (struct rtree_node *node, const BoxType * query,
                 int manage, bool force)
{

#ifdef SLOW_ASSERTS
  assert (__r_node_is_good (node));
#endif
  /* Ok, at this point we must already enclose the query or we're forcing
   * this node to expand to enclose it, so if we're a leaf, simply store
   * the query here
   */

  if (node->flags.is_leaf)
    {
      register int i;

      if (UNLIKELY (manage))
        {
          register int flag = 1;

          for (i = 0; i < M_SIZE; i++)
            {
              if (!node->u.rects[i].bptr)
                break;
              flag <<= 1;
            }
          node->flags.manage |= flag;
        }
      else
        {
          for (i = 0; i < M_SIZE; i++)
            if (!node->u.rects[i].bptr)
              break;
        }
      /* the node always has an extra space available */
      node->u.rects[i].bptr = query;
      node->u.rects[i].bounds = *query;
      /* first entry in node determines initial bounding box */
      if (i == 0)
        node->box = *query;
      else if (force)
        {
          MAKEMIN (node->box.X1, query->X1);
          MAKEMAX (node->box.X2, query->X2);
          MAKEMIN (node->box.Y1, query->Y1);
          MAKEMAX (node->box.Y2, query->Y2);
        }
      if (i < M_SIZE)
        {
          sort_node (node);
          return;
        }
      /* we must split the node */
      split_node (node);
      return;
    }
  else
    {
      int i;
      struct rtree_node *best_node;
      double score, best_score;

      if (force)
        {
          MAKEMIN (node->box.X1, query->X1);
          MAKEMAX (node->box.X2, query->X2);
          MAKEMIN (node->box.Y1, query->Y1);
          MAKEMAX (node->box.Y2, query->Y2);
        }

      /* this node encloses it, but it's not a leaf, so descend the tree */

      /* First check if any children actually encloses it */
      assert (node->u.kids[0]);
      for (i = 0; i < M_SIZE; i++)
        {
          if (!node->u.kids[i])
            break;
          if (contained (node->u.kids[i], query))
            {
              __r_insert_node (node->u.kids[i], query, manage, false);
              sort_node (node);
              return;
            }
        }

      /* see if there is room for a new leaf node */
      if (node->u.kids[0]->flags.is_leaf && i < M_SIZE)
        {
          struct rtree_node *new_node;
          new_node = (struct rtree_node *)calloc (1, sizeof (*new_node));
          new_node->parent = node;
          new_node->flags.is_leaf = true;
          node->u.kids[i] = new_node;
          new_node->u.rects[0].bptr = query;
          new_node->u.rects[0].bounds = *query;
          new_node->box = *query;
          if (UNLIKELY (manage))
            new_node->flags.manage = 1;
          sort_node (node);
          return;
        }

      /* Ok, so we're still here - look for the best child to push it into */
      best_score = penalty (node->u.kids[0], query);
      best_node = node->u.kids[0];
      for (i = 1; i < M_SIZE; i++)
        {
          if (!node->u.kids[i])
            break;
          score = penalty (node->u.kids[i], query);
          if (score < best_score)
            {
              best_score = score;
              best_node = node->u.kids[i];
            }
        }
      __r_insert_node (best_node, query, manage, true);
      sort_node (node);
      return;
    }
}