ruen-ui/RuenUI/Optimizer.lua

411 lines
23 KiB
Lua
Raw Normal View History

local _, P = ...
-- Explicit, bounded scene calibration. No idle polling after a profile settles.
-- Graphics are reversible; hardware/thermal evidence is supplied by the companion.
local f, running, session, pendingLoad, loading, deferredEnvironment
local modes = {'world', 'dungeon', 'raid', 'battleground'}
local function say(en, ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en, ru or en)) end
local function validFPS(value)
local n = tonumber(value)
if n and n >= 20 and n <= 240 and n == math.floor(n) then return n end
end
local function db()
RuenUIDB.optimizer = RuenUIDB.optimizer or {original={}, profiles={}}
local d = RuenUIDB.optimizer
d.original = d.original or {}; d.profiles = d.profiles or {}
for _, name in ipairs(modes) do d.profiles[name] = d.profiles[name] or {tier=1} end
return d
end
local function mode()
local inside, kind = IsInInstance()
if inside and kind == 'raid' then return 'raid' end
if inside and (kind == 'pvp' or kind == 'arena') then return 'battleground' end
if inside then return 'dungeon' end
return 'world'
end
local function fingerprint()
local w,h = GetPhysicalScreenSize()
return w..'x'..h..':'..(C_CVar.GetCVar('gxAdapter') or '')..':'..(C_CVar.GetCVar('gxApi') or '')
end
local function hardware()
local h = P.hardwareProfile or {}
if not h.checkedAt or time()-h.checkedAt > 604800 or time() < h.checkedAt then return {} end
return h
end
local fields = {'ShadowQuality','SSAO','ViewDistance','EnvironmentDetail','GroundClutter',
'LiquidDetail','ComputeEffects','LightMode','PBRLiquidDetail'}
local tiers = {
{0,0,1,1,1,0,0,0,0}, {1,0,2,2,2,1,1,0,0}, {2,1,3,3,3,2,2,1,0},
{2,1,5,5,4,3,2,1,1}, {3,2,7,6,5,3,3,2,1},
}
local settings = {
{'graphicsShadowQuality','Shadows','Тени',{'Low','Fair','Good','High','Ultra','Ultra High'}},
{'graphicsSSAO','Ambient shading','Рассеянное затенение',{'Off','Low','Good','High','Ultra'}},
{'graphicsLightMode','Lighting','Освещение',{'Fair','Good','High','Ultra'}},
{'graphicsViewDistance','View distance','Дальность видимости','distance'},
{'graphicsEnvironmentDetail','Environment detail','Детализация окружения','distance'},
{'graphicsGroundClutter','Ground clutter','Детализация земли','distance'},
{'graphicsLiquidDetail','Water','Вода',{'Low','Fair','Good','High'}},
{'graphicsPBRLiquidDetail','Modern water','Современная вода',{'Low','High','Ultra'}},
{'graphicsComputeEffects','Compute effects','Вычисляемые эффекты',{'Low','Fair','Good','High','Ultra'}},
{'graphicsProjectedTextures','Ground spell indicators','Наземные эффекты заклинаний','toggle'},
{'graphicsParticleDensity','Particle detail','Детализация частиц'},
{'graphicsSpellDensity','Spell density','Плотность заклинаний',{'Essential','Reduced','Everything'}},
{'graphicsDepthEffects','Depth effects','Эффекты глубины',{'Off','Low','Good','High'}},
{'RAIDsettingsEnabled','Native raid override','Встроенные настройки рейда','toggle'},
{'MSAAQuality','MSAA','MSAA'}, {'msaaAlphaTest','MSAA alpha test','MSAA alpha test','toggle'},
{'ffxAntiAliasingMode','Anti-aliasing mode','Режим сглаживания'},
{'vsync','VSync','Вертикальная синхронизация','toggle'},
{'useTargetFPS','Dynamic FPS control','Динамическое управление FPS','toggle'},
{'useMaxFPS','FPS limiter','Ограничение FPS','toggle'}, {'maxFPS','FPS cap','Лимит FPS'},
}
local function snapshot()
local values={}
for _,spec in ipairs(settings) do values[spec[1]]=C_CVar.GetCVar(spec[1]) end
return values
end
local function equivalent(a,b)
return a==b or (tonumber(a)~=nil and tonumber(a)==tonumber(b))
end
local function differences(before,after)
local result={}
for _,spec in ipairs(settings) do
local key=spec[1]
if not equivalent(before[key],after[key]) then
result[#result+1]={key=key,before=before[key],after=after[key]}
end
end
return result
end
local function describe(change)
local spec
for _,entry in ipairs(settings) do if entry[1]==change.key then spec=entry; break end end
local function value(v)
if v==nil then return P.Localized('unavailable','недоступно') end
local n=tonumber(v)
if spec[4]=='distance' and n then return tostring(n+1)..'/10' end
if spec[4]=='toggle' and n then return n==0 and P.Localized('off','выкл') or P.Localized('on','вкл') end
if type(spec[4])=='table' and n and spec[4][n+1] then
local text=spec[4][n+1]
local ru={Off='Выкл',Low='Низко',Fair='Удовлетворительно',Good='Хорошо',High='Высоко',
Ultra='Ультра',['Ultra High']='Максимум',Essential='Необходимые',Reduced='Меньше',Everything='Все'}
return P.Localized(text,ru[text] or text)
end
if spec[1]=='MSAAQuality' and v=='0,0' then return P.Localized('off','выкл') end
return tostring(v)
end
return P.Localized(spec[2],spec[3])..': '..value(change.before)..' → '..value(change.after)
end
local function showChanges(changes)
if #changes==0 then
say('No graphics values changed in this step.',
'На этом шаге значения графики не изменились.'); return
end
for first=1,#changes,4 do
local parts={}
for i=first,math.min(first+3,#changes) do parts[#parts+1]=describe(changes[i]) end
say(table.concat(parts,'; '))
end
end
local function showUnavailable(failures)
if failures and next(failures) then
local names={}
for _,spec in ipairs(settings) do if failures[spec[1]] then names[#names+1]=P.Localized(spec[2],spec[3]) end end
say('Unavailable/not applied: '..table.concat(names,', '),'Недоступно/не применено: '..table.concat(names,', '))
end
end
local function reportApplication(before,heading,ru,failures)
local d=db(); local changes=differences(before,snapshot())
d.lastChange={time=time(),release=P.release,mode=mode(),heading=heading,headingRU=ru,changes=changes,unavailable=failures}
say(heading,ru); showChanges(changes)
showUnavailable(failures)
end
local function write(key, value)
local before = C_CVar.GetCVar(key)
if before == nil then return false end
if key:find('^graphics') and IsGraphicsSettingValueSupported then
local ok, reason = pcall(IsGraphicsSettingValueSupported, key, value, false)
if not ok or (reason and reason ~= 0) then return false end
end
if equivalent(before,tostring(value)) then return true end
local d = db()
if d.original[key] == nil then d.original[key] = before end
local ok = pcall(C_CVar.SetCVar, key, tostring(value))
if not ok then return false end
return equivalent(C_CVar.GetCVar(key),tostring(value))
end
local function profile(tier)
local failures = {}
tier = math.max(1, math.min(#tiers, tier or 1))
-- Own environment switching explicitly: the native raid preset must not
-- silently replace the settings being measured in a dungeon/BG/raid.
if not write('RAIDsettingsEnabled', 0) then failures.RAIDsettingsEnabled = true end
for i, suffix in ipairs(fields) do
local key = 'graphics'..suffix
if not write(key, tiers[tier][i]) then failures[key] = true end
end
for key, value in pairs({graphicsProjectedTextures=1, graphicsParticleDensity=2,
graphicsSpellDensity=0, graphicsDepthEffects=0}) do
if not write(key, value) then failures[key] = true end
end
-- Keep render scale, texture resolution and UI scale as the player chose.
-- These low-cost AA choices take effect without replacing GPU/API/drivers.
write('MSAAQuality', '0,0'); write('msaaAlphaTest', 0)
write('ffxAntiAliasingMode', 1); write('vsync', 0); write('useTargetFPS', 0)
return failures
end
local function cap(value)
write('useMaxFPS', 1); write('maxFPS', value)
end
local function resetSample(seconds)
if session then session.sample=P.NewFrameSample(); session.warmup=seconds or 8 end
end
local function applyTier(tier, phase)
local s, d = session, db()
local before=snapshot()
s.tier=tier; s.phase=phase or 'search'; s.pending=nil; s.good=0; s.waitNotified=nil
s.unsupported=profile(tier)
cap(s.phase == 'validate' and d.target or math.ceil(d.target * 1.1))
resetSample(8)
reportApplication(before,
('%s %s tier %d/5; FPS cap %d%s.'):format(s.phase=='validate' and 'Verifying' or 'Testing',s.mode,tier,
s.phase=='validate' and d.target or math.ceil(d.target*1.1),s.phase=='validate' and ' (final)' or ' (temporary)'),
('%s %s, уровень %d/5; лимит FPS %d%s.'):format(s.phase=='validate' and 'Итоговая проверка' or 'Проверка',s.mode,tier,
s.phase=='validate' and d.target or math.ceil(d.target*1.1),s.phase=='validate' and ' (итоговый)' or ' (временный)'),s.unsupported)
end
local function passed(r, target, validate)
-- Tail latency and explicit hitches matter even when 99% of frames are fast.
-- At most one >50ms frame per 20s, and no >100ms frame, passes this window.
return r.frames > 0 and 1000/r.p90MS >= target * (validate and .95 or 1.02)
and 1000/r.p99MS >= target * .80 and r.over100 == 0
and r.over50 <= math.floor(r.seconds / 20 + .01)
end
local function finish(r)
local s, d = session, db()
local saved = d.profiles[s.mode]
saved.tier=s.tier; saved.calibrated=true; saved.fingerprint=fingerprint(); saved.time=time()
saved.revision=2; saved.metTarget=passed(r,d.target,true); saved.last=r
saved.history=s.history; saved.unsupported=s.unsupported
saved.zone=GetRealZoneText and GetRealZoneText() or nil
saved.subzone=GetSubZoneText and GetSubZoneText() or nil
saved.requestedFPS=d.requestedFPS
cap(d.target)
say(('Graphics %s: tier %d/5 saved at %d FPS. p99 %.1f ms; worst %.1f ms; >100 ms frames: %d. %s'):format(
s.mode, s.tier, d.target, r.p99MS or 0, r.worstMS, r.over100,
saved.metTarget and 'Smoothness checks passed in this sample.' or 'Target/smoothness NOT met. Settings alone may not resolve these stalls.'),
('Графика %s: уровень %d/5, цель %d FPS. p99 %.1f мс; максимум %.1f мс; кадров >100 мс: %d. %s'):format(
s.mode, s.tier, d.target, r.p99MS or 0, r.worstMS, r.over100,
saved.metTarget and 'Проверка плавности пройдена для этого замера.' or 'Цель НЕ достигнута. Настройки графики могут не устранить задержки.'))
if next(s.unsupported) then
say('Some graphics controls are unavailable on this client/GPU; the result measures the settings actually accepted.',
'Некоторые настройки недоступны; результат получен с фактически применёнными значениями.')
end
reportApplication(s.before,'Final changes compared with the start of this run:',
'Итоговые изменения относительно начала этой проверки:',s.unsupported)
session=nil; f:SetScript('OnUpdate',nil)
end
local function commit()
local s = session
if not s or not s.pending or loading then return end
if InCombatLockdown() then
if not s.waitNotified then
say('Sample complete; waiting for combat to end before applying the next step.',
'Замер завершён; следующий шаг будет применён после окончания боя.')
s.waitNotified=true
end
return
end
if s.pending == 'finish' then finish(s.last)
else local nextStep=s.pending; applyTier(nextStep.tier,nextStep.phase) end
end
local function result()
local s, d = session, db()
local r=P.FrameSampleSummary(s.sample); r.tier=s.tier; r.phase=s.phase
s.last=r; s.history[#s.history+1]=r
local pass=passed(r,d.target,s.phase=='validate')
say(('Tier %d/5 check: %s; p99 %.1f ms, worst %.1f ms, frames >100 ms: %d.'):format(
s.tier,pass and 'passed' or 'target/smoothness missed',r.p99MS or 0,r.worstMS,r.over100),
('Проверка уровня %d/5: %s; p99 %.1f мс, максимум %.1f мс, кадров >100 мс: %d.'):format(
s.tier,pass and 'пройдена' or 'цель/плавность не достигнута',r.p99MS or 0,r.worstMS,r.over100))
if s.phase == 'validate' then
if not passed(r,d.target,true) and s.tier > 1 then
s.pending={tier=s.tier-1,phase='validate'}
else s.pending='finish' end
else
s.windows=s.windows+1
if passed(r,d.target,false) then s.good=s.good+1 else s.good=0 end
if s.good >= 2 then
s.best=s.tier
if s.tier < d.ceiling and s.windows < 10 then s.pending={tier=s.tier+1}
else s.pending={tier=s.best,phase='validate'} end
elseif not passed(r,d.target,false) then
if s.best then s.pending={tier=s.best,phase='validate'}
elseif s.tier > 1 then s.pending={tier=s.tier-1}
elseif s.windows >= 2 then s.pending={tier=1,phase='validate'} end
end
if s.windows >= 10 then s.pending={tier=s.best or 1,phase='validate'} end
end
resetSample(0); commit()
end
local update
local function start(which)
local d=db(); local saved=d.profiles[which]
session={mode=which,tier=math.min(saved.tier or 1,2,d.ceiling),windows=0,good=0,history={},before=snapshot()}
applyTier(session.tier)
f:SetScript('OnUpdate',update)
say(('Optimizing %s for %d FPS: move/fight in this area for about 2–5 minutes. Keep WoW focused; /ruen optimize pause before switching apps. Changes wait for combat to end.'):format(which,d.target),
('Настройка %s для %d FPS: играйте здесь 2–5 минут. Не переключайте окно; перед переключением /ruen optimize pause. Изменения применяются вне боя.'):format(which,d.target))
end
local function activate()
if not running or loading then return end
if P.IsBenchmarkRunning and P.IsBenchmarkRunning() then deferredEnvironment=true; return end
deferredEnvironment=nil
if InCombatLockdown() then
if pendingLoad~=activate then say('Environment changed; waiting for combat to end before applying its graphics.',
'Зона изменилась; графика будет применена после окончания боя.') end
pendingLoad=activate; return
end
local d=db(); local which=mode(); local r=d.profiles[which]
session=nil
if r.calibrated and r.revision==2 and r.fingerprint==fingerprint() then
local before=snapshot()
profile(r.tier); cap(d.target); f:SetScript('OnUpdate',nil)
if #differences(before,snapshot())>0 then
reportApplication(before,'Applied saved '..which..' graphics.','Применён сохранённый профиль '..which..'.')
end
else start(which) end
end
update = function(_, dt)
if not running or RuenUIDB.disabled then session=nil; f:SetScript('OnUpdate',nil); return end
if loading then return end
local s=session
if not s then f:SetScript('OnUpdate',nil); return end
if s.mode ~= mode() then
-- Discard the entire old window; never let a different environment
-- validate the old profile, even while changes are deferred by combat.
session=nil; f:SetScript('OnUpdate',nil); activate(); return
end
if s.pending then commit(); return end
if s.warmup > 0 then s.warmup=math.max(0,s.warmup-dt); return end
P.AddFrameSample(s.sample,dt) -- includes real long stalls, not just percentiles
if s.sample.seconds >= 20 then result() end
end
function P.IsOptimizerCalibrating() return session ~= nil or (running and pendingLoad ~= nil) end
function P.OptimizerBenchmarkEnded()
if deferredEnvironment then activate() end
end
function P.StopOptimizer()
if not RuenUIDB or not RuenUIDB.optimizer then return end
local d=db(); running=false; d.enabled=false; pendingLoad=nil; deferredEnvironment=nil
if session then
local s=session; local tier=s.best or s.tier
d.profiles[s.mode].tier=tier
profile(tier)
end
session=nil
if f then f:SetScript('OnUpdate',nil) end
cap(d.target or 60)
end
function P.OptimizerCommand(arg)
arg=(arg or ''):lower():match('^%s*(.-)%s*$')
local d=db()
if arg=='changes' then
local last=d.lastChange
if last then say(last.heading,last.headingRU); showChanges(last.changes); showUnavailable(last.unavailable)
else say('No recorded changes yet. This command does not start optimization.',
'Изменения ещё не записаны. Эта команда не запускает настройку.') end
return
end
if arg=='status' then
local which=mode(); local r=d.profiles[which]
local state=loading and 'loading' or session and (session.pending and
(InCombatLockdown() and 'waiting for combat to end' or 'applying next step') or session.warmup>0 and
('settling: '..math.ceil(session.warmup)..' seconds') or ('recording: '..math.floor(session.sample.seconds)..'/20 seconds'))
or pendingLoad and 'waiting for combat to end' or deferredEnvironment and 'waiting for benchmark'
say(('Optimizer [%s]: %s; %s; target %d FPS (requested %d). %s. Thermal evidence: %s.'):format(P.release or 'unknown',
running and 'ON' or 'OFF',which,d.target or validFPS(d.requestedFPS) or 60,
validFPS(d.requestedFPS) or 60,session and ('measuring tier '..session.tier..'/5 ('..session.phase..')')
or r.calibrated and ('saved tier '..r.tier..'/5; '..(r.metTarget and 'sample passed' or 'target NOT met')) or 'not measured',
hardware().evidence or 'not measured'))
if state then say(state) end
if d.lastChange then say('Last update: '..d.lastChange.heading..' /ruen optimize changes lists the settings.',
'Последнее изменение: '..(d.lastChange.headingRU or d.lastChange.heading)..' Список: /ruen optimize changes.') end
if r.last then say(('Last saved sample: p99 %.1f ms; worst %.1f ms; >50/>100/>250 ms frames: %d/%d/%d.'):format(
r.last.p99MS or 0,r.last.worstMS or 0,r.last.over50 or 0,r.last.over100 or 0,r.last.over250 or 0)) end
return
end
if InCombatLockdown() then say('Change optimization outside combat.','Меняйте оптимизацию вне боя.'); return end
if arg=='off' or arg=='pause' then
local before=snapshot(); P.StopOptimizer()
reportApplication(before,'Calibration paused; settled/current quality retained.','Калибровка приостановлена; текущие настройки сохранены.'); return
end
if arg=='restore' then
local before=snapshot()
P.StopOptimizer()
for key,value in pairs(d.original) do pcall(C_CVar.SetCVar,key,value) end
reportApplication(before,'Restored pre-optimization graphics:','Исходная графика восстановлена:')
RuenUIDB.optimizer=nil; say('Pre-optimization graphics restored.','Исходные настройки графики восстановлены.'); return
end
local cmd, fpsText=arg:match('^(%S+)%s+(%S+)$')
cmd=cmd or arg
if validFPS(cmd) and not fpsText then fpsText=cmd; cmd='' end
local fps=fpsText and validFPS(fpsText)
if (fpsText and not fps) or (cmd~='' and cmd~='start' and cmd~='resume' and not d.profiles[cmd]) then
say('/ruen optimize [20–240 FPS] | world|dungeon|raid|battleground [FPS] | pause|resume|status|changes|restore'); return
end
if P.IsBenchmarkRunning and P.IsBenchmarkRunning() then
say('Finish the benchmark or /ruen bench stop before changing graphics.','Завершите замер или /ruen bench stop перед настройкой графики.'); return
end
if d.profiles[cmd] and mode()~=cmd then
say('Run this in the requested environment; a solo sample cannot validate raid performance.',
'Запустите в соответствующей зоне; соло-замер не проверяет производительность рейда.'); return
end
if session then P.StopOptimizer() end
local h=hardware()
d.requestedFPS=fps or validFPS(d.requestedFPS) or 60
local target=h.thermalPressure and math.min(d.requestedFPS,45) or d.requestedFPS
local ceiling=(h.thermalPressure or h.performancePressure) and 2 or 5
if d.target~=target or d.ceiling~=ceiling then
for _,r in pairs(d.profiles) do r.calibrated=false end
end
d.target=target; d.ceiling=ceiling
-- A plain command is a fresh measurement HERE, even if the outdoor profile
-- previously passed elsewhere. Other environments retain their own evidence.
if cmd~='resume' then d.profiles[mode()].calibrated=false end
running=true; d.enabled=true
activate()
end
function P.InitializeOptimizer()
if f then return end
f=CreateFrame('Frame')
for _,event in ipairs({'PLAYER_ENTERING_WORLD','PLAYER_LEAVING_WORLD','PLAYER_REGEN_ENABLED',
'DISPLAY_SIZE_CHANGED','ZONE_CHANGED_NEW_AREA'}) do f:RegisterEvent(event) end
f:SetScript('OnEvent',function(_,event)
if event=='PLAYER_LEAVING_WORLD' then
loading=true; resetSample(8); return
elseif event=='PLAYER_REGEN_ENABLED' then
if pendingLoad then local fn=pendingLoad; pendingLoad=nil; fn() end
commit(); return
elseif event=='PLAYER_ENTERING_WORLD' then loading=false end
if running then
if event=='DISPLAY_SIZE_CHANGED' then
for _,r in pairs(db().profiles) do r.calibrated=false end
end
-- Immediately stop measuring; apply the next environment only once
-- safe. A loading screen is never charged as a gameplay hitch.
session=nil; f:SetScript('OnUpdate',nil); activate()
end
end)
local function initializeSaved()
local h=hardware()
local key=h.checkedAt and (tostring(h.checkedAt)..':'..(validFPS(h.targetFPS) or 60))
if h.autoStart and RuenUIDB.hardwareImport~=key then
db().requestedFPS=validFPS(h.targetFPS) or 60
P.OptimizerCommand('start'); RuenUIDB.hardwareImport=key; return
end
local d=RuenUIDB.optimizer
if d and d.enabled then P.OptimizerCommand('resume')
elseif d then cap(d.target or 60) end -- recover interrupted trial cap
end
if InCombatLockdown() then pendingLoad=initializeSaved else initializeSaved() end
end