local Players = game:GetService("Players") local Lighting = game:GetService("Lighting") local RunService = game:GetService("RunService") local Stats = game:GetService("Stats") local Workspace = game:GetService("Workspace") local CollectionService = game:GetService("CollectionService") local LocalPlayer = Players.LocalPlayer local Config = { Name = "UltraPotatoFPSBooster_v4_AUTO_HEADLESS_V42", Version = "4.2.0", TargetFPS = 66, RecoveryFPS = 72, RecoverySeconds = 8, ParticleFlipbookFramerateCap = 4, ParticleSizeScale = 0.48, TrailMinLengthFloor = 0.65, TrailWidthScale = 0.35, BeamWidthScale = 0.35, SurfaceGuiPixelsPerStudCap = 10, SurfaceGuiMaxDistanceExtreme = 72, BillboardGuiMaxDistanceExtreme = 85, BillboardDistanceStep = 16, Tier1P95 = 17, Tier2FPS = 55, Tier2P95 = 23, Tier3FPS = 46, Tier3P95 = 32, Tier4FPS = 32, Tier4P95 = 45, TierChangeCooldown = 2.5, AdaptiveInterval = 0.65, MetricsInterval = 0.55, GuardInterval = 15, DistanceInterval = 0.65, DistanceSlowInterval = 1.25, BatchSize = 140, PanicBatchSize = 40, BatchBudgetSeconds = 0.0025, BatchYield = 0.012, MaxQueueEntries = 24000, MaxLogEntries = 250, MaxMetricSamples = 360, MaxFPSHistory = 60, MaxDistancePerPass = 180, SafeDecorDistance = 260, SafeDebrisDistance = 120, EffectDistance = 180, LightDistance = 150, AvatarDistance = 230, DistanceHysteresis = 0.15, SafeDecorAttribute = "PotatoSafeDecor", SafeDebrisAttribute = "PotatoSafeDebris", SafeDecorTag = "PotatoSafeDecor", SafeDebrisTag = "PotatoSafeDebris", SafeDebrisMaxMagnitude = 3, ParticleRateCap = 3, ParticleRateScale = 0.25, ParticleDensityScale = 0.20, ParticleLifetimeScale = 0.30, TrailLifetimeCap = 0.12, BeamSegmentsCap = 3, LightRangeCap = 8, LightBrightnessCap = 0.4, BillboardMaxDistance = 150, SurfaceGuiMaxDistance = 150, CacheMarkerSeconds = 0.35, CacheToolSeconds = 0.20, CachePlayerSeconds = 0.20, CacheMaintenanceInterval = 30, BenchmarkSeconds = 15, StartAutomatic = true, StartAdaptive = true, } local OptionDefinitions, Options = {}, {} local function AddOption(key, name, category, description, defaultValue, risk, autoTier, supported, reason) local definition = { Key = key, Name = name, Category = category, Description = description, DefaultValue = defaultValue == true, CurrentValue = defaultValue == true, RiskLevel = risk or "LOW", RequiresRestart = false, ApplyHandler = nil, RestoreHandler = nil, Supported = supported ~= false, UnsupportedReason = reason, AutoTier = autoTier, LastApplied = 0, } table.insert(OptionDefinitions, definition) Options[key] = definition.DefaultValue end AddOption("GlobalShadows", "Global shadows off", "CORE", "Desativa sombras globais do Lighting.", true) AddOption("PartShadows", "Part CastShadow off", "CORE", "Desativa CastShadow nas BaseParts elegiveis.", true) AddOption("SmoothPlastic", "SmoothPlastic materials", "CORE", "Simplifica materiais das BaseParts elegiveis.", true) AddOption("NoReflectance", "Reflectance zero", "CORE", "Zera Reflectance nas BaseParts elegiveis.", true) AddOption("PostEffects", "All post effects off", "VISUAL", "Desativa Bloom, Blur, ColorCorrection, SunRays e DepthOfField.", true, "MEDIUM", 2) AddOption("AtmosphereClouds", "Atmosphere and Clouds reduction", "VISUAL", "Reduz Atmosphere e desativa Clouds.", true, "MEDIUM", 2) AddOption("DynamicLights", "Dynamic lights off", "LIGHTING", "Desativa PointLight, SpotLight e SurfaceLight.", true, "MEDIUM", 2) AddOption("Particles", "ParticleEmitters off", "PARTICLES", "Desativa emissores de particulas.", true, "MEDIUM", 2) AddOption("Trails", "Trails off", "TRAILS", "Desativa rastros visuais.", true, "MEDIUM", 2) AddOption("Beams", "Beams off", "TRAILS", "Desativa beams visuais.", true, "MEDIUM", 2) AddOption("FireSmokeSparkles", "Fire / Smoke / Sparkles off", "PARTICLES", "Desativa efeitos classicos.", true, "MEDIUM", 2) AddOption("Decals", "Decals hidden", "TEXTURES", "Oculta Decals no cliente.", true, "MEDIUM", 2) AddOption("Textures", "Textures hidden", "TEXTURES", "Oculta Textures no cliente.", true, "MEDIUM", 2) AddOption("SurfaceAppearance", "SurfaceAppearance maps cleared", "TEXTURES", "Limpa mapas de SurfaceAppearance.", false, "HIGH", 3) AddOption("Sky", "Skybox simplified", "VISUAL", "Limpa texturas de Sky e corpos celestes.", true, "MEDIUM", 2) AddOption("TerrainDecoration", "Terrain decoration off", "TERRAIN", "Desativa decoracao do Terrain.", true, "LOW", 1) AddOption("WaterWaves", "Water waves off", "TERRAIN", "Zera tamanho e velocidade das ondas.", true, "LOW", 1) AddOption("WaterInvisible", "Water transparency 1", "TERRAIN", "Deixa a agua invisivel localmente.", false, "HIGH") AddOption("WaterReflectance", "Water reflectance zero", "TERRAIN", "Zera reflexos da agua.", true, "LOW", 1) AddOption("MeshPerformance", "MeshPart Performance fidelity", "MESH", "Usa RenderFidelity.Performance.", true, "MEDIUM", 2) AddOption("MeshTextures", "MeshPart TextureID cleared", "MESH", "Remove TextureID; pode alterar aparencia importante.", false, "HIGH") AddOption("LayeredClothing", "Other players WrapLayer off", "AVATAR", "Desativa WrapLayer somente em outros avatares.", true, "MEDIUM", 3) AddOption("SoundEffects", "Sound effects off", "AUDIO", "Desativa Reverb, Echo e Equalizer SoundEffects.", true, "LOW", 1) AddOption("Fog", "Fog removed", "LIGHTING", "Aumenta FogEnd e zera FogStart.", true, "MEDIUM", 2) AddOption("EnvironmentScales", "Environment scales zero", "LIGHTING", "Zera escalas ambientais difusa e especular.", true, "LOW", 1) AddOption("SafeDecorTouch", "SafeDecor CanTouch off", "SAFE DECOR", "Desativa CanTouch somente em SafeDecor marcado.", true, "MEDIUM") AddOption("SafeDecorQuery", "SafeDecor CanQuery off", "SAFE DECOR", "Desativa CanQuery somente em SafeDecor marcado.", true, "MEDIUM") AddOption("SafeDecorShadows", "SafeDecor shadows off", "SAFE DECOR", "Remove sombras somente em SafeDecor marcado.", true, "LOW", 1) AddOption("TaggedDebrisHide", "Tagged debris hidden", "SAFE DECOR", "Oculta debris marcados e pequenos.", false, "HIGH") AddOption("LiveGuard", "Live object monitor", "SYSTEM", "Monitora novos objetos e reaplica regras ativas.", true, "LOW") AddOption("ParticleRateLimiter", "Particle Rate Limiter", "PARTICLES", "Limita Rate de emissores ao teto configurado.", false, "LOW", 1) AddOption("ParticleLifetimeReduction", "Particle Lifetime Reduction", "PARTICLES", "Reduz Lifetime usando o intervalo original.", false, "LOW", 2) AddOption("ParticleLightEmissionReduction", "Particle Light Emission Reduction", "PARTICLES", "Reduz LightEmission dos emissores.", false, "LOW", 1) AddOption("ParticleLightInfluenceReduction", "Particle Light Influence Reduction", "PARTICLES", "Zera LightInfluence; altera a resposta a luz ambiente.", false, "LOW") AddOption("ParticleDistanceCulling", "Particle Distance Culling", "PARTICLES", "Desativa emissores distantes da camera local.", false, "MEDIUM", 2) AddOption("ParticleDensityControl", "Particle Density Control", "PARTICLES", "Multiplica Rate original por um fator menor.", false, "MEDIUM", 2) AddOption("ParticleBurstOptimization", "Particle Burst Optimization", "PARTICLES", "Zera Rate automatico; Emit() manual nao pode ser interceptado.", false, "HIGH", 3) AddOption("TrailLifetimeLimiter", "Trail Lifetime Limiter", "TRAILS", "Limita Lifetime original de Trails.", false, "LOW", 1) AddOption("TrailDistanceOptimization", "Trail Distance Optimization", "TRAILS", "Desativa Trails distantes.", false, "MEDIUM", 2) AddOption("BeamSegmentReduction", "Beam Segment Reduction", "TRAILS", "Reduz Segments respeitando keypoints.", false, "LOW", 1) AddOption("BeamTextureAnimationControl", "Beam Texture Animation Control", "TRAILS", "Zera TextureSpeed para parar animacao UV.", false, "LOW", 1) AddOption("BeamDistanceCulling", "Beam Distance Culling", "TRAILS", "Desativa Beams distantes.", false, "MEDIUM", 2) AddOption("TrailRenderingReduction", "Trail Rendering Reduction", "TRAILS", "Limita MaxLength e Lifetime de Trails.", false, "LOW", 2) AddOption("LightRangeLimiter", "Light Range Limiter", "LIGHTING", "Limita Range de luzes locais.", false, "LOW", 1) AddOption("LightBrightnessLimiter", "Light Brightness Limiter", "LIGHTING", "Limita Brightness de luzes locais.", false, "LOW", 1) AddOption("DistantLightCulling", "Distant Light Culling", "LIGHTING", "Desativa luzes distantes com base na camera.", false, "MEDIUM", 2) AddOption("SelectiveShadowRemoval", "Selective Shadow Removal", "LIGHTING", "Desativa Shadows em luzes elegiveis.", false, "LOW", 1) AddOption("DecorativeLightReduction", "Decorative Light Reduction", "LIGHTING", "Desativa luzes dentro de SafeDecor marcado.", false, "MEDIUM", 2) AddOption("LightUpdateThrottling", "Light Update Throttling", "LIGHTING", "Nao existe API publica para controlar a frequencia interna de atualizacao de luzes.", false, "LOW", nil, false, "Sem API publica; nao e simulado.") AddOption("SelectiveHighlightRemoval", "Selective Highlight Removal", "VISUAL", "Desativa Highlights em SafeDecor marcado.", false, "MEDIUM", 2) AddOption("SafeBillboardGuiOptimization", "Safe BillboardGui Optimization", "VISUAL", "Limita MaxDistance de BillboardGui em SafeDecor.", false, "LOW", 1) AddOption("SafeSurfaceGuiOptimization", "Safe SurfaceGui Optimization", "VISUAL", "Limita MaxDistance de SurfaceGui em SafeDecor.", false, "LOW", 1) AddOption("SelectionBoxOptimization", "SelectionBox Optimization", "VISUAL", "Oculta SelectionBox em SafeDecor.", false, "MEDIUM", 2) AddOption("SelectionSphereOptimization", "SelectionSphere Optimization", "VISUAL", "Oculta SelectionSphere em SafeDecor.", false, "MEDIUM", 2) AddOption("BoxHandleAdornmentOptimization", "BoxHandleAdornment Optimization", "VISUAL", "Oculta BoxHandleAdornment em SafeDecor.", false, "MEDIUM", 2) AddOption("SphereHandleAdornmentOptimization", "SphereHandleAdornment Optimization", "VISUAL", "Oculta SphereHandleAdornment em SafeDecor.", false, "MEDIUM", 2) AddOption("IndividualBloomControl", "Individual Bloom Control", "VISUAL", "Desativa BloomEffect individualmente.", false, "LOW", 1) AddOption("IndividualBlurControl", "Individual Blur Control", "VISUAL", "Desativa BlurEffect individualmente.", false, "LOW", 2) AddOption("IndividualColorCorrectionControl", "Individual ColorCorrection Control", "VISUAL", "Desativa ColorCorrectionEffect individualmente.", false, "MEDIUM", 2) AddOption("IndividualSunRaysControl", "Individual SunRays Control", "VISUAL", "Desativa SunRaysEffect individualmente.", false, "LOW", 1) AddOption("IndividualDepthOfFieldControl", "Individual DepthOfField Control", "VISUAL", "Desativa DepthOfFieldEffect individualmente.", false, "MEDIUM", 2) AddOption("AtmosphereDensityController", "Atmosphere Density Controller", "VISUAL", "Zera Density de Atmosphere.", false, "MEDIUM", 2) AddOption("AtmosphereHazeController", "Atmosphere Haze Controller", "VISUAL", "Zera Haze de Atmosphere.", false, "LOW", 1) AddOption("AtmosphereGlareController", "Atmosphere Glare Controller", "VISUAL", "Zera Glare de Atmosphere.", false, "LOW", 1) AddOption("SkyboxTextureOptimization", "Skybox Texture Optimization", "VISUAL", "Limpa texturas do Skybox e corpos celestes.", false, "MEDIUM", 2) AddOption("SafeDecorLocalHide", "SafeDecor Local Hide", "SAFE DECOR", "Oculta SafeDecor por LocalTransparencyModifier.", false, "HIGH", 3) AddOption("SafeDecorDistanceCulling", "SafeDecor Distance Culling", "DISTANCE", "Oculta SafeDecor marcado e distante.", false, "MEDIUM", 2) AddOption("SafeDecorMaterialSimplification", "SafeDecor Material Simplification", "SAFE DECOR", "Simplifica material apenas em SafeDecor.", false, "LOW", 1) AddOption("SafeDecorMeshOptimization", "SafeDecor Mesh Optimization", "SAFE DECOR", "Aplica RenderFidelity.Performance em MeshParts marcadas.", false, "LOW", 1) AddOption("SafeDecorMeshTextureRemoval", "SafeDecor Mesh Texture Removal", "SAFE DECOR", "Limpa TextureID de MeshParts marcadas.", false, "HIGH", 3) AddOption("SafeDecorSurfaceAppearanceReduction", "SafeDecor SurfaceAppearance Reduction", "SAFE DECOR", "Limpa SurfaceAppearance de SafeDecor.", false, "HIGH", 3) AddOption("SafeDecorDecalReduction", "SafeDecor Decal Reduction", "SAFE DECOR", "Oculta Decals dentro de SafeDecor.", false, "MEDIUM", 2) AddOption("SafeDecorTextureReduction", "SafeDecor Texture Reduction", "SAFE DECOR", "Oculta Textures dentro de SafeDecor.", false, "MEDIUM", 2) AddOption("SafeDebrisDistanceCulling", "SafeDebris Distance Culling", "DISTANCE", "Oculta debris marcado, elegivel e distante.", false, "MEDIUM", 2) AddOption("SafeDebrisSizeControl", "SafeDebris Size Control", "SAFE DECOR", "Limita operacoes a BaseParts marcadas pequenas.", false, "LOW") AddOption("SafeDebrisShadowRemoval", "SafeDebris Shadow Removal", "SAFE DECOR", "Remove CastShadow de debris marcado e elegivel.", false, "LOW", 1) AddOption("OtherPlayersHairReduction", "Other Players Hair Reduction", "AVATAR", "Oculta handles Hair de outros jogadores.", false, "HIGH") AddOption("OtherPlayersHatReduction", "Other Players Hat Reduction", "AVATAR", "Oculta handles Hat de outros jogadores.", false, "HIGH") AddOption("OtherPlayersFaceAccessoriesReduction", "Other Players Face Accessories Reduction", "AVATAR", "Oculta handles Face de outros jogadores.", false, "HIGH") AddOption("OtherPlayersBackAccessoriesReduction", "Other Players Back Accessories Reduction", "AVATAR", "Oculta handles Back de outros jogadores.", false, "HIGH") AddOption("OtherPlayersShoulderAccessoriesReduction", "Other Players Shoulder Accessories Reduction", "AVATAR", "Oculta handles Shoulder de outros jogadores.", false, "HIGH") AddOption("OtherPlayersWaistAccessoriesReduction", "Other Players Waist Accessories Reduction", "AVATAR", "Oculta handles Waist de outros jogadores.", false, "HIGH") AddOption("OtherPlayersCharacterDecalsReduction", "Other Players Character Decals Reduction", "AVATAR", "Oculta Decals e Textures de outros avatares.", false, "HIGH") AddOption("OtherPlayersCharacterParticlesReduction", "Other Players Character Particles Reduction", "AVATAR", "Desativa particulas em outros avatares.", false, "HIGH") AddOption("OtherPlayersCharacterTrailsReduction", "Other Players Character Trails Reduction", "AVATAR", "Desativa Trails e Beams em outros avatares.", false, "HIGH") AddOption("OtherPlayersCharacterHighlightsReduction", "Other Players Character Highlights Reduction", "AVATAR", "Desativa Highlights em outros avatares.", false, "HIGH") AddOption("OtherPlayersCharacterLightsReduction", "Other Players Character Lights Reduction", "AVATAR", "Desativa luzes em outros avatares.", false, "HIGH") AddOption("AdaptiveRenderDistance", "Adaptive Render Distance", "DISTANCE", "Ativa politica central de culling visual opt-in.", false, "MEDIUM", 2) AddOption("DynamicEffectsDistance", "Dynamic Effects Distance", "DISTANCE", "Faz culling de efeitos visuais distantes.", false, "MEDIUM", 2) AddOption("DynamicLightsDistance", "Dynamic Lights Distance", "DISTANCE", "Faz culling de luzes locais distantes.", false, "MEDIUM", 2) AddOption("DynamicDebrisDistance", "Dynamic Debris Distance", "DISTANCE", "Faz culling de debris marcados e distantes.", false, "MEDIUM", 2) AddOption("DynamicAvatarDistance", "Dynamic Avatar Distance", "DISTANCE", "Oculta somente cosmeticos/efeitos de outros avatares distantes.", false, "HIGH") AddOption("CameraBasedCulling", "Camera-Based Culling", "DISTANCE", "Usa CurrentCamera como referencia do controlador central.", true, "LOW") AddOption("DistanceUpdateThrottling", "Distance Update Throttling", "DISTANCE", "Limita a frequencia do scanner de distancia.", true, "LOW") AddOption("CoreCompatibilityMode", "Compatibility Guard", "SYSTEM", "Ignora propriedades inacessiveis e continua a execucao.", true, "LOW") AddOption("PreserveLocalAvatar", "Preserve Local Avatar", "SYSTEM", "Protecao fixa do avatar local; nao pode ser desligada nesta versao.", true, "LOW") AddOption("ParticleFlipbookBlendOff", "Particle Flipbook Blend Off", "PARTICLES V4", "Desliga blending entre quadros de flipbook para emissores.", false, "LOW", 1) AddOption("ParticleFlipbookFramerateCap", "Particle Flipbook Framerate Cap", "PARTICLES V4", "Limita a animacao de flipbook a poucos quadros por segundo.", false, "LOW", 1) AddOption("ParticleRotationSpeedZero", "Particle Rotation Speed Zero", "PARTICLES V4", "Zera RotSpeed de emissores para reduzir atualizacao angular.", false, "LOW", 1) AddOption("ParticleAccelerationZero", "Particle Acceleration Zero", "PARTICLES V4", "Zera aceleracao de emissores para reduzir simulacao extra.", false, "LOW", 1) AddOption("ParticleDragZero", "Particle Drag Zero", "PARTICLES V4", "Zera Drag de emissores quando a resistencia nao e necessaria.", false, "LOW", 1) AddOption("ParticleSizeReduction", "Particle Size Reduction", "PARTICLES V4", "Reduz a escala visual de particulas sem destruir emissores.", false, "MEDIUM", 2) AddOption("TrailMinLengthOptimization", "Trail MinLength Optimization", "TRAILS V4", "Aumenta MinLength para reduzir a frequencia de segmentos curtos.", false, "LOW", 1) AddOption("TrailWidthScaleReduction", "Trail WidthScale Reduction", "TRAILS V4", "Reduz a largura renderizada dos rastros.", false, "LOW", 1) AddOption("TrailLightBlendReduction", "Trail Light Blend Reduction", "TRAILS V4", "Remove blending luminoso de Trails.", false, "LOW", 1) AddOption("BeamWidthReduction", "Beam Width Reduction", "TRAILS V4", "Reduz Width0 e Width1 dos Beams.", false, "LOW", 1) AddOption("BeamLightBlendReduction", "Beam Light Blend Reduction", "TRAILS V4", "Remove blending luminoso de Beams.", false, "LOW", 1) AddOption("SurfaceGuiPixelDensityCap", "SurfaceGui Pixel Density Cap", "WORLD UI V4", "Limita PixelsPerStud de SurfaceGui em decoracao marcada.", false, "MEDIUM", 2) AddOption("SurfaceGuiDistanceCulling", "SurfaceGui Distance Culling", "WORLD UI V4", "Reduz a distancia de render de SurfaceGui em SafeDecor.", false, "MEDIUM", 2) AddOption("BillboardGuiDistanceCulling", "BillboardGui Distance Culling", "WORLD UI V4", "Reduz a distancia de render de BillboardGui em SafeDecor.", false, "MEDIUM", 2) AddOption("BillboardGuiDistanceStep", "BillboardGui Distance Step", "WORLD UI V4", "Aumenta o passo de atualizacao de distancia em BillboardGui SafeDecor.", false, "LOW", 1) AddOption("SafeDecorBillboardDisable", "SafeDecor Billboard Disable", "SAFE DECOR V4", "Desativa BillboardGui somente dentro de SafeDecor marcado.", false, "HIGH", 3) AddOption("SafeDecorSurfaceGuiDisable", "SafeDecor SurfaceGui Disable", "SAFE DECOR V4", "Desativa SurfaceGui somente dentro de SafeDecor marcado.", false, "HIGH", 3) AddOption("SafeDecorSpecialMeshTextureClear", "SafeDecor SpecialMesh Texture Clear", "SAFE DECOR V4", "Remove TextureId de SpecialMesh dentro de SafeDecor.", false, "HIGH", 3) AddOption("SafeDecorMeshDoubleSidedOff", "SafeDecor Mesh DoubleSided Off", "SAFE DECOR V4", "Desativa faces duplas em MeshPart SafeDecor.", false, "MEDIUM", 2) AddOption("SafeDecorMaterialVariantClear", "SafeDecor MaterialVariant Clear", "SAFE DECOR V4", "Remove MaterialVariant customizado de BaseParts SafeDecor.", false, "MEDIUM", 2) AddOption("SpecialMeshTextureClearGlobal", "SpecialMesh Texture Clear Global", "TEXTURE MAX", "Limpa TextureId de SpecialMesh fora do personagem local e de Tools.", false, "HIGH", 3) AddOption("DecalTextureAssetClearGlobal", "Decal Texture Asset Clear", "TEXTURE MAX", "Limpa a referencia Texture de Decals e Textures fora do personagem local e de Tools.", false, "HIGH", 3) AddOption("ParticleEmitterTextureClearGlobal", "Particle Emitter Texture Clear", "TEXTURE MAX", "Limpa a textura de emissores fora do personagem local e de Tools.", false, "HIGH", 3) AddOption("TrailTextureClearGlobal", "Trail Texture Clear Global", "TEXTURE MAX", "Limpa a textura de Trails fora do personagem local e de Tools.", false, "HIGH", 3) AddOption("BeamTextureClearGlobal", "Beam Texture Clear Global", "TEXTURE MAX", "Limpa a textura de Beams fora do personagem local e de Tools.", false, "HIGH", 3) AddOption("MeshPartDoubleSidedOffGlobal", "MeshPart DoubleSided Off Global", "MESH MAX", "Desativa faces duplas em MeshParts fora do personagem local e de Tools.", false, "HIGH", 3) local QueueEngine, DistanceEngine, BackgroundMonitor, MemoryCleaner local MetricsMonitor, AdaptiveController, Benchmark, ProfileManager local BoosterController local State = { Running = true, Enabled = false, OneClickActive = false, Automatic = Config.StartAutomatic, Adaptive = Config.StartAdaptive, Panic = false, Tier = 0, TierReason = "Inicializacao", Profile = "DEFAULT", StartedAt = 0, LastTierChange = 0, RecoveryStartedAt = nil, LastGuardRun = 0, LastDistanceRun = 0, LastScanSeconds = 0, ProcessedInstances = 0, InitialScanDone = false, InitialScanStarted = false, ScanGeneration = 0, AppliedProperties = 0, RestoredProperties = 0, FailedProperties = 0, ExternalChangesPreserved = 0, QueueDropped = 0, QueueGeneration = 0, QueueWorker = false, QueueHigh = {}, QueueNormal = {}, QueueHighHead = 1, QueueNormalHead = 1, Pending = setmetatable({}, { __mode = "k" }), SeenInstances = setmetatable({}, { __mode = "k" }), Original = setmetatable({}, { __mode = "k" }), DistanceCulled = setmetatable({}, { __mode = "k" }), DistanceCursor = nil, Connections = {}, PlayerConnections = setmetatable({}, { __mode = "k" }), Log = {}, LastLogSignature = nil, LastLogTime = 0, LastLogRepeat = 0, FrameTimes = {}, FrameTimeHead = 1, FrameTimeCount = 0, FPSHistory = {}, Samples = {}, FPS = 0, AverageFPS = 0, MinimumFPS = 0, MaximumFPS = 0, FrameTime = 0, SuddenDropCount = 0, LastSuddenDropTime = 0, AverageFrameTime = 0, P95FrameTime = 0, OnePercentLow = 0, SessionMinFrameTime = math.huge, SessionMaxFrameTime = 0, Ping = 0, MemoryMB = 0, CurrentSampleCount = 0, CacheStats = { IsAHit = 0, IsAMiss = 0, MarkerHit = 0, MarkerMiss = 0, ToolHit = 0, ToolMiss = 0, PlayerHit = 0, PlayerMiss = 0, SequenceHit = 0, SequenceMiss = 0 }, LastCacheMaintenance = 0, Benchmark = { Active = false, Kind = nil, StartedAt = 0, Duration = Config.BenchmarkSeconds, FrameTimes = {}, Baseline = nil, Optimized = nil, LastComparison = nil }, Profiles = {}, ShutdownStarted = false, BootstrapStarted = false, } local Logger = {} function Logger.Write(level, category, message, instance, propertyName, result) local now = os.clock() local fullName = "" if instance and typeof(instance) == "Instance" then pcall(function() fullName = instance:GetFullName() end) end local signature = table.concat({ tostring(level), tostring(category), tostring(message), fullName, tostring(propertyName), tostring(result) }, "|") if signature == State.LastLogSignature and now - State.LastLogTime < 2 then State.LastLogRepeat = State.LastLogRepeat + 1 local last = State.Log[#State.Log] if last then last.Repeats = State.LastLogRepeat end return end State.LastLogSignature, State.LastLogTime, State.LastLogRepeat = signature, now, 0 table.insert(State.Log, { Time = now, Clock = os.date("%H:%M:%S"), Level = tostring(level), Category = tostring(category), Message = tostring(message), Instance = fullName, Property = propertyName and tostring(propertyName) or "", Result = result and tostring(result) or "", Repeats = 0, }) while #State.Log > Config.MaxLogEntries do table.remove(State.Log, 1) end end function Logger.Info(message, category) Logger.Write("INFO", category or "SYSTEM", message) end function Logger.Warn(message, category, instance, propertyName) Logger.Write("WARNING", category or "SYSTEM", message, instance, propertyName) end function Logger.Error(message, category, instance, propertyName, result) Logger.Write("ERROR", category or "SYSTEM", message, instance, propertyName, result) end function Logger.Optimization(message, instance, propertyName) Logger.Write("INFO", "OPTIMIZATION", message, instance, propertyName, "APPLIED") end function Logger.Restore(message, instance, propertyName, result) Logger.Write("INFO", "RESTORE", message, instance, propertyName, result or "RESTORED") end function Logger.Clear() table.clear(State.Log); State.LastLogSignature = nil; State.LastLogRepeat = 0 end local Safe = {} local IsACache = setmetatable({}, { __mode = "k" }) local MarkerCache = setmetatable({}, { __mode = "k" }) local ToolAncestorCache = setmetatable({}, { __mode = "k" }) local PlayerAncestorCache = setmetatable({}, { __mode = "k" }) local AccessoryTypeCache = setmetatable({}, { __mode = "k" }) function Safe.IsA(instance, className) if typeof(instance) ~= "Instance" then return false end local perInstance = IsACache[instance] if perInstance then local cached = perInstance[className] if cached ~= nil then State.CacheStats.IsAHit = State.CacheStats.IsAHit + 1 return cached end else perInstance = {} IsACache[instance] = perInstance end State.CacheStats.IsAMiss = State.CacheStats.IsAMiss + 1 local ok, result = pcall(function() return instance:IsA(className) end) local answer = ok and result == true perInstance[className] = answer return answer end function Safe.Get(instance, propertyName) if typeof(instance) ~= "Instance" then return false, nil end local ok, value = pcall(function() return instance[propertyName] end) return ok, value end function Safe.IsAlive(instance) if typeof(instance) ~= "Instance" then return false end local ok, parent = pcall(function() return instance.Parent end) return ok and parent ~= nil end function Safe.HasAttribute(instance, attributeName) local ok, value = pcall(function() return instance:GetAttribute(attributeName) end) return ok and value == true end function Safe.HasTag(instance, tagName) local ok, value = pcall(function() return CollectionService:HasTag(instance, tagName) end) return ok and value == true end function Safe.HasMarker(instance, attributeName, tagName) if typeof(instance) ~= "Instance" then return false end local now = os.clock() local key = tostring(attributeName) .. "|" .. tostring(tagName) local byKey = MarkerCache[instance] if byKey then local entry = byKey[key] if entry and entry.Expires > now then State.CacheStats.MarkerHit = State.CacheStats.MarkerHit + 1 return entry.Value end else byKey = {} MarkerCache[instance] = byKey end State.CacheStats.MarkerMiss = State.CacheStats.MarkerMiss + 1 local cursor, depth, found = instance, 0, false while cursor and cursor ~= game and depth < 16 do if Safe.HasAttribute(cursor, attributeName) or Safe.HasTag(cursor, tagName) then found = true break end cursor, depth = cursor.Parent, depth + 1 end byKey[key] = { Value = found, Expires = now + Config.CacheMarkerSeconds } return found end function Safe.IsInsideTool(instance) if typeof(instance) ~= "Instance" then return false end local now = os.clock() local cached = ToolAncestorCache[instance] if cached and cached.Expires > now then State.CacheStats.ToolHit = State.CacheStats.ToolHit + 1 return cached.Value end State.CacheStats.ToolMiss = State.CacheStats.ToolMiss + 1 local cursor, depth, found = instance, 0, false while cursor and cursor ~= Workspace and depth < 18 do if Safe.IsA(cursor, "Tool") then found = true; break end cursor, depth = cursor.Parent, depth + 1 end ToolAncestorCache[instance] = { Value = found, Expires = now + Config.CacheToolSeconds } return found end function Safe.GetPlayerFromAncestor(instance) if typeof(instance) ~= "Instance" then return nil end local now = os.clock() local cached = PlayerAncestorCache[instance] if cached and cached.Expires > now then State.CacheStats.PlayerHit = State.CacheStats.PlayerHit + 1 return cached.Player end State.CacheStats.PlayerMiss = State.CacheStats.PlayerMiss + 1 local cursor, depth, owner = instance, 0, nil while cursor and cursor ~= Workspace and depth < 20 do if Safe.IsA(cursor, "Model") then local ok, player = pcall(function() return Players:GetPlayerFromCharacter(cursor) end) if ok and player then owner = player; break end end cursor, depth = cursor.Parent, depth + 1 end PlayerAncestorCache[instance] = { Player = owner, Expires = now + Config.CachePlayerSeconds } return owner end function Safe.IsLocalCharacter(instance) local character = LocalPlayer and LocalPlayer.Character if character and typeof(instance) == "Instance" then local ok, isDescendant = pcall(function() return instance == character or instance:IsDescendantOf(character) end) if ok and isDescendant then return true end end return Safe.GetPlayerFromAncestor(instance) == LocalPlayer end function Safe.IsOtherAvatar(instance) local owner = Safe.GetPlayerFromAncestor(instance) return owner ~= nil and owner ~= LocalPlayer end function Safe.IsSmallPart(part, maximum) if not Safe.IsA(part, "BasePart") then return false end local ok, size = Safe.Get(part, "Size") return ok and typeof(size) == "Vector3" and size.Magnitude <= (maximum or Config.SafeDebrisMaxMagnitude) end function Safe.IsDecor(instance) return Safe.HasMarker(instance, Config.SafeDecorAttribute, Config.SafeDecorTag) end function Safe.IsDebris(instance) return Safe.HasMarker(instance, Config.SafeDebrisAttribute, Config.SafeDebrisTag) end function Safe.AccessoryTypeName(accessory) local cached = AccessoryTypeCache[accessory] if cached ~= nil then return cached end local ok, kind = Safe.Get(accessory, "AccessoryType") if not ok then return "Unknown" end local name = "Unknown" pcall(function() name = kind.Name end) AccessoryTypeCache[accessory] = name return name end function Safe.TrimTimedCaches() local now = os.clock() if now - State.LastCacheMaintenance < Config.CacheMaintenanceInterval then return end State.LastCacheMaintenance = now table.clear(MarkerCache) table.clear(ToolAncestorCache) table.clear(PlayerAncestorCache) end function Safe.AccessoryHandle(accessory) local ok, handle = pcall(function() return accessory:FindFirstChild("Handle") end) if ok and handle and Safe.IsA(handle, "BasePart") then return handle end return nil end function Safe.IsPostEffect(instance) return Safe.IsA(instance, "BloomEffect") or Safe.IsA(instance, "BlurEffect") or Safe.IsA(instance, "ColorCorrectionEffect") or Safe.IsA(instance, "SunRaysEffect") or Safe.IsA(instance, "DepthOfFieldEffect") end function Safe.IsLight(instance) return Safe.IsA(instance, "PointLight") or Safe.IsA(instance, "SpotLight") or Safe.IsA(instance, "SurfaceLight") end function Safe.IsSoundEffect(instance) return Safe.IsA(instance, "ReverbSoundEffect") or Safe.IsA(instance, "EchoSoundEffect") or Safe.IsA(instance, "EqualizerSoundEffect") end local PropertyStore = {} function PropertyStore.Entry(instance, propertyName) local values = State.Original[instance] return values and values[propertyName] or nil end function PropertyStore.GetOriginal(instance, propertyName) local entry = PropertyStore.Entry(instance, propertyName) local ok, current = Safe.Get(instance, propertyName) if not ok then return entry and entry.Original or nil end if entry and entry.Applied ~= nil and current ~= entry.Applied then entry.Original = current State.ExternalChangesPreserved = State.ExternalChangesPreserved + 1 end if entry then return entry.Original end return current end function PropertyStore.Set(instance, propertyName, desired) if not Safe.IsAlive(instance) then return false end local ok, current = Safe.Get(instance, propertyName) if not ok then State.FailedProperties = State.FailedProperties + 1 return false end local values = State.Original[instance] local entry = values and values[propertyName] if entry and entry.Applied ~= nil and current ~= entry.Applied then entry.Original = current State.ExternalChangesPreserved = State.ExternalChangesPreserved + 1 end if current == desired then if entry then entry.Applied = desired end return true end if not values then values = {}; State.Original[instance] = values end if not entry then entry = { Original = current, Applied = nil, Writes = 0 } values[propertyName] = entry end local changed, err = pcall(function() instance[propertyName] = desired end) if not changed then State.FailedProperties = State.FailedProperties + 1 Logger.Error("Falha ao alterar propriedade", "PROPERTY", instance, propertyName, err) return false end entry.Applied = desired entry.Writes = entry.Writes + 1 entry.ChangedAt = os.clock() State.AppliedProperties = State.AppliedProperties + 1 return true end function PropertyStore.RestoreProperty(instance, propertyName) local values = State.Original[instance] local entry = values and values[propertyName] if not entry then return false end if not Safe.IsAlive(instance) then values[propertyName] = nil if next(values) == nil then State.Original[instance] = nil end return false end local ok, current = Safe.Get(instance, propertyName) if ok and entry.Applied ~= nil and current == entry.Applied then local restored, err = pcall(function() instance[propertyName] = entry.Original end) if restored then State.RestoredProperties = State.RestoredProperties + 1 Logger.Restore("Propriedade restaurada", instance, propertyName) else State.FailedProperties = State.FailedProperties + 1 Logger.Error("Falha na restauracao", "RESTORE", instance, propertyName, err) end else State.ExternalChangesPreserved = State.ExternalChangesPreserved + 1 Logger.Restore("Valor externo preservado", instance, propertyName, "EXTERNAL_VALUE_KEPT") end values[propertyName] = nil if next(values) == nil then State.Original[instance] = nil end return true end function PropertyStore.RestoreInstance(instance) local values = State.Original[instance] if not values then return end local properties = {} for propertyName in pairs(values) do table.insert(properties, propertyName) end for _, propertyName in ipairs(properties) do PropertyStore.RestoreProperty(instance, propertyName) end end function PropertyStore.Reconcile(instance, desired) local values = State.Original[instance] if values then local toRestore = {} for propertyName in pairs(values) do if desired[propertyName] == nil then table.insert(toRestore, propertyName) end end for _, propertyName in ipairs(toRestore) do PropertyStore.RestoreProperty(instance, propertyName) end end for propertyName, value in pairs(desired) do PropertyStore.Set(instance, propertyName, value) end end function PropertyStore.RestoreAll() local instances = {} for instance in pairs(State.Original) do table.insert(instances, instance) end for _, instance in ipairs(instances) do PropertyStore.RestoreInstance(instance) end Logger.Info("Rollback por propriedade concluido", "RESTORE") end function PropertyStore.Count() local count = 0 for _, values in pairs(State.Original) do for _ in pairs(values) do count = count + 1 end end return count end local AdaptivePolicy = {} local OptimizerEngine = {} local function Wants(key) return AdaptivePolicy.IsActive(key) end local function DesiredSet(desired, propertyName, value) desired[propertyName] = value end local NumberSequenceCache = setmetatable({}, { __mode = "k" }) local function ScaleNumberSequence(sequence, factor) if typeof(sequence) ~= "NumberSequence" then return nil end local factorKey = string.format("%.4f", factor) local cachedByFactor = NumberSequenceCache[sequence] if cachedByFactor and cachedByFactor[factorKey] then State.CacheStats.SequenceHit = State.CacheStats.SequenceHit + 1 return cachedByFactor[factorKey] end State.CacheStats.SequenceMiss = State.CacheStats.SequenceMiss + 1 local keypoints = {} for _, keypoint in ipairs(sequence.Keypoints) do keypoints[#keypoints + 1] = NumberSequenceKeypoint.new( keypoint.Time, keypoint.Value * factor, keypoint.Envelope * factor ) end if #keypoints < 2 then return nil end local ok, scaled = pcall(function() return NumberSequence.new(keypoints) end) if ok and scaled then if not cachedByFactor then cachedByFactor = {} NumberSequenceCache[sequence] = cachedByFactor end cachedByFactor[factorKey] = scaled return scaled end return nil end local function GetAccessoryAncestor(instance) local cursor, depth = instance, 0 while cursor and cursor ~= Workspace and depth < 20 do if Safe.IsA(cursor, "Accessory") then return cursor end cursor, depth = cursor.Parent, depth + 1 end return nil end local function AvatarAccessoryOption(accessory) local kind = Safe.AccessoryTypeName(accessory) if kind == "Hair" then return "OtherPlayersHairReduction" end if kind == "Hat" then return "OtherPlayersHatReduction" end if kind == "Face" then return "OtherPlayersFaceAccessoriesReduction" end if kind == "Back" then return "OtherPlayersBackAccessoriesReduction" end if kind == "Shoulder" then return "OtherPlayersShoulderAccessoriesReduction" end if kind == "Waist" then return "OtherPlayersWaistAccessoriesReduction" end return nil end local function IsAvatarReductionActive(instance, optionKey) return Safe.IsOtherAvatar(instance) and Wants(optionKey) end local function IsDistanceCulled(instance) return State.DistanceCulled[instance] == true end function OptimizerEngine.BuildDesiredProperties(instance) local desired = {} if not State.Enabled or not Safe.IsAlive(instance) then return desired end local localAvatar = Safe.IsLocalCharacter(instance) local otherAvatar = Safe.IsOtherAvatar(instance) local safeDecor = Safe.IsDecor(instance) local safeDebris = Safe.IsDebris(instance) local inTool = Safe.IsInsideTool(instance) local distanceCulled = IsDistanceCulled(instance) if Safe.IsA(instance, "BasePart") then if not localAvatar then if Wants("PartShadows") then DesiredSet(desired, "CastShadow", false) end if Wants("SmoothPlastic") then DesiredSet(desired, "Material", Enum.Material.SmoothPlastic) end if Wants("NoReflectance") then DesiredSet(desired, "Reflectance", 0) end if safeDecor and Wants("SafeDecorMaterialVariantClear") then DesiredSet(desired, "MaterialVariant", "") end if safeDecor and Wants("SafeDecorMeshDoubleSidedOff") and Safe.IsA(instance, "MeshPart") then DesiredSet(desired, "DoubleSided", false) end if safeDecor and Wants("SafeDecorShadows") then DesiredSet(desired, "CastShadow", false) end if safeDebris and Wants("SafeDebrisShadowRemoval") and Safe.IsSmallPart(instance) then DesiredSet(desired, "CastShadow", false) end if safeDecor and Wants("SafeDecorMaterialSimplification") then DesiredSet(desired, "Material", Enum.Material.SmoothPlastic) end if safeDecor and Wants("SafeDecorTouch") then DesiredSet(desired, "CanTouch", false) end if safeDecor and Wants("SafeDecorQuery") then DesiredSet(desired, "CanQuery", false) end if safeDecor and Wants("SafeDecorLocalHide") then DesiredSet(desired, "LocalTransparencyModifier", 1) end if safeDebris and (Wants("TaggedDebrisHide") or distanceCulled) and Safe.IsSmallPart(instance) then DesiredSet(desired, "LocalTransparencyModifier", 1) if Wants("SafeDebrisSizeControl") then DesiredSet(desired, "CanTouch", false) DesiredSet(desired, "CanQuery", false) end end if safeDebris and Wants("SafeDebrisSizeControl") and Safe.IsSmallPart(instance) then DesiredSet(desired, "CanTouch", false) DesiredSet(desired, "CanQuery", false) end if distanceCulled and safeDecor then DesiredSet(desired, "LocalTransparencyModifier", 1) end if distanceCulled and safeDebris and Safe.IsSmallPart(instance) then DesiredSet(desired, "LocalTransparencyModifier", 1) end local accessory = GetAccessoryAncestor(instance) if accessory and otherAvatar and not inTool then local accessoryOption = AvatarAccessoryOption(accessory) if accessoryOption and Wants(accessoryOption) then DesiredSet(desired, "LocalTransparencyModifier", 1) end end if Safe.IsA(instance, "MeshPart") then if Wants("MeshPerformance") or (safeDecor and Wants("SafeDecorMeshOptimization")) then DesiredSet(desired, "RenderFidelity", Enum.RenderFidelity.Performance) end if Wants("MeshPartDoubleSidedOffGlobal") and not inTool then DesiredSet(desired, "DoubleSided", false) end if safeDecor and Wants("SafeDecorMeshTextureRemoval") then DesiredSet(desired, "TextureID", "") elseif Wants("MeshTextures") and not inTool then DesiredSet(desired, "TextureID", "") end end end local avatarAccessory = GetAccessoryAncestor(instance) if otherAvatar and avatarAccessory and Wants("DynamicAvatarDistance") and distanceCulled then DesiredSet(desired, "LocalTransparencyModifier", 1) end return desired end if Safe.IsA(instance, "Decal") or Safe.IsA(instance, "Texture") then if not localAvatar then if Safe.IsA(instance, "Decal") and Wants("Decals") then DesiredSet(desired, "Transparency", 1) end if Safe.IsA(instance, "Texture") and Wants("Textures") then DesiredSet(desired, "Transparency", 1) end if Wants("DecalTextureAssetClearGlobal") and not inTool then if Safe.IsA(instance, "Decal") or Safe.IsA(instance, "Texture") then DesiredSet(desired, "Texture", "") end end if safeDecor and Safe.IsA(instance, "Decal") and Wants("SafeDecorDecalReduction") then DesiredSet(desired, "Transparency", 1) end if safeDecor and Safe.IsA(instance, "Texture") and Wants("SafeDecorTextureReduction") then DesiredSet(desired, "Transparency", 1) end if otherAvatar and (Wants("OtherPlayersCharacterDecalsReduction") or (Wants("DynamicAvatarDistance") and distanceCulled)) then DesiredSet(desired, "Transparency", 1) end end return desired end if Safe.IsA(instance, "SurfaceAppearance") then if not localAvatar and (Wants("SurfaceAppearance") or (safeDecor and Wants("SafeDecorSurfaceAppearanceReduction")) or (otherAvatar and Wants("DynamicAvatarDistance") and distanceCulled)) then DesiredSet(desired, "ColorMap", "") DesiredSet(desired, "NormalMap", "") DesiredSet(desired, "RoughnessMap", "") DesiredSet(desired, "MetalnessMap", "") end return desired end if Safe.IsPostEffect(instance) then local individual = false if Safe.IsA(instance, "BloomEffect") then individual = Wants("IndividualBloomControl") end if Safe.IsA(instance, "BlurEffect") then individual = Wants("IndividualBlurControl") end if Safe.IsA(instance, "ColorCorrectionEffect") then individual = Wants("IndividualColorCorrectionControl") end if Safe.IsA(instance, "SunRaysEffect") then individual = Wants("IndividualSunRaysControl") end if Safe.IsA(instance, "DepthOfFieldEffect") then individual = Wants("IndividualDepthOfFieldControl") end if Wants("PostEffects") or individual then DesiredSet(desired, "Enabled", false) end return desired end if Safe.IsA(instance, "Atmosphere") then if Wants("AtmosphereClouds") or Wants("AtmosphereDensityController") then DesiredSet(desired, "Density", 0) end if Wants("AtmosphereClouds") or Wants("AtmosphereHazeController") then DesiredSet(desired, "Haze", 0) end if Wants("AtmosphereClouds") or Wants("AtmosphereGlareController") then DesiredSet(desired, "Glare", 0) end return desired end if Safe.IsA(instance, "Clouds") then if Wants("AtmosphereClouds") then DesiredSet(desired, "Enabled", false) end return desired end if Safe.IsLight(instance) then if not localAvatar then if Wants("DynamicLights") or IsAvatarReductionActive(instance, "OtherPlayersCharacterLightsReduction") then DesiredSet(desired, "Enabled", false) else if Wants("LightRangeLimiter") then local original = PropertyStore.GetOriginal(instance, "Range") if type(original) == "number" then DesiredSet(desired, "Range", math.min(original, Config.LightRangeCap)) end end if Wants("LightBrightnessLimiter") then local original = PropertyStore.GetOriginal(instance, "Brightness") if type(original) == "number" then DesiredSet(desired, "Brightness", math.min(original, Config.LightBrightnessCap)) end end if Wants("SelectiveShadowRemoval") then DesiredSet(desired, "Shadows", false) end if safeDecor and Wants("DecorativeLightReduction") then DesiredSet(desired, "Enabled", false) end if distanceCulled then DesiredSet(desired, "Enabled", false) end end end return desired end if Safe.IsA(instance, "ParticleEmitter") then local avatarOff = IsAvatarReductionActive(instance, "OtherPlayersCharacterParticlesReduction") if not localAvatar then if Wants("ParticleEmitterTextureClearGlobal") and not inTool then DesiredSet(desired, "Texture", "") end if Wants("Particles") or avatarOff then DesiredSet(desired, "Enabled", false) else local originalRate = PropertyStore.GetOriginal(instance, "Rate") if type(originalRate) == "number" then local targetRate = originalRate if Wants("ParticleDensityControl") then targetRate = targetRate * Config.ParticleDensityScale end if Wants("ParticleRateLimiter") then targetRate = math.min(targetRate, Config.ParticleRateCap) end if Wants("ParticleBurstOptimization") then targetRate = 0 end if targetRate ~= originalRate then DesiredSet(desired, "Rate", targetRate) end end if Wants("ParticleLifetimeReduction") then local range = PropertyStore.GetOriginal(instance, "Lifetime") if typeof(range) == "NumberRange" then DesiredSet(desired, "Lifetime", NumberRange.new( math.max(0, range.Min * Config.ParticleLifetimeScale), math.max(0, range.Max * Config.ParticleLifetimeScale))) end end if Wants("ParticleLightEmissionReduction") then DesiredSet(desired, "LightEmission", 0) end if Wants("ParticleLightInfluenceReduction") then DesiredSet(desired, "LightInfluence", 0) end if Wants("ParticleFlipbookBlendOff") then DesiredSet(desired, "FlipbookBlendFrames", false) end if Wants("ParticleFlipbookFramerateCap") then local flipbookRate = PropertyStore.GetOriginal(instance, "FlipbookFramerate") if typeof(flipbookRate) == "NumberRange" then local cap = Config.ParticleFlipbookFramerateCap DesiredSet(desired, "FlipbookFramerate", NumberRange.new( math.min(flipbookRate.Min, cap), math.min(flipbookRate.Max, cap))) end end if Wants("ParticleRotationSpeedZero") then DesiredSet(desired, "RotSpeed", NumberRange.new(0, 0)) end if Wants("ParticleAccelerationZero") then DesiredSet(desired, "Acceleration", Vector3.zero) end if Wants("ParticleDragZero") then DesiredSet(desired, "Drag", 0) end if Wants("ParticleSizeReduction") then local originalSize = PropertyStore.GetOriginal(instance, "Size") local reducedSize = ScaleNumberSequence(originalSize, Config.ParticleSizeScale) if reducedSize then DesiredSet(desired, "Size", reducedSize) end end if distanceCulled then DesiredSet(desired, "Enabled", false) end end end return desired end if Safe.IsA(instance, "Trail") then local avatarOff = IsAvatarReductionActive(instance, "OtherPlayersCharacterTrailsReduction") if not localAvatar then if Wants("TrailTextureClearGlobal") and not inTool then DesiredSet(desired, "Texture", "") end if Wants("Trails") or avatarOff then DesiredSet(desired, "Enabled", false) else local originalLifetime = PropertyStore.GetOriginal(instance, "Lifetime") if type(originalLifetime) == "number" and (Wants("TrailLifetimeLimiter") or Wants("TrailRenderingReduction")) then DesiredSet(desired, "Lifetime", math.min(originalLifetime, Config.TrailLifetimeCap)) end local maxLength = PropertyStore.GetOriginal(instance, "MaxLength") if type(maxLength) == "number" and Wants("TrailRenderingReduction") then DesiredSet(desired, "MaxLength", math.min(maxLength, 12)) end if Wants("TrailMinLengthOptimization") then local originalMin = PropertyStore.GetOriginal(instance, "MinLength") local effectiveMax = type(maxLength) == "number" and maxLength or math.huge if type(originalMin) == "number" then DesiredSet(desired, "MinLength", math.min(math.max(originalMin, Config.TrailMinLengthFloor), effectiveMax)) end end if Wants("TrailWidthScaleReduction") then local originalWidth = PropertyStore.GetOriginal(instance, "WidthScale") local reducedWidth = ScaleNumberSequence(originalWidth, Config.TrailWidthScale) if reducedWidth then DesiredSet(desired, "WidthScale", reducedWidth) end end if Wants("TrailLightBlendReduction") then DesiredSet(desired, "LightEmission", 0) DesiredSet(desired, "LightInfluence", 0) end if distanceCulled then DesiredSet(desired, "Enabled", false) end end end return desired end if Safe.IsA(instance, "Beam") then local avatarOff = IsAvatarReductionActive(instance, "OtherPlayersCharacterTrailsReduction") if not localAvatar then if Wants("BeamTextureClearGlobal") and not inTool then DesiredSet(desired, "Texture", "") end if Wants("Beams") or avatarOff then DesiredSet(desired, "Enabled", false) else if Wants("BeamSegmentReduction") then local color = PropertyStore.GetOriginal(instance, "Color") local transparency = PropertyStore.GetOriginal(instance, "Transparency") local minimum = 1 if typeof(color) == "ColorSequence" then minimum = math.max(minimum, #color.Keypoints - 1) end if typeof(transparency) == "NumberSequence" then minimum = math.max(minimum, #transparency.Keypoints - 1) end local segments = PropertyStore.GetOriginal(instance, "Segments") if type(segments) == "number" then DesiredSet(desired, "Segments", math.max(minimum, math.min(segments, Config.BeamSegmentsCap))) end end if Wants("BeamTextureAnimationControl") then DesiredSet(desired, "TextureSpeed", 0) end if Wants("BeamWidthReduction") then local originalWidth0 = PropertyStore.GetOriginal(instance, "Width0") local originalWidth1 = PropertyStore.GetOriginal(instance, "Width1") if type(originalWidth0) == "number" then DesiredSet(desired, "Width0", originalWidth0 * Config.BeamWidthScale) end if type(originalWidth1) == "number" then DesiredSet(desired, "Width1", originalWidth1 * Config.BeamWidthScale) end end if Wants("BeamLightBlendReduction") then DesiredSet(desired, "LightEmission", 0) DesiredSet(desired, "LightInfluence", 0) end if distanceCulled then DesiredSet(desired, "Enabled", false) end end end return desired end if Safe.IsA(instance, "Fire") or Safe.IsA(instance, "Smoke") or Safe.IsA(instance, "Sparkles") then if not localAvatar and (Wants("FireSmokeSparkles") or IsAvatarReductionActive(instance, "OtherPlayersCharacterParticlesReduction") or (otherAvatar and Wants("DynamicAvatarDistance") and distanceCulled)) then DesiredSet(desired, "Enabled", false) end return desired end if Safe.IsSoundEffect(instance) then if Wants("SoundEffects") then DesiredSet(desired, "Enabled", false) end return desired end if Safe.IsA(instance, "Sky") then if Wants("Sky") or Wants("SkyboxTextureOptimization") then DesiredSet(desired, "SkyboxBk", "") DesiredSet(desired, "SkyboxDn", "") DesiredSet(desired, "SkyboxFt", "") DesiredSet(desired, "SkyboxLf", "") DesiredSet(desired, "SkyboxRt", "") DesiredSet(desired, "SkyboxUp", "") DesiredSet(desired, "SunTextureId", "") DesiredSet(desired, "MoonTextureId", "") DesiredSet(desired, "StarCount", 0) DesiredSet(desired, "CelestialBodiesShown", false) end return desired end if Safe.IsA(instance, "WrapLayer") then if otherAvatar and not localAvatar and (Wants("LayeredClothing") or (Wants("DynamicAvatarDistance") and distanceCulled)) then DesiredSet(desired, "Enabled", false) end return desired end if Safe.IsA(instance, "Highlight") then if not localAvatar and ((safeDecor and Wants("SelectiveHighlightRemoval")) or (otherAvatar and (Wants("OtherPlayersCharacterHighlightsReduction") or (Wants("DynamicAvatarDistance") and distanceCulled)))) then DesiredSet(desired, "Enabled", false) end return desired end if not localAvatar and Safe.IsA(instance, "BillboardGui") and safeDecor then if Wants("SafeDecorBillboardDisable") then DesiredSet(desired, "Enabled", false) else local originalMaxDistance = PropertyStore.GetOriginal(instance, "MaxDistance") if Wants("SafeBillboardGuiOptimization") and type(originalMaxDistance) == "number" then DesiredSet(desired, "MaxDistance", originalMaxDistance > 0 and math.min(originalMaxDistance, Config.BillboardMaxDistance) or Config.BillboardMaxDistance) end if Wants("BillboardGuiDistanceCulling") and type(originalMaxDistance) == "number" then DesiredSet(desired, "MaxDistance", originalMaxDistance > 0 and math.min(originalMaxDistance, Config.BillboardGuiMaxDistanceExtreme) or Config.BillboardGuiMaxDistanceExtreme) end if Wants("BillboardGuiDistanceStep") then DesiredSet(desired, "DistanceStep", math.max(PropertyStore.GetOriginal(instance, "DistanceStep") or 0, Config.BillboardDistanceStep)) end end return desired end if not localAvatar and Safe.IsA(instance, "SurfaceGui") and safeDecor then if Wants("SafeDecorSurfaceGuiDisable") then DesiredSet(desired, "Enabled", false) else local originalMaxDistance = PropertyStore.GetOriginal(instance, "MaxDistance") if Wants("SafeSurfaceGuiOptimization") and type(originalMaxDistance) == "number" then DesiredSet(desired, "MaxDistance", originalMaxDistance > 0 and math.min(originalMaxDistance, Config.SurfaceGuiMaxDistance) or Config.SurfaceGuiMaxDistance) end if Wants("SurfaceGuiDistanceCulling") and type(originalMaxDistance) == "number" then DesiredSet(desired, "MaxDistance", originalMaxDistance > 0 and math.min(originalMaxDistance, Config.SurfaceGuiMaxDistanceExtreme) or Config.SurfaceGuiMaxDistanceExtreme) end if Wants("SurfaceGuiPixelDensityCap") then local pixelsPerStud = PropertyStore.GetOriginal(instance, "PixelsPerStud") if type(pixelsPerStud) == "number" then DesiredSet(desired, "PixelsPerStud", math.min(pixelsPerStud, Config.SurfaceGuiPixelsPerStudCap)) end end end return desired end if not localAvatar and Safe.IsA(instance, "SpecialMesh") and not inTool then if Wants("SpecialMeshTextureClearGlobal") or (safeDecor and Wants("SafeDecorSpecialMeshTextureClear")) then DesiredSet(desired, "TextureId", "") end return desired end if safeDecor and not localAvatar then if Safe.IsA(instance, "SelectionBox") and Wants("SelectionBoxOptimization") then DesiredSet(desired, "Visible", false) end if Safe.IsA(instance, "SelectionSphere") and Wants("SelectionSphereOptimization") then DesiredSet(desired, "Visible", false) end if Safe.IsA(instance, "BoxHandleAdornment") and Wants("BoxHandleAdornmentOptimization") then DesiredSet(desired, "Visible", false) end if Safe.IsA(instance, "SphereHandleAdornment") and Wants("SphereHandleAdornmentOptimization") then DesiredSet(desired, "Visible", false) end end return desired end function OptimizerEngine.ApplyInstance(instance) if not State.Enabled or not Safe.IsAlive(instance) then return false end State.SeenInstances[instance] = true local desired = OptimizerEngine.BuildDesiredProperties(instance) PropertyStore.Reconcile(instance, desired) State.ProcessedInstances = State.ProcessedInstances + 1 return true end function OptimizerEngine.ApplyGlobal() if not State.Enabled then return end local lightingDesired = {} if Wants("GlobalShadows") then lightingDesired.GlobalShadows = false end if Wants("Fog") then lightingDesired.FogStart = 0; lightingDesired.FogEnd = 1000000 end if Wants("EnvironmentScales") then lightingDesired.EnvironmentDiffuseScale = 0 lightingDesired.EnvironmentSpecularScale = 0 end PropertyStore.Reconcile(Lighting, lightingDesired) local terrain = Workspace:FindFirstChildOfClass("Terrain") if terrain then local terrainDesired = {} if Wants("TerrainDecoration") then terrainDesired.Decoration = false end if Wants("WaterWaves") then terrainDesired.WaterWaveSize = 0 terrainDesired.WaterWaveSpeed = 0 end if Wants("WaterReflectance") then terrainDesired.WaterReflectance = 0 end if Wants("WaterInvisible") then terrainDesired.WaterTransparency = 1 end PropertyStore.Reconcile(terrain, terrainDesired) end end function OptimizerEngine.ReconcileTracked() for instance in pairs(State.SeenInstances) do if Safe.IsAlive(instance) then OptimizerEngine.ApplyInstance(instance) else State.SeenInstances[instance] = nil end end end QueueEngine = {} local function QueueCount(queue, head) return math.max(0, #queue - head + 1) end function QueueEngine.Count() return QueueCount(State.QueueHigh, State.QueueHighHead) + QueueCount(State.QueueNormal, State.QueueNormalHead) end function QueueEngine.GetBatchBudget() local budget = Config.BatchBudgetSeconds local fps = State.AverageFPS > 0 and State.AverageFPS or State.FPS if State.Tier >= 4 then budget = budget * 0.25 elseif State.Tier == 3 then budget = budget * 0.40 elseif State.Tier == 2 then budget = budget * 0.60 elseif State.Tier == 1 then budget = budget * 0.80 end if fps > 0 and fps < 35 then budget = math.min(budget, 0.00065) elseif fps > 0 and fps < 45 then budget = math.min(budget, 0.00090) end return math.clamp(budget, 0.00035, Config.BatchBudgetSeconds) end function QueueEngine.Clear() State.QueueGeneration = State.QueueGeneration + 1 table.clear(State.QueueHigh) table.clear(State.QueueNormal) table.clear(State.Pending) State.QueueHighHead, State.QueueNormalHead = 1, 1 State.QueueDropped = 0 end function QueueEngine.Compact(queueName) local queue = queueName == "HIGH" and State.QueueHigh or State.QueueNormal local headName = queueName == "HIGH" and "QueueHighHead" or "QueueNormalHead" local head = State[headName] if head <= 1 then return end local compacted = {} for index = head, #queue do local instance = queue[index] if instance then table.insert(compacted, instance) end end table.clear(queue) for index, instance in ipairs(compacted) do queue[index] = instance end State[headName] = 1 end function QueueEngine.Pop() if State.QueueHighHead <= #State.QueueHigh then local item = State.QueueHigh[State.QueueHighHead] State.QueueHighHead = State.QueueHighHead + 1 return item end if State.QueueNormalHead <= #State.QueueNormal then local item = State.QueueNormal[State.QueueNormalHead] State.QueueNormalHead = State.QueueNormalHead + 1 return item end return nil end function QueueEngine.Enqueue(instance, highPriority) if not State.Enabled or typeof(instance) ~= "Instance" or not Safe.IsAlive(instance) then return false end if not QueueEngine.IsCandidate(instance) then return false end if State.Pending[instance] then return false end if QueueEngine.Count() >= Config.MaxQueueEntries then State.QueueDropped = State.QueueDropped + 1 return false end State.Pending[instance] = true if highPriority then table.insert(State.QueueHigh, instance) else table.insert(State.QueueNormal, instance) end QueueEngine.StartWorker() return true end function QueueEngine.StartWorker() if State.QueueWorker or not State.Enabled then return end State.QueueWorker = true local workerGeneration = State.QueueGeneration task.spawn(function() while State.Running and State.Enabled and workerGeneration == State.QueueGeneration do local started = os.clock() local processed = 0 local batchBudget = QueueEngine.GetBatchBudget() local tierScale = 1 - (State.Tier * 0.12) local maxBatch = math.max(20, math.floor(Config.BatchSize * tierScale)) if State.Tier >= 4 then maxBatch = math.min(maxBatch, Config.PanicBatchSize) end while processed < maxBatch and os.clock() - started < batchBudget and workerGeneration == State.QueueGeneration do local instance = QueueEngine.Pop() if not instance then break end State.Pending[instance] = nil if Safe.IsAlive(instance) then OptimizerEngine.ApplyInstance(instance) end processed = processed + 1 end if QueueEngine.Count() == 0 then break end local yieldTime = State.Tier >= 4 and (Config.BatchYield * 3) or Config.BatchYield task.wait(yieldTime) end if workerGeneration == State.QueueGeneration then if State.QueueHighHead > #State.QueueHigh then table.clear(State.QueueHigh); State.QueueHighHead = 1 elseif State.QueueHighHead > 512 then QueueEngine.Compact("HIGH") end if State.QueueNormalHead > #State.QueueNormal then table.clear(State.QueueNormal); State.QueueNormalHead = 1 elseif State.QueueNormalHead > 512 then QueueEngine.Compact("NORMAL") end end State.QueueWorker = false if State.Running and State.Enabled and QueueEngine.Count() > 0 then QueueEngine.StartWorker() end end) end function QueueEngine.IsCandidate(instance) return Safe.IsA(instance, "BasePart") or Safe.IsA(instance, "Decal") or Safe.IsA(instance, "Texture") or Safe.IsA(instance, "SurfaceAppearance") or Safe.IsPostEffect(instance) or Safe.IsA(instance, "Atmosphere") or Safe.IsA(instance, "Clouds") or Safe.IsLight(instance) or Safe.IsA(instance, "ParticleEmitter") or Safe.IsA(instance, "Trail") or Safe.IsA(instance, "Beam") or Safe.IsA(instance, "Fire") or Safe.IsA(instance, "Smoke") or Safe.IsA(instance, "Sparkles") or Safe.IsSoundEffect(instance) or Safe.IsA(instance, "Sky") or Safe.IsA(instance, "WrapLayer") or Safe.IsA(instance, "Highlight") or Safe.IsA(instance, "BillboardGui") or Safe.IsA(instance, "SurfaceGui") or Safe.IsA(instance, "SpecialMesh") or Safe.IsA(instance, "SelectionBox") or Safe.IsA(instance, "SelectionSphere") or Safe.IsA(instance, "BoxHandleAdornment") or Safe.IsA(instance, "SphereHandleAdornment") end function QueueEngine.ScanRoot(root, highPriority, scanGeneration) if not root or not State.Enabled then return end local started = os.clock() local stack = { [1] = root } local stackHead, stackTail = 1, 1 local visited = 0 while stackHead <= stackTail and State.Running and State.Enabled and (scanGeneration == nil or scanGeneration == State.ScanGeneration) do local current = stack[stackHead] stack[stackHead] = nil stackHead = stackHead + 1 if current ~= root and QueueEngine.IsCandidate(current) then QueueEngine.Enqueue(current, highPriority) end local ok, children = pcall(function() return current:GetChildren() end) if ok then for index = 1, #children do stackTail = stackTail + 1 stack[stackTail] = children[index] end end visited = visited + 1 if visited % 160 == 0 then task.wait() end end State.LastScanSeconds = os.clock() - started Logger.Info(string.format("Scan incremental concluido: %d nos em %.2fs", visited, State.LastScanSeconds), "SCAN") end function QueueEngine.ScanWorld() if State.InitialScanStarted or not State.Enabled then return end State.InitialScanStarted = true State.ScanGeneration = State.ScanGeneration + 1 local scanGeneration = State.ScanGeneration task.spawn(function() local started = os.clock() QueueEngine.ScanRoot(Workspace, true, scanGeneration) QueueEngine.ScanRoot(Lighting, true, scanGeneration) for _, player in ipairs(Players:GetPlayers()) do if scanGeneration ~= State.ScanGeneration or not State.Enabled then break end if player.Character then QueueEngine.ScanRoot(player.Character, true, scanGeneration) end end if scanGeneration == State.ScanGeneration then State.LastScanSeconds = os.clock() - started State.InitialScanDone = State.Enabled State.InitialScanStarted = false if State.InitialScanDone then Logger.Info(string.format("Varredura completa: %.2fs", State.LastScanSeconds), "SCAN") end end end) end function QueueEngine.ReapplyTracked() task.spawn(function() local processed = 0 for instance in pairs(State.SeenInstances) do if State.Running and State.Enabled and Safe.IsAlive(instance) then if State.Automatic then QueueEngine.Enqueue(instance, false) else OptimizerEngine.ApplyInstance(instance) end end processed = processed + 1 if processed % 100 == 0 then task.wait() end end end) end MemoryCleaner = {} function MemoryCleaner.TrimLog() while #State.Log > Config.MaxLogEntries do table.remove(State.Log, 1) end end function MemoryCleaner.CompactQueues() if State.QueueHighHead > 256 then QueueEngine.Compact("HIGH") end if State.QueueNormalHead > 256 then QueueEngine.Compact("NORMAL") end end function MemoryCleaner.Trim() MemoryCleaner.TrimLog() MemoryCleaner.CompactQueues() Safe.TrimTimedCaches() local ok = pcall(function() collectgarbage("step", 48) end) if not ok then Logger.Warn("Coleta incremental nao disponivel neste contexto", "MEMORY") end end function MemoryCleaner.CleanNow() local before pcall(function() before = Stats:GetTotalMemoryUsageMb() end) MemoryCleaner.Trim() local after pcall(function() after = Stats:GetTotalMemoryUsageMb() end) if before and after then Logger.Info(string.format("Limpeza de estruturas internas; memoria reportada %.1f -> %.1f MB (nao garantida)", before, after), "MEMORY") else Logger.Info("Estruturas internas do Booster compactadas; RAM do motor nao e controlavel", "MEMORY") end end DistanceEngine = { Snapshot = {}, Cursor = 1, LastSnapshot = 0, Refreshing = false, Generation = 0 } function DistanceEngine.IsEnabled() if not Wants("CameraBasedCulling") then return false end return Wants("AdaptiveRenderDistance") or Wants("SafeDecorDistanceCulling") or Wants("SafeDebrisDistanceCulling") or Wants("DynamicEffectsDistance") or Wants("DynamicLightsDistance") or Wants("DynamicDebrisDistance") or Wants("DynamicAvatarDistance") or Wants("ParticleDistanceCulling") or Wants("TrailDistanceOptimization") or Wants("BeamDistanceCulling") or Wants("DistantLightCulling") end function DistanceEngine.GetCameraPosition() local camera = Workspace.CurrentCamera if not camera then return nil end local ok, cframe = pcall(function() return camera.CFrame end) if not ok then return nil end return cframe.Position end function DistanceEngine.GetWorldPosition(instance) if Safe.IsA(instance, "BasePart") then local ok, position = Safe.Get(instance, "Position") if ok then return position end end if Safe.IsA(instance, "Attachment") then local ok, position = Safe.Get(instance, "WorldPosition") if ok then return position end end local cursor, depth = instance, 0 while cursor and cursor ~= Workspace and depth < 18 do if Safe.IsA(cursor, "BasePart") then local ok, position = Safe.Get(cursor, "Position") if ok then return position end end cursor, depth = cursor.Parent, depth + 1 end local owner = Safe.GetPlayerFromAncestor(instance) if owner and owner.Character then local root = owner.Character:FindFirstChild("HumanoidRootPart") if root then return root.Position end end return nil end function DistanceEngine.GetLimit(instance) if Safe.IsDebris(instance) and (Wants("SafeDebrisDistanceCulling") or Wants("DynamicDebrisDistance")) then return Config.SafeDebrisDistance end if Safe.IsDecor(instance) and (Wants("AdaptiveRenderDistance") or Wants("SafeDecorDistanceCulling")) then return Config.SafeDecorDistance end if Safe.IsLight(instance) and (Wants("DynamicLightsDistance") or Wants("DistantLightCulling")) then return Config.LightDistance end if (Safe.IsA(instance, "ParticleEmitter") and Wants("ParticleDistanceCulling")) or (Safe.IsA(instance, "Trail") and Wants("TrailDistanceOptimization")) or (Safe.IsA(instance, "Beam") and Wants("BeamDistanceCulling")) or ((Safe.IsA(instance, "ParticleEmitter") or Safe.IsA(instance, "Trail") or Safe.IsA(instance, "Beam")) and Wants("DynamicEffectsDistance")) then return Config.EffectDistance end if Safe.IsOtherAvatar(instance) and Wants("DynamicAvatarDistance") then return Config.AvatarDistance end return nil end function DistanceEngine.RefreshSnapshot() if DistanceEngine.Refreshing then return end DistanceEngine.Refreshing = true DistanceEngine.Generation = DistanceEngine.Generation + 1 local generation = DistanceEngine.Generation task.spawn(function() local snapshot = {} local visited = 0 for instance in pairs(State.SeenInstances) do if generation ~= DistanceEngine.Generation or not State.Running then break end if Safe.IsAlive(instance) then snapshot[#snapshot + 1] = instance end visited = visited + 1 if visited % 300 == 0 then task.wait() end end if generation == DistanceEngine.Generation then DistanceEngine.Snapshot = snapshot DistanceEngine.Cursor = 1 DistanceEngine.LastSnapshot = os.clock() DistanceEngine.Refreshing = false end end) end function DistanceEngine.UpdateOne(instance, cameraPosition) local limit = DistanceEngine.GetLimit(instance) local shouldCull = false if limit and cameraPosition then local position = DistanceEngine.GetWorldPosition(instance) if position then local distance = (position - cameraPosition).Magnitude local wasCulled = State.DistanceCulled[instance] == true local threshold = wasCulled and limit * (1 - Config.DistanceHysteresis) or limit * (1 + Config.DistanceHysteresis) shouldCull = distance > threshold end end local wasCulled = State.DistanceCulled[instance] == true if shouldCull ~= wasCulled then if shouldCull then State.DistanceCulled[instance] = true else State.DistanceCulled[instance] = nil end if State.Automatic then QueueEngine.Enqueue(instance, false) else OptimizerEngine.ApplyInstance(instance) end end end function DistanceEngine.Step() if not State.Enabled or not DistanceEngine.IsEnabled() then return end local now = os.clock() local interval = Wants("DistanceUpdateThrottling") and Config.DistanceSlowInterval or Config.DistanceInterval if now - State.LastDistanceRun < interval then return end State.LastDistanceRun = now if #DistanceEngine.Snapshot == 0 or DistanceEngine.Cursor > #DistanceEngine.Snapshot or now - DistanceEngine.LastSnapshot > 5 then DistanceEngine.RefreshSnapshot() if DistanceEngine.Refreshing then return end end local cameraPosition = DistanceEngine.GetCameraPosition() if not cameraPosition then return end local processed = 0 local started = os.clock() local distanceBudget = QueueEngine.GetBatchBudget() * 0.65 while DistanceEngine.Cursor <= #DistanceEngine.Snapshot and processed < Config.MaxDistancePerPass and os.clock() - started < distanceBudget do local instance = DistanceEngine.Snapshot[DistanceEngine.Cursor] DistanceEngine.Cursor = DistanceEngine.Cursor + 1 if instance and Safe.IsAlive(instance) then DistanceEngine.UpdateOne(instance, cameraPosition) end processed = processed + 1 end end function DistanceEngine.Reset() DistanceEngine.Generation = DistanceEngine.Generation + 1 DistanceEngine.Refreshing = false table.clear(DistanceEngine.Snapshot) DistanceEngine.Cursor = 1 DistanceEngine.LastSnapshot = 0 table.clear(State.DistanceCulled) end MetricsMonitor = {} function MetricsMonitor.OnFrame(deltaTime) if type(deltaTime) ~= "number" or deltaTime <= 0 or deltaTime > 1 then return end local frameMs = deltaTime * 1000 if State.Benchmark and State.Benchmark.Active then local frameTimes = State.Benchmark.FrameTimes frameTimes[#frameTimes + 1] = frameMs end if frameMs < State.SessionMinFrameTime then State.SessionMinFrameTime = frameMs end if frameMs > State.SessionMaxFrameTime then State.SessionMaxFrameTime = frameMs end if frameMs > 50 then State.SuddenDropCount = State.SuddenDropCount + 1 State.LastSuddenDropTime = os.clock() end local index = State.FrameTimeHead State.FrameTimes[index] = frameMs State.FrameTimeHead = (index % Config.MaxMetricSamples) + 1 State.FrameTimeCount = math.min(State.FrameTimeCount + 1, Config.MaxMetricSamples) end function MetricsMonitor.GetFrameSamples() local result = {} local count = State.FrameTimeCount local start = State.FrameTimeCount == Config.MaxMetricSamples and State.FrameTimeHead or 1 for offset = 0, count - 1 do local index = ((start + offset - 1) % Config.MaxMetricSamples) + 1 local value = State.FrameTimes[index] if type(value) == "number" then result[#result + 1] = value end end return result end function MetricsMonitor.Percentile(sortedValues, percentile) local count = #sortedValues if count == 0 then return 0 end local index = math.clamp(math.ceil(count * percentile), 1, count) return sortedValues[index] end function MetricsMonitor.ReadPing() local ok, pingSeconds = pcall(function() return LocalPlayer:GetNetworkPing() end) if ok and type(pingSeconds) == "number" then State.Ping = pingSeconds * 1000 end return State.Ping end function MetricsMonitor.ReadMemory() local ok, memory = pcall(function() return Stats:GetTotalMemoryUsageMb() end) if ok and type(memory) == "number" then State.MemoryMB = memory end return State.MemoryMB end function MetricsMonitor.Recalculate() local samples = MetricsMonitor.GetFrameSamples() if #samples == 0 then return end local current = samples[#samples] local sum = 0 for _, frameMs in ipairs(samples) do sum = sum + frameMs end local sorted = table.clone(samples) table.sort(sorted) State.FrameTime = current State.AverageFrameTime = sum / #samples State.P95FrameTime = MetricsMonitor.Percentile(sorted, 0.95) local p99 = MetricsMonitor.Percentile(sorted, 0.99) State.FPS = current > 0 and (1000 / current) or 0 State.AverageFPS = State.AverageFrameTime > 0 and (1000 / State.AverageFrameTime) or 0 State.MinimumFPS = State.SessionMaxFrameTime > 0 and (1000 / State.SessionMaxFrameTime) or 0 State.MaximumFPS = State.SessionMinFrameTime < math.huge and (1000 / State.SessionMinFrameTime) or 0 State.OnePercentLow = p99 > 0 and (1000 / p99) or 0 State.CurrentSampleCount = #samples table.insert(State.FPSHistory, State.FPS) while #State.FPSHistory > Config.MaxFPSHistory do table.remove(State.FPSHistory, 1) end end function MetricsMonitor.Snapshot() return { FPS = State.FPS, AverageFPS = State.AverageFPS, MinimumFPS = State.MinimumFPS, MaximumFPS = State.MaximumFPS, FrameTime = State.FrameTime, AverageFrameTime = State.AverageFrameTime, P95FrameTime = State.P95FrameTime, OnePercentLow = State.OnePercentLow, Ping = State.Ping, MemoryMB = State.MemoryMB, ProcessedInstances = State.ProcessedInstances, AppliedProperties = State.AppliedProperties, RestoredProperties = State.RestoredProperties, FailedProperties = State.FailedProperties, ExternalChangesPreserved = State.ExternalChangesPreserved, QueueSize = QueueEngine.Count(), LastScanSeconds = State.LastScanSeconds, CacheStats = table.clone(State.CacheStats), Tier = State.Tier, Profile = State.Profile, } end function MetricsMonitor.Tick() MetricsMonitor.Recalculate() MetricsMonitor.ReadPing() MetricsMonitor.ReadMemory() end function MetricsMonitor.Start() if State.Connections.PreRender then return end local callback = function(deltaTime) MetricsMonitor.OnFrame(deltaTime) end local connected, connection = pcall(function() return RunService.PreRender:Connect(callback) end) if not connected then connected, connection = pcall(function() return RunService.RenderStepped:Connect(callback) end) end if connected then State.Connections.PreRender = connection else Logger.Error("Nao foi possivel iniciar captura de frame-time", "METRICS", nil, nil, connection) return end if State.MetricsLoopStarted then return end State.MetricsLoopStarted = true task.spawn(function() while State.Running do task.wait(State.Tier >= 4 and 1.25 or Config.MetricsInterval) if State.Running then MetricsMonitor.Tick() end end end) end AdaptiveController = {} State.TierHistory = {} local TierNames = { [0] = "NORMAL", [1] = "OPTIMIZED", [2] = "EXTREME", [3] = "POTATO", [4] = "PANIC MODE" } function AdaptiveController.CandidateTier() local fps = State.AverageFPS > 0 and State.AverageFPS or State.FPS local p95 = State.P95FrameTime if fps <= 0 then return State.Tier, "Aguardando amostras suficientes" end if os.clock() - State.LastSuddenDropTime < 1 and State.FrameTime > 50 then return 4, "Queda repentina de frame-time detectada" end if fps < Config.Tier4FPS or p95 > Config.Tier4P95 then return 4, "FPS abaixo do limite critico ou p95 elevado" end if fps < Config.Tier3FPS or p95 > Config.Tier3P95 then return 3, "FPS ou p95 no limite POTATO" end if fps < Config.Tier2FPS or p95 > Config.Tier2P95 then return 2, "FPS ou p95 no limite EXTREME" end if fps < Config.TargetFPS or p95 > Config.Tier1P95 then return 1, "Meta de FPS nao sustentada" end return 0, "Desempenho dentro da meta configurada" end function AdaptiveController.RecordChange(oldTier, newTier, reason) local event = { Time = os.clock(), From = oldTier, To = newTier, Reason = reason } table.insert(State.TierHistory, event) while #State.TierHistory > 100 do table.remove(State.TierHistory, 1) end Logger.Write("INFO", "ADAPTIVE", string.format("%s -> %s: %s", TierNames[oldTier], TierNames[newTier], reason)) end function AdaptiveController.ApplyTier(newTier, reason) newTier = math.clamp(math.floor(newTier), 0, 4) if State.Tier == newTier then State.TierReason = reason; return end local oldTier = State.Tier State.Tier = newTier State.Panic = newTier >= 4 State.TierReason = reason State.LastTierChange = os.clock() AdaptiveController.RecordChange(oldTier, newTier, reason) if State.Enabled then OptimizerEngine.ApplyGlobal() QueueEngine.ReapplyTracked() end end function AdaptiveController.Update() if not State.Enabled or not State.Adaptive then if State.Tier ~= 0 then AdaptiveController.ApplyTier(0, "Adaptativo desativado") end return end local candidate, reason = AdaptiveController.CandidateTier() local now = os.clock() if candidate > State.Tier then State.RecoveryStartedAt = nil if now - State.LastTierChange >= Config.TierChangeCooldown then AdaptiveController.ApplyTier(candidate, reason) end return end if candidate < State.Tier then if State.FPS >= Config.RecoveryFPS and State.P95FrameTime <= Config.Tier1P95 then State.RecoveryStartedAt = State.RecoveryStartedAt or now if now - State.RecoveryStartedAt >= Config.RecoverySeconds and now - State.LastTierChange >= Config.TierChangeCooldown then AdaptiveController.ApplyTier(State.Tier - 1, "Estabilidade recuperada por " .. Config.RecoverySeconds .. "s") State.RecoveryStartedAt = nil end else State.RecoveryStartedAt = nil end return end State.RecoveryStartedAt = nil end function AdaptiveController.Start() if State.AdaptiveLoopStarted then return end State.AdaptiveLoopStarted = true task.spawn(function() while State.Running do task.wait(Config.AdaptiveInterval) if State.Running then AdaptiveController.Update() end end end) end Benchmark = {} local function SummarizeFrameTimes(frameTimes, duration) if #frameTimes == 0 then return nil end local sorted = table.clone(frameTimes) table.sort(sorted) local sum, maximumFrame = 0, 0 for _, frameMs in ipairs(frameTimes) do sum = sum + frameMs if frameMs > maximumFrame then maximumFrame = frameMs end end local averageFrame = sum / #frameTimes return { Count = #frameTimes, AverageFPS = averageFrame > 0 and (1000 / averageFrame) or 0, AverageFrameTime = averageFrame, MinimumFPS = maximumFrame > 0 and (1000 / maximumFrame) or 0, P95FrameTime = MetricsMonitor.Percentile(sorted, 0.95), OnePercentLow = MetricsMonitor.Percentile(sorted, 0.99) > 0 and (1000 / MetricsMonitor.Percentile(sorted, 0.99)) or 0, Duration = duration, } end function Benchmark.Start(kind, duration) if State.Benchmark.Active then Logger.Warn("Benchmark ja esta em execucao", "BENCHMARK") return false end if kind ~= "BASELINE" and kind ~= "OPTIMIZED" then return false end if kind == "BASELINE" and State.Enabled then Logger.Warn("Desative o Booster para medir o baseline", "BENCHMARK") return false end if kind == "OPTIMIZED" and not State.Enabled then Logger.Warn("Ative o Booster para medir o perfil otimizado", "BENCHMARK") return false end State.Benchmark.Active = true State.Benchmark.Kind = kind State.Benchmark.StartedAt = os.clock() State.Benchmark.Duration = math.clamp(tonumber(duration) or Config.BenchmarkSeconds, 5, 90) State.Benchmark.FrameTimes = {} Logger.Info("Benchmark " .. kind .. " iniciado", "BENCHMARK") task.spawn(function() while State.Running and State.Benchmark.Active do if os.clock() - State.Benchmark.StartedAt >= State.Benchmark.Duration then break end task.wait(0.1) end if State.Benchmark.Active then Benchmark.Stop() end end) return true end function Benchmark.Stop() if not State.Benchmark.Active then return false end local kind = State.Benchmark.Kind local elapsed = math.max(0, os.clock() - State.Benchmark.StartedAt) local summary = SummarizeFrameTimes(State.Benchmark.FrameTimes, elapsed) State.Benchmark.Active = false State.Benchmark.Kind = nil if summary then if kind == "BASELINE" then State.Benchmark.Baseline = summary elseif kind == "OPTIMIZED" then State.Benchmark.Optimized = summary end Logger.Info(string.format("%s: %.1f FPS medio, %.2fms medio, %d amostras", kind, summary.AverageFPS, summary.AverageFrameTime, summary.Count), "BENCHMARK") else Logger.Warn("Benchmark terminou sem amostras suficientes", "BENCHMARK") end return true end function Benchmark.Compare() local baseline, optimized = State.Benchmark.Baseline, State.Benchmark.Optimized if not baseline or not optimized then return nil end local delta = optimized.AverageFPS - baseline.AverageFPS local percent = baseline.AverageFPS > 0 and (delta / baseline.AverageFPS) * 100 or 0 local comparison = { DeltaFPS = delta, DeltaPercent = percent, DeltaFrameTime = optimized.AverageFrameTime - baseline.AverageFrameTime, Baseline = baseline, Optimized = optimized, } State.Benchmark.LastComparison = comparison return comparison end function Benchmark.Reset() if State.Benchmark.Active then Benchmark.Stop() end State.Benchmark.Baseline = nil State.Benchmark.Optimized = nil State.Benchmark.LastComparison = nil State.Benchmark.FrameTimes = {} Logger.Info("Historico de benchmark reiniciado", "BENCHMARK") end local DefinitionByKey = {} for _, definition in ipairs(OptionDefinitions) do DefinitionByKey[definition.Key] = definition end for _, key in ipairs({ "SurfaceAppearance", "SafeDecorSurfaceAppearanceReduction" }) do local definition = DefinitionByKey[key] if definition then definition.Supported = false definition.UnsupportedReason = "Map properties de SurfaceAppearance exigem permissao Plugin; LocalScript nao pode modifica-las." definition.CurrentValue = false Options[key] = false end end local AntiResetGuard = {} function AntiResetGuard.Run() if not State.Enabled then return end OptimizerEngine.ApplyGlobal() State.LastGuardRun = os.clock() end BackgroundMonitor = {} function BackgroundMonitor.DisconnectWorld() for _, name in ipairs({ "WorkspaceAdded", "LightingAdded" }) do local connection = State.Connections[name] if connection then connection:Disconnect(); State.Connections[name] = nil end end end function BackgroundMonitor.DisconnectPlayers() for player, connection in pairs(State.PlayerConnections) do if connection then pcall(function() connection:Disconnect() end) end State.PlayerConnections[player] = nil end for _, name in ipairs({ "PlayerAdded", "PlayerRemoving" }) do local connection = State.Connections[name] if connection then connection:Disconnect(); State.Connections[name] = nil end end end function BackgroundMonitor.ScanCharacter(character) if character and State.Enabled then local scanGeneration = State.ScanGeneration task.spawn(function() QueueEngine.ScanRoot(character, true, scanGeneration) end) end end function BackgroundMonitor.ConnectPlayer(player) if State.PlayerConnections[player] then return end local connection = player.CharacterAdded:Connect(function(character) BackgroundMonitor.ScanCharacter(character) end) State.PlayerConnections[player] = connection if player.Character then BackgroundMonitor.ScanCharacter(player.Character) end end function BackgroundMonitor.Refresh() BackgroundMonitor.DisconnectWorld() BackgroundMonitor.DisconnectPlayers() if not State.Enabled or not State.Automatic or not Wants("LiveGuard") then return end State.Connections.WorkspaceAdded = Workspace.DescendantAdded:Connect(function(instance) QueueEngine.Enqueue(instance, false) end) State.Connections.LightingAdded = Lighting.DescendantAdded:Connect(function(instance) QueueEngine.Enqueue(instance, true) end) for _, player in ipairs(Players:GetPlayers()) do BackgroundMonitor.ConnectPlayer(player) end State.Connections.PlayerAdded = Players.PlayerAdded:Connect(function(player) BackgroundMonitor.ConnectPlayer(player) end) State.Connections.PlayerRemoving = Players.PlayerRemoving:Connect(function(player) local connection = State.PlayerConnections[player] if connection then connection:Disconnect(); State.PlayerConnections[player] = nil end end) end function BackgroundMonitor.Start() if State.BackgroundStarted then return end State.BackgroundStarted = true DistanceEngine.Start() task.spawn(function() while State.Running do task.wait(Config.GuardInterval) if State.Running and State.Enabled and State.Automatic then AntiResetGuard.Run() MemoryCleaner.Trim() end end end) end function BackgroundMonitor.ScanInitial() if not State.Enabled then return end QueueEngine.ScanWorld() end ProfileManager = {} local function ProfileFromDefaults() local values = {} for _, definition in ipairs(OptionDefinitions) do values[definition.Key] = definition.DefaultValue end return values end local function MakeProfile(overrides) local profile = ProfileFromDefaults() for key, value in pairs(overrides or {}) do if DefinitionByKey[key] and DefinitionByKey[key].Supported then profile[key] = value == true end end return profile end local PresetProfiles = {} PresetProfiles.DEFAULT = MakeProfile({}) PresetProfiles.BALANCED = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = false, AtmosphereClouds = false, DynamicLights = false, Particles = false, Trails = false, Beams = false, FireSmokeSparkles = false, Decals = false, Textures = false, SurfaceAppearance = false, Sky = false, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, MeshPerformance = true, LayeredClothing = false, SoundEffects = true, Fog = false, EnvironmentScales = true, }) PresetProfiles["LOW END PC"] = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = true, AtmosphereClouds = true, DynamicLights = true, Particles = true, Trails = true, Beams = true, FireSmokeSparkles = true, Decals = true, Textures = true, SurfaceAppearance = true, Sky = true, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, MeshPerformance = true, LayeredClothing = true, SoundEffects = true, Fog = true, EnvironmentScales = true, ParticleRateLimiter = true, ParticleLifetimeReduction = true, TrailLifetimeLimiter = true, BeamSegmentReduction = true, LightRangeLimiter = true, LightBrightnessLimiter = true, SafeDecorDistanceCulling = true, SafeDebrisDistanceCulling = true, }) PresetProfiles.POTATO = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = true, AtmosphereClouds = true, DynamicLights = true, Particles = true, Trails = true, Beams = true, FireSmokeSparkles = true, Decals = true, Textures = true, SurfaceAppearance = true, Sky = true, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, WaterInvisible = true, MeshPerformance = true, MeshTextures = true, LayeredClothing = true, SoundEffects = true, Fog = true, EnvironmentScales = true, ParticleBurstOptimization = true, SafeDecorLocalHide = true, TaggedDebrisHide = true, AdaptiveRenderDistance = true, DynamicEffectsDistance = true, DynamicLightsDistance = true, SafeDecorDistanceCulling = true, SafeDebrisDistanceCulling = true, }) PresetProfiles.EXTREME = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = true, AtmosphereClouds = true, DynamicLights = true, Particles = true, Trails = true, Beams = true, FireSmokeSparkles = true, Decals = true, Textures = true, SurfaceAppearance = true, Sky = true, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, WaterInvisible = true, MeshPerformance = true, MeshTextures = true, LayeredClothing = true, SoundEffects = true, Fog = true, EnvironmentScales = true, ParticleBurstOptimization = true, ParticleRateLimiter = true, ParticleLifetimeReduction = true, ParticleLightEmissionReduction = true, ParticleLightInfluenceReduction = true, ParticleDistanceCulling = true, ParticleDensityControl = true, TrailLifetimeLimiter = true, TrailDistanceOptimization = true, BeamSegmentReduction = true, BeamTextureAnimationControl = true, BeamDistanceCulling = true, TrailRenderingReduction = true, LightRangeLimiter = true, LightBrightnessLimiter = true, DistantLightCulling = true, SelectiveShadowRemoval = true, DecorativeLightReduction = true, SelectiveHighlightRemoval = true, SafeBillboardGuiOptimization = true, SafeSurfaceGuiOptimization = true, SelectionBoxOptimization = true, SelectionSphereOptimization = true, BoxHandleAdornmentOptimization = true, SphereHandleAdornmentOptimization = true, IndividualBloomControl = true, IndividualBlurControl = true, IndividualColorCorrectionControl = true, IndividualSunRaysControl = true, IndividualDepthOfFieldControl = true, AtmosphereDensityController = true, AtmosphereHazeController = true, AtmosphereGlareController = true, SkyboxTextureOptimization = true, SafeDecorLocalHide = true, SafeDecorDistanceCulling = true, SafeDecorMaterialSimplification = true, SafeDecorMeshOptimization = true, SafeDecorMeshTextureRemoval = true, SafeDecorSurfaceAppearanceReduction = true, SafeDecorDecalReduction = true, SafeDecorTextureReduction = true, SafeDebrisDistanceCulling = true, SafeDebrisSizeControl = true, SafeDebrisShadowRemoval = true, AdaptiveRenderDistance = true, DynamicEffectsDistance = true, DynamicLightsDistance = true, DynamicDebrisDistance = true, CameraBasedCulling = true, }) PresetProfiles["NUCLEAR POTATO"] = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = true, AtmosphereClouds = true, DynamicLights = true, Particles = true, Trails = true, Beams = true, FireSmokeSparkles = true, Decals = true, Textures = true, SurfaceAppearance = true, Sky = true, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, WaterInvisible = true, MeshPerformance = true, MeshTextures = true, LayeredClothing = true, SoundEffects = true, Fog = true, EnvironmentScales = true, ParticleBurstOptimization = true, ParticleRateLimiter = true, ParticleLifetimeReduction = true, ParticleLightEmissionReduction = true, ParticleLightInfluenceReduction = true, ParticleDistanceCulling = true, ParticleDensityControl = true, TrailLifetimeLimiter = true, TrailDistanceOptimization = true, BeamSegmentReduction = true, BeamTextureAnimationControl = true, BeamDistanceCulling = true, TrailRenderingReduction = true, LightRangeLimiter = true, LightBrightnessLimiter = true, DistantLightCulling = true, SelectiveShadowRemoval = true, DecorativeLightReduction = true, SelectiveHighlightRemoval = true, SafeBillboardGuiOptimization = true, SafeSurfaceGuiOptimization = true, SelectionBoxOptimization = true, SelectionSphereOptimization = true, BoxHandleAdornmentOptimization = true, SphereHandleAdornmentOptimization = true, IndividualBloomControl = true, IndividualBlurControl = true, IndividualColorCorrectionControl = true, IndividualSunRaysControl = true, IndividualDepthOfFieldControl = true, AtmosphereDensityController = true, AtmosphereHazeController = true, AtmosphereGlareController = true, SkyboxTextureOptimization = true, SafeDecorLocalHide = true, SafeDecorDistanceCulling = true, SafeDecorMaterialSimplification = true, SafeDecorMeshOptimization = true, SafeDecorMeshTextureRemoval = true, SafeDecorSurfaceAppearanceReduction = true, SafeDecorDecalReduction = true, SafeDecorTextureReduction = true, TaggedDebrisHide = true, SafeDebrisDistanceCulling = true, SafeDebrisSizeControl = true, SafeDebrisShadowRemoval = true, OtherPlayersHairReduction = true, OtherPlayersHatReduction = true, OtherPlayersFaceAccessoriesReduction = true, OtherPlayersBackAccessoriesReduction = true, OtherPlayersShoulderAccessoriesReduction = true, OtherPlayersWaistAccessoriesReduction = true, OtherPlayersCharacterDecalsReduction = true, OtherPlayersCharacterParticlesReduction = true, OtherPlayersCharacterTrailsReduction = true, OtherPlayersCharacterHighlightsReduction = true, OtherPlayersCharacterLightsReduction = true, AdaptiveRenderDistance = true, DynamicEffectsDistance = true, DynamicLightsDistance = true, DynamicDebrisDistance = true, DynamicAvatarDistance = true, CameraBasedCulling = true, }) local V4MaxOptions = { "ParticleFlipbookBlendOff", "ParticleFlipbookFramerateCap", "ParticleRotationSpeedZero", "ParticleAccelerationZero", "ParticleDragZero", "ParticleSizeReduction", "TrailMinLengthOptimization", "TrailWidthScaleReduction", "TrailLightBlendReduction", "BeamWidthReduction", "BeamLightBlendReduction", "SurfaceGuiPixelDensityCap", "SurfaceGuiDistanceCulling", "BillboardGuiDistanceCulling", "BillboardGuiDistanceStep", "SafeDecorBillboardDisable", "SafeDecorSurfaceGuiDisable", "SafeDecorSpecialMeshTextureClear", "SafeDecorMeshDoubleSidedOff", "SafeDecorMaterialVariantClear", "SpecialMeshTextureClearGlobal", "DecalTextureAssetClearGlobal", "ParticleEmitterTextureClearGlobal", "TrailTextureClearGlobal", "BeamTextureClearGlobal", "MeshPartDoubleSidedOffGlobal", } for _, key in ipairs(V4MaxOptions) do PresetProfiles.POTATO[key] = true PresetProfiles.EXTREME[key] = true PresetProfiles["NUCLEAR POTATO"][key] = true end PresetProfiles.COMPETITIVE = MakeProfile({ GlobalShadows = true, PartShadows = true, SmoothPlastic = true, NoReflectance = true, PostEffects = true, AtmosphereClouds = false, DynamicLights = false, Particles = false, Trails = false, Beams = false, FireSmokeSparkles = false, Decals = false, Textures = false, SurfaceAppearance = false, Sky = false, TerrainDecoration = true, WaterWaves = true, WaterReflectance = true, WaterInvisible = false, MeshPerformance = true, MeshTextures = false, LayeredClothing = false, SoundEffects = true, Fog = false, EnvironmentScales = false, OtherPlayersHairReduction = false, OtherPlayersHatReduction = false, OtherPlayersFaceAccessoriesReduction = false, OtherPlayersBackAccessoriesReduction = false, OtherPlayersShoulderAccessoriesReduction = false, OtherPlayersWaistAccessoriesReduction = false, OtherPlayersCharacterDecalsReduction = false, OtherPlayersCharacterParticlesReduction = false, OtherPlayersCharacterTrailsReduction = false, OtherPlayersCharacterHighlightsReduction = false, OtherPlayersCharacterLightsReduction = false, AdaptiveRenderDistance = false, DynamicAvatarDistance = false, }) PresetProfiles.CUSTOM = ProfileFromDefaults() function ProfileManager.GetNames() local names = {} for name in pairs(PresetProfiles) do names[#names + 1] = name end for name in pairs(State.Profiles) do names[#names + 1] = name end table.sort(names) return names end function ProfileManager.Get(name) return State.Profiles[name] or PresetProfiles[name] end function ProfileManager.Save(name) if type(name) ~= "string" or name == "" then return false end if PresetProfiles[name] then Logger.Warn("Nome reservado para preset; escolha outro nome para salvar", "PROFILE") return false end local copy = {} for _, definition in ipairs(OptionDefinitions) do copy[definition.Key] = Options[definition.Key] == true end State.Profiles[name] = copy Logger.Info("Perfil salvo na sessao: " .. name, "PROFILE") return true end function ProfileManager.Duplicate(sourceName, newName) local source = ProfileManager.Get(sourceName) if not source or type(newName) ~= "string" or newName == "" then return false end local copy = {} for key, value in pairs(source) do copy[key] = value == true end State.Profiles[newName] = copy Logger.Info("Perfil duplicado: " .. sourceName .. " -> " .. newName, "PROFILE") return true end function ProfileManager.Compare(firstName, secondName) local first, second = ProfileManager.Get(firstName), ProfileManager.Get(secondName) if not first or not second then return nil end local differences = {} for _, definition in ipairs(OptionDefinitions) do if (first[definition.Key] == true) ~= (second[definition.Key] == true) then differences[#differences + 1] = { Key = definition.Key, Name = definition.Name, First = first[definition.Key] == true, Second = second[definition.Key] == true, } end end return differences end function DistanceEngine.Start() if State.DistanceLoopStarted then return end State.DistanceLoopStarted = true task.spawn(function() while State.Running do if State.Enabled and DistanceEngine.IsEnabled() then DistanceEngine.Step() local interval = Wants("DistanceUpdateThrottling") and Config.DistanceSlowInterval or Config.DistanceInterval task.wait(math.max(0.08, interval)) else task.wait(0.5) end end end) end BoosterController = {} function BoosterController.ApplyTracked() if not State.Enabled then return end if State.Automatic then QueueEngine.ReapplyTracked() else task.spawn(function() local processed = 0 for instance in pairs(State.SeenInstances) do if Safe.IsAlive(instance) then OptimizerEngine.ApplyInstance(instance) end processed = processed + 1 if processed % 100 == 0 then task.wait() end end end) end end function BoosterController.ToggleOption(key, value) local definition = DefinitionByKey[key] if not definition or not definition.Supported then return false, "OPTION_UNSUPPORTED" end if definition.RiskLevel == "HIGH" and value == true then return false, "CONFIRM_HIGH_IMPACT" end AdaptivePolicy.Set(key, value) if key == "LiveGuard" and value == false then State.ScanGeneration = State.ScanGeneration + 1 State.InitialScanStarted = false State.InitialScanDone = false end if State.Enabled then table.clear(State.DistanceCulled) OptimizerEngine.ApplyGlobal() BoosterController.ApplyTracked() BackgroundMonitor.Refresh() if key == "LiveGuard" and value == true and State.Automatic and not State.InitialScanDone then BackgroundMonitor.ScanInitial() end end Logger.Info(string.format("Opcao %s: %s", key, tostring(Options[key])), "OPTIMIZATION") return true end function BoosterController.EnableAll(confirmed) for _, definition in ipairs(OptionDefinitions) do if definition.Supported and definition.RiskLevel == "HIGH" and not confirmed then return false, "CONFIRM_HIGH_IMPACT" end end for _, definition in ipairs(OptionDefinitions) do if definition.Supported then AdaptivePolicy.Set(definition.Key, true) end end if State.Enabled then table.clear(State.DistanceCulled) OptimizerEngine.ApplyGlobal() BoosterController.ApplyTracked() BackgroundMonitor.Refresh() end Logger.Warn("Todas as opcoes suportadas foram ativadas", "CONFIG") return true end function BoosterController.ToggleOneClick() if State.OneClickActive then State.OneClickActive = false BoosterController.Disable() State.Profile = "DEFAULT" return false end State.Adaptive = true State.Automatic = true table.clear(State.UserOverrides) for _, definition in ipairs(OptionDefinitions) do if definition.Supported then AdaptivePolicy.Set(definition.Key, true) end end State.Profile = "ONE-CLICK MAX" State.OneClickActive = true if not State.Enabled then BoosterController.Enable() else table.clear(State.DistanceCulled) OptimizerEngine.ApplyGlobal() BoosterController.ApplyTracked() BackgroundMonitor.Refresh() if not State.InitialScanDone and not State.InitialScanStarted then BackgroundMonitor.ScanInitial() end end Logger.Warn("ONE-CLICK MAX: todos os modulos suportados foram ativados", "CONFIG") return true end function BoosterController.DisableAllOptions() for _, definition in ipairs(OptionDefinitions) do if definition.Supported then AdaptivePolicy.Set(definition.Key, false) end end if State.Enabled then table.clear(State.DistanceCulled) OptimizerEngine.ApplyGlobal() BoosterController.ApplyTracked() BackgroundMonitor.Refresh() end Logger.Info("Todas as opcoes suportadas foram desativadas", "CONFIG") end function BoosterController.Enable() if State.Enabled or not State.Running then return false end State.Enabled = true State.StartedAt = os.clock() State.Tier = 0 State.Panic = false State.RecoveryStartedAt = nil QueueEngine.Clear() Logger.Info("Ultra Potato V4 ativado", "SYSTEM") OptimizerEngine.ApplyGlobal() BackgroundMonitor.Start() MetricsMonitor.Start() AdaptiveController.Start() BackgroundMonitor.Refresh() if State.InitialScanDone then BoosterController.ApplyTracked() else BackgroundMonitor.ScanInitial() end return true end function BoosterController.Disable() if not State.Enabled then State.OneClickActive = false return false end State.OneClickActive = false State.Enabled = false State.Panic = false State.Tier = 0 State.RecoveryStartedAt = nil BackgroundMonitor.Refresh() State.ScanGeneration = State.ScanGeneration + 1 State.InitialScanStarted = false State.InitialScanDone = false QueueEngine.Clear() DistanceEngine.Reset() PropertyStore.RestoreAll() Logger.Info("Booster desativado; propriedades ainda sob controle foram restauradas", "SYSTEM") return true end function BoosterController.RestoreAll() if State.Enabled then return BoosterController.Disable() end PropertyStore.RestoreAll() DistanceEngine.Reset() return true end function BoosterController.ToggleAdaptive() State.Adaptive = not State.Adaptive if not State.Adaptive and State.Tier ~= 0 then AdaptiveController.ApplyTier(0, "Adaptativo desligado") end Logger.Info("Adaptativo: " .. tostring(State.Adaptive), "ADAPTIVE") end function BoosterController.ToggleAutomatic() State.Automatic = not State.Automatic if not State.Automatic then State.ScanGeneration = State.ScanGeneration + 1 State.InitialScanStarted = false State.InitialScanDone = false end if State.Enabled then BackgroundMonitor.Refresh() if State.Automatic then BackgroundMonitor.ScanInitial() end end Logger.Info("Atualizacao automatica: " .. tostring(State.Automatic), "SYSTEM") end function BoosterController.PanicNow() if not State.Enabled then return false end AdaptiveController.ApplyTier(4, "Modo de emergencia acionado manualmente") State.RecoveryStartedAt = nil return true end function BoosterController.Shutdown() if State.ShutdownStarted then return end State.ShutdownStarted = true if State.Enabled then BoosterController.Disable() end State.Running = false QueueEngine.Clear() for name, connection in pairs(State.Connections) do if connection then pcall(function() connection:Disconnect() end) end State.Connections[name] = nil end BackgroundMonitor.DisconnectPlayers() end for _, definition in ipairs(OptionDefinitions) do if definition.Supported then definition.ApplyHandler = function(instance) return OptimizerEngine.ApplyInstance(instance) end definition.RestoreHandler = function(instance) return PropertyStore.RestoreInstance(instance) end end end State.UserOverrides = {} function AdaptivePolicy.IsActive(key) local definition = DefinitionByKey[key] if not definition or not definition.Supported then return false end local override = State.UserOverrides[key] if override ~= nil then return override end if Options[key] == true then return true end return State.Enabled and State.Adaptive and definition.RiskLevel ~= "HIGH" and definition.AutoTier ~= nil and State.Tier >= definition.AutoTier end function AdaptivePolicy.Set(key, value) local definition = DefinitionByKey[key] if not definition or not definition.Supported then return false end Options[key] = value == true State.UserOverrides[key] = value == true definition.CurrentValue = Options[key] definition.LastApplied = os.clock() return true end function ProfileManager.Apply(name, confirmed) local profile = ProfileManager.Get(name) if not profile then return false, "Perfil nao encontrado" end local highImpact = false for _, definition in ipairs(OptionDefinitions) do if definition.RiskLevel == "HIGH" and profile[definition.Key] == true then highImpact = true; break end end if highImpact and not confirmed then return false, "CONFIRM_HIGH_IMPACT" end table.clear(State.UserOverrides) for _, definition in ipairs(OptionDefinitions) do if definition.Supported then Options[definition.Key] = profile[definition.Key] == true definition.CurrentValue = Options[definition.Key] end end State.Profile = name table.clear(State.DistanceCulled) if State.Enabled then OptimizerEngine.ApplyGlobal() BoosterController.ApplyTracked() BackgroundMonitor.Refresh() end Logger.Info("Perfil aplicado: " .. name, "PROFILE") return true end local function Initialize() if State.BootstrapStarted then return State.Enabled end State.BootstrapStarted = true local preserve = DefinitionByKey.PreserveLocalAvatar if preserve then preserve.Supported = false preserve.UnsupportedReason = "Protecao fixa: o personagem local nunca e alterado." end local compatibility = DefinitionByKey.CoreCompatibilityMode if compatibility then compatibility.Supported = false compatibility.UnsupportedReason = "pcall e verificacoes sao invariantes de seguranca." end if not LocalPlayer then local deadline = os.clock() + 10 repeat task.wait(0.1) LocalPlayer = Players.LocalPlayer until LocalPlayer or os.clock() >= deadline end if not LocalPlayer then Logger.Error("LocalPlayer indisponivel; bootstrap cancelado", "BOOTSTRAP") warn("[UltraPotato V4 AUTO] ERRO: LocalPlayer indisponivel. Execute depois de entrar completamente no jogo.") return false end State.Running = true State.Automatic = true State.Adaptive = true State.Profile = "ONE-CLICK MAX (AUTO)" State.OneClickActive = true table.clear(State.UserOverrides) local supportedCount = 0 local unsupportedCount = 0 for _, definition in ipairs(OptionDefinitions) do if definition.Supported then if AdaptivePolicy.Set(definition.Key, true) then supportedCount = supportedCount + 1 else unsupportedCount = unsupportedCount + 1 end else unsupportedCount = unsupportedCount + 1 end end if script then pcall(function() if script.Destroying then State.Connections.ScriptDestroying = script.Destroying:Connect(function() BoosterController.Shutdown() end) end end) end warn(string.format( "[UltraPotato V4 AUTO] Iniciando ONE-CLICK MAX | opcoes=%d | ativadas=%d | indisponiveis=%d", #OptionDefinitions, supportedCount, unsupportedCount )) local callOk, enabled = pcall(function() return BoosterController.Enable() end) if not callOk or enabled ~= true then State.OneClickActive = false pcall(function() BoosterController.Disable() end) local reason = callOk and "BoosterController.Enable retornou false" or tostring(enabled) Logger.Error("Falha ao ativar automaticamente: " .. reason, "BOOTSTRAP") warn("[UltraPotato V4 AUTO] FALHA AO ATIVAR: " .. reason) return false end Logger.Warn( string.format("ONE-CLICK MAX automatico ativo: %d opcoes suportadas ativadas", supportedCount), "BOOTSTRAP" ) warn(string.format( "[UltraPotato V4.2 AUTO] ATIVO | opcoes=%d | ativadas=%d | cache IsA=%d/%d", #OptionDefinitions, supportedCount, State.CacheStats.IsAHit, State.CacheStats.IsAMiss )) return true end Initialize()