feat: track prev. pos. attempts to speed up bruteforcing

This commit is contained in:
ae 2025-06-01 22:05:22 +03:00
parent 271d8201e5
commit dcff8cd18e
Signed by: ae
GPG Key ID: 995EFD5C1B532B3E

View File

@ -91,8 +91,7 @@ func getTextBounds(text []string, size float64) (width, height int) {
}
func rectsOverlap(r1, r2 struct{ x, y, w, h int }) bool {
return !(r1.x+r1.w <= r2.x || r2.x+r2.w <= r1.x ||
r1.y+r1.h <= r2.y || r2.y+r2.h <= r1.y)
return !(r1.x+r1.w <= r2.x || r2.x+r2.w <= r1.x || r1.y+r1.h <= r2.y || r2.y+r2.h <= r1.y)
}
func drawTextWithOutline(canvas *image.RGBA, text []string, x, y int, textColor, outlineColor color.RGBA, size float64) {
@ -144,7 +143,18 @@ func drawTextWithOutline(canvas *image.RGBA, text []string, x, y int, textColor,
}
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
func findTextPositions(textData []*TextData, filename string) {
type attemptedPos struct {
x, y int
}
padding := 10
for i, data := range textData {
@ -172,12 +182,33 @@ func findTextPositions(textData []*TextData, filename string) {
continue
}
// track attempted positions to avoid redundancy
attempts := make([]attemptedPos, 0, maxPositioningAttempts)
// min. distance between attempts (1/5 of text height)
minAttemptDistance := max(h/5, 10)
isTooCloseToAttempted := func(x, y int) bool {
for _, pos := range attempts {
if abs(x-pos.x) < minAttemptDistance && abs(y-pos.y) < minAttemptDistance {
return true
}
}
return false
}
// try random positions
for attempt := 0; attempt < maxPositioningAttempts && !placed; attempt++ {
// gen. random pos.
x := rand.IntN(maxX-minX+1) + minX
y := rand.IntN(maxY-minY+1) + minY
// skip if too close to a previously attempt pos.
if isTooCloseToAttempted(x, y) {
continue
}
attempts = append(attempts, attemptedPos{x: x, y: y})
// bounding box for cur. text
curRect := struct{ x, y, w, h int }{
x: x,
@ -188,7 +219,7 @@ func findTextPositions(textData []*TextData, filename string) {
// checks of overlaps with already placed texts
overlaps := false
for j := 0; j < i; j++ {
for j := range i {
other := textData[j]
if !other.Positioned {
continue
@ -245,7 +276,7 @@ func findTextPositions(textData []*TextData, filename string) {
totalOverlapArea := 0
// calculate total overlap area with existing texts
for j := 0; j < i; j++ {
for j := range i {
other := textData[j]
if !other.Positioned {
continue