2026-11-21 12:10:42 -06:00
local _ , P = ...
2026-11-22 10:40:49 -06:00
-- 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
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
end
local function mode ( )
2026-11-22 10:40:49 -06:00
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 '
2026-11-21 12:10:42 -06:00
end
local function fingerprint ( )
2026-11-22 10:40:49 -06:00
local w , h = GetPhysicalScreenSize ( )
2026-11-21 12:10:42 -06:00
return w .. ' x ' .. h .. ' : ' .. ( C_CVar.GetCVar ( ' gxAdapter ' ) or ' ' ) .. ' : ' .. ( C_CVar.GetCVar ( ' gxApi ' ) or ' ' )
end
local function hardware ( )
2026-11-22 10:40:49 -06:00
local h = P.hardwareProfile or { }
if not h.checkedAt or time ( ) - h.checkedAt > 604800 or time ( ) < h.checkedAt then return { } end
2026-11-21 12:10:42 -06:00
return h
end
2026-11-22 10:40:49 -06:00
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 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 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 tostring ( 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
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
end
local function cap ( value )
2026-11-22 10:40:49 -06:00
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 ( )
s.tier = tier ; s.phase = phase or ' search ' ; s.pending = nil ; s.good = 0
s.unsupported = profile ( tier )
cap ( s.phase == ' validate ' and d.target or math.ceil ( d.target * 1.1 ) )
resetSample ( 8 )
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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 )
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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. ' ,
' Некоторые настройки недоступны; результат получен с фактически применёнными значениями. ' )
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
session = nil ; f : SetScript ( ' OnUpdate ' , nil )
2026-11-21 12:10:42 -06:00
end
local function commit ( )
2026-11-22 10:40:49 -06:00
local s = session
if not s or not s.pending or InCombatLockdown ( ) or loading then return end
if s.pending == ' finish ' then finish ( s.last )
else local nextStep = s.pending ; applyTier ( nextStep.tier , nextStep.phase ) end
2026-11-21 12:10:42 -06:00
end
local function result ( )
2026-11-22 10:40:49 -06:00
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
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
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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 = { } }
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 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
profile ( r.tier ) ; cap ( d.target ) ; f : SetScript ( ' OnUpdate ' , nil )
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
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
end
function P . StopOptimizer ( )
if not RuenUIDB or not RuenUIDB.optimizer then return end
2026-11-22 10:40:49 -06:00
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 )
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
session = nil
2026-11-21 12:10:42 -06:00
if f then f : SetScript ( ' OnUpdate ' , nil ) end
cap ( d.target or 60 )
end
function P . OptimizerCommand ( arg )
2026-11-22 10:40:49 -06:00
arg = ( arg or ' ' ) : lower ( ) : match ( ' ^%s*(.-)%s*$ ' )
2026-11-21 12:10:42 -06:00
local d = db ( )
if arg == ' status ' then
2026-11-22 10:40:49 -06:00
local which = mode ( ) ; local r = d.profiles [ which ]
say ( ( ' Optimizer: %s; %s; target %d FPS (requested %d). %s. Thermal evidence: %s. ' ) : format (
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 r.last then say ( ( ' Last 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
2026-11-21 12:10:42 -06:00
return
end
2026-11-22 10:40:49 -06:00
if InCombatLockdown ( ) then say ( ' Change optimization outside combat. ' , ' Меняйте оптимизацию вне боя. ' ) ; return end
if arg == ' off ' or arg == ' pause ' then
P.StopOptimizer ( ) ; say ( ' Calibration paused; settled/current quality retained. ' , ' Калибровка приостановлена; текущие настройки сохранены. ' ) ; return
end
2026-11-21 12:10:42 -06:00
if arg == ' restore ' then
P.StopOptimizer ( )
2026-11-22 10:40:49 -06:00
for key , value in pairs ( d.original ) do pcall ( C_CVar.SetCVar , key , value ) end
RuenUIDB.optimizer = nil ; say ( ' Pre-optimization graphics restored. ' , ' Исходные настройки графики восстановлены. ' ) ; return
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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|restore ' ) ; return
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
if P.IsBenchmarkRunning and P.IsBenchmarkRunning ( ) then
say ( ' Finish the benchmark or /ruen bench stop before changing graphics. ' , ' Завершите замер или /ruen bench stop перед настройкой графики. ' ) ; return
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
if d.profiles [ cmd ] and mode ( ) ~= cmd then
say ( ' Run this in the requested environment; a solo sample cannot validate raid performance. ' ,
' Запустите в соответствующей зоне; соло-замер не проверяет производительность рейда. ' ) ; return
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
if session then P.StopOptimizer ( ) end
2026-11-21 12:10:42 -06:00
local h = hardware ( )
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
end
2026-11-22 10:40:49 -06:00
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 ( )
2026-11-21 12:10:42 -06:00
end
function P . InitializeOptimizer ( )
if f then return end
f = CreateFrame ( ' Frame ' )
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
f : SetScript ( ' OnEvent ' , function ( _ , event )
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
if event == ' DISPLAY_SIZE_CHANGED ' then
2026-11-22 10:40:49 -06:00
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 ( )
2026-11-21 12:10:42 -06:00
end
end )
local function initializeSaved ( )
local h = hardware ( )
2026-11-22 10:40:49 -06:00
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
2026-11-21 12:10:42 -06:00
end
local d = RuenUIDB.optimizer
2026-11-22 10:40:49 -06:00
if d and d.enabled then P.OptimizerCommand ( ' resume ' )
elseif d then cap ( d.target or 60 ) end -- recover interrupted trial cap
2026-11-21 12:10:42 -06:00
end
if InCombatLockdown ( ) then pendingLoad = initializeSaved else initializeSaved ( ) end
end