Question

I've currently implemented the Bresenham line algorithm for a tile based world editor I'm developing. For Shift + Click functionality, I would like to render a line based off the selection rectangle from a tileset. This is simple, as I can just find the points on the line from point1 to point2 using the algorithm and draw the selection at each point.

The issue with this is that the points overlap when the selection rectangle is larger than one tile. The result is as seen below.

Current

My question is given all the points on a line, and the selection size, how can I get a result like this? Note that I want to stop drawing the selection once it goes past point2.

Desired

Here's what I have currently for rendering a line without respect to the selection size.

void renderPoint(Point point, bool invalidate = false)
{
    Rectangle selection = world.SelectionRectangle;

    int width = selection.Width / world.Settings.TileSize.Width,
        height = selection.Height / world.Settings.TileSize.Height,
        offsetX = (int)Math.Floor((float)width / 2),
        offsetY = (int)Math.Floor((float)height / 2);

    for (int x = point.X, sx = 0; x < point.X + width; x++, sx++)
    {
        for (int y = point.Y, sy = 0; y < point.Y + height; y++, sy++)
        {
            Point change = new Point(x - offsetX, y - offsetY);

            if (!changesUndo.ContainsKey(change))
                changesUndo[change] = world.GetTile(change);

            WorldTile tile = new WorldTile(selection.X + (sx * world.Settings.TileSize.Width), selection.Y + (sy * world.Settings.TileSize.Height), 0);

            world.SetTile(change.X, change.Y, tile);

            changesRedo[change] = tile;
        }
    }

    lastRenderedPoint = point;

    if (invalidate)
        world.InvalidateCanvas();
}

void renderLine(Point p1, Point p2)
{
    List<Point> points = pointsOnLine(p1, p2);

    for (int i = 0; i < points.Count; i++)
        renderPoint(points[i], i == points.Count - 1);
}

Leave a comment if you need more context of my code.

Was it helpful?

Solution

If the points are rendered with Bresenham, then you have to skip every 'n-1' out of 'n' points, where 'n' is the selection size in the major direction of the line (i.e. if it's a mostly horizontal line, the width).

Something like this? :

void renderLine(Point p1, Point p2)
{
    List<Point> points = pointsOnLine(p1, p2);

    int dx = Abs(p2.x - p1.x);
    int dy = Abs(p2.y - p1.y);

    Rectangle selection = world.SelectionRectangle;

    int incr = selection.Width / world.Settings.TileSize.Width;
    if(dy > dx)
    {
        incr = selection.Height / world.Settings.TileSize.Height;
    }

    int lastPoint = (points.Count-1) / incr;
    lastPoint *= incr;

    for (int i = 0; i <= lastPoint; i+=incr)
        renderPoint(points[i], i == lastPoint);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top