Last active
May 25, 2022 14:20
-
-
Save s1moe2/a85a5da7e2af25397de326d9714a6bbc to your computer and use it in GitHub Desktop.
Golang implementation of Bresenham's line algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
"os" | |
"strconv" | |
) | |
func main() { | |
x1, _ := strconv.Atoi(os.Args[1:][0]) | |
y1, _ := strconv.Atoi(os.Args[1:][1]) | |
p1 := point{ | |
x: x1, | |
y: y1, | |
} | |
x2, _ := strconv.Atoi(os.Args[1:][2]) | |
y2, _ := strconv.Atoi(os.Args[1:][3]) | |
p2 := point{ | |
x: x2, | |
y: y2, | |
} | |
fmt.Println(bresenhamPoints(p1, p2)) | |
} | |
type point struct { | |
x int | |
y int | |
} | |
func bresenhamPoints(p1, p2 point) []point { | |
dx := int(math.Abs(float64(p2.x) - float64(p1.x))) | |
sx := -1 | |
if p1.x < p2.x { | |
sx = 1 | |
} | |
dy := -int(math.Abs(float64(p2.y) - float64(p1.y))) | |
sy := -1 | |
if p1.y < p2.y { | |
sy = 1 | |
} | |
err := dx + dy | |
points := []point{} | |
for { | |
points = append(points, point{p1.x, p1.y}) | |
if p1.x == p2.x && p1.y == p2.y { | |
break | |
} | |
e2 := 2 * err | |
if e2 >= dy { | |
if p1.x == p2.x { | |
break | |
} | |
err = err + dy | |
p1.x = p1.x + sx | |
} | |
if e2 <= dx { | |
if p1.y == p2.y { | |
break | |
} | |
err = err + dx | |
p1.y = p1.y + sy | |
} | |
} | |
return points | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment