Skip to content

Commit

Permalink
perf(wordsoccupancy): implement caching to optimize performance
Browse files Browse the repository at this point in the history
  • Loading branch information
guo-yong-zhi committed Oct 21, 2024
1 parent 7e2c25d commit e169805
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/strategy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ function feelingoccupancy(imgs, border=0, bgvalue=imgs[1][1])
oc * 0.93
end

function wordsoccupancy!(wc)
function wordsoccupancy!(wc, cache=(-ones(length(wc)), Vector(undef, length(wc))))
words = wc.words
fonts = getfonts(wc)
angles = getangles(wc) ./ 180 .* π
border = 1
sizemax = size(wc.mask) .* (getparameter(wc, :volume) / prod(size(wc.mask))) .* 0.9
check = getparameter(wc, :maxfontsize0) == :auto
check && setparameter!(wc, minimum(sizemax), :maxfontsize)
imgs = Vector(undef, length(words))
szcache, imgs = cache
for i in 1:3
fontsizes = getfontsizes(wc)
success = true
Expand All @@ -64,6 +64,9 @@ function wordsoccupancy!(wc)
for j in ichunk:nchunk:length(words) # it is a more balance split strategy since the words is sorted by size
success || break
c, sz, ft, θ = words[j], fontsizes[j], fonts[j], angles[j]
if szcache[j] == sz # only check the fontsize, assume the font won't change
continue
end
img = Render.rendertext(string(c), sz, backgroundcolor=(0, 0, 0, 0), font=ft, border=border)
a, b = size(img)
imsz = max(a*abs(cos(θ)), b*abs(sin(θ))), max(a*abs(sin(θ)), b*abs(cos(θ)))
Expand All @@ -76,6 +79,7 @@ function wordsoccupancy!(wc)
end
end
imgs[j] = img
szcache[j] = sz
end
success || break
end
Expand Down Expand Up @@ -145,6 +149,7 @@ function findscale!(wc::WC; initialscale=0, density=0.3, maxiter=5, tolerance=0.
sc0 = 0.
tg0 = 0.
oneway_count = 1
occ_cache = (-ones(length(wc)), Vector(undef, length(wc)))
while true
step = step + 1
if step > maxiter
Expand All @@ -153,7 +158,7 @@ function findscale!(wc::WC; initialscale=0, density=0.3, maxiter=5, tolerance=0.
end
# cal tg1
setparameter!(wc, sc1, :scale)
tg1 = wordsoccupancy!(wc)
tg1 = wordsoccupancy!(wc, occ_cache)
dens = tg1 / area
@debug "⋯scale=$(getparameter(wc, :scale)), density=$dens\t" * (dens > density ? "" : "")
if tg1 > target
Expand Down

0 comments on commit e169805

Please sign in to comment.