Files
beatglow/draw/draw.go
T
2026-10-29 17:29:41 +01:00

164 lines
3.1 KiB
Go

// Package draw contains screen drawing routines.
package draw
import (
"image"
"image/color"
"image/draw"
)
// Image is a type alias for the Go package.
type Image = draw.Image
// Line draws a line from (x0, y0) to (x1, y1).
func Line(dst Image, c color.Color, x0, y0, x1, y1 int) {
PolyLine(dst, c, image.Point{X: x0, Y: y0}, image.Point{X: x1, Y: y1})
}
// PolyLine draws a multi point line between the specified points.
func PolyLine(dst Image, c color.Color, points ...image.Point) {
if l := len(points); l < 1 {
return
} else if l == 1 {
points = append(points, points[0])
}
for i, l := 0, len(points)-1; i < l; i++ {
a, b := points[i], points[i+1]
bresenham(dst, c, a.X, a.Y, b.X, b.Y)
}
}
// Rectangle draws an empty rectangle.
func Rectangle(dst Image, c color.Color, x, y, w, h int) {
Line(dst, c, x+0, y+0, x+w, y+0)
Line(dst, c, x+w, y+0, x+w, y+h)
Line(dst, c, x+0, y+h, x+w, y+h)
Line(dst, c, x+0, y+0, x+0, y+h)
}
// FilledRectangle draws a filled rectangle from (x, y) to (x + w, y + h).
func FilledRectangle(dst Image, c color.Color, x, y, w, h int) {
for dy := 0; dy < h; dy++ {
Line(dst, c, x, y+dy, x+w, y+dy)
}
}
// Generalized with integer
func bresenham(dst Image, c color.Color, x1, y1, x2, y2 int) {
var dx, dy, e, slope int
// Because drawing p1 -> p2 is equivalent to draw p2 -> p1,
// I sort points in x-axis order to handle only half of possible cases.
if x1 > x2 {
x1, y1, x2, y2 = x2, y2, x1, y1
}
dx, dy = x2-x1, y2-y1
// Because point is x-axis ordered, dx cannot be negative
if dy < 0 {
dy = -dy
}
switch {
// Is line a point ?
case x1 == x2 && y1 == y2:
dst.Set(x1, y1, c)
// Is line an horizontal ?
case y1 == y2:
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
}
dst.Set(x1, y1, c)
// Is line a vertical ?
case x1 == x2:
if y1 > y2 {
y1, y2 = y2, y1
}
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1++
}
dst.Set(x1, y1, c)
// Is line a diagonal ?
case dx == dy:
if y1 < y2 {
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
y1++
}
} else {
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
y1--
}
}
dst.Set(x1, y1, c)
// wider than high ?
case dx > dy:
if y1 < y2 {
// BresenhamDxXRYD(img, x1, y1, x2, y2, col)
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
e -= dy
if e < 0 {
y1++
e += slope
}
}
} else {
// BresenhamDxXRYU(img, x1, y1, x2, y2, col)
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
e -= dy
if e < 0 {
y1--
e += slope
}
}
}
dst.Set(x2, y2, c)
// higher than wide.
default:
if y1 < y2 {
// BresenhamDyXRYD(img, x1, y1, x2, y2, col)
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1++
e -= dx
if e < 0 {
x1++
e += slope
}
}
} else {
// BresenhamDyXRYU(img, x1, y1, x2, y2, col)
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1--
e -= dx
if e < 0 {
x1++
e += slope
}
}
}
dst.Set(x2, y2, c)
}
}