Universal Script – The Flash (i tried) - Verified script for Universal Roblox
Key RequiredUniversal

Universal Script – The Flash (i tried)

Universal ScriptkillerXkillerX 1K views 4.9K executesUpdated Oct 22, 2026
Unrated
00
Lua Script•3544 lines (125843 chars)
--// THE FLASH (BARRY ALLEN) - POLISHED HUD + COMIC-STYLE LIGHTNING WAKE
--// CONTROLS: HOLD E = ACCELERATE | HOLD Q = BRAKE | WASD = STEER | Z = HUD | F9 = RESET | F10 = CLOSE
--// 400+: straight speed beams plus a long, thin, jagged comic-style lightning wake.
--// Limb (arm/foot) Trails removed. Side/ahead light beams are unchanged.
--// 1,400+: cinematic lighting. 2,000+: pose echoes and phasing. 5,000+: dark gold time-rift corridor.
--// Speed has no configured cap (math.huge); world movement remains subject to Roblox engine limits.
--// Client-side LocalScript. Time-rift and slow-motion are visual illusions only.

local F = {}
local function __BarryAllenStart()
F.Players = game:GetService("Players")
F.UIS = game:GetService("UserInputService")
F.ContextActionService = game:GetService("ContextActionService")
F.RunService = game:GetService("RunService")
F.Lighting = game:GetService("Lighting")
F.TweenService = game:GetService("TweenService")
F.Debris = game:GetService("Debris")
F.SoundService = game:GetService("SoundService")
for _, oldMusic in ipairs(F.SoundService:GetChildren()) do
    if oldMusic.Name == "BarryAllenMyOrdinaryLifeMusic" then
        pcall(function() oldMusic:Stop(); oldMusic:Destroy() end)
    end
end

F.Player = F.Players.LocalPlayer
F.PlayerGui = F.Player:WaitForChild("PlayerGui")
F.Camera = workspace.CurrentCamera
F.CameraBindName = "BarryAllenSpeedForceCamera_" .. tostring(F.Player.UserId)
F.AccelActionName = "BarryAllenHoldAccel_" .. tostring(F.Player.UserId)
F.BrakeActionName = "BarryAllenHoldBrake_" .. tostring(F.Player.UserId)

--==================================================
-- CLEAN UP PREVIOUS RUN
--==================================================

if _G.WallySpeedForceCleanup then
	pcall(_G.WallySpeedForceCleanup)
end

F.Camera = workspace.CurrentCamera
F.OriginalCameraFOV = (F.Camera and F.Camera.FieldOfView) or 70

for _, name in ipairs({
	"WallyWestSpeedForceHUD",
	"BarryAllenSpeedForceHUD",
	"BarryAllenStartupError",
	"WallyCinematicSpeedTunnel",
	"WallyCinematicColorGrade",
	"WallyCinematicBloom",
	"BarryAllenCinematicColorGrade",
	"BarryAllenCinematicBloom",
	"BarryAllenTimeRiftGrade",
	"BarryAllenTimeRiftBloom",
}) do
	local item = F.PlayerGui:FindFirstChild(name) or F.Lighting:FindFirstChild(name)
	if item then
		item:Destroy()
	end
end

for _, folderName in ipairs({"WallyWest_LocalVFX", "BarryAllen_LocalVFX"}) do
	local oldVFX = workspace:FindFirstChild(folderName)
	if oldVFX then oldVFX:Destroy() end
end

local legacyEffectNames = {
    BarryCinematicShockwave = true,
    BarrySonicCondensationFlash = true,
    BarrySonicPressureFront = true,
    BarrySonicMachConeAnchor = true,
    BarrySonicCondensationPuff = true,
    BarrySonicChargeLight = true,
    BarrySonicChargeSparkAttachment = true,
    BarrySonicPressureSparks = true,
    BarrySonicChargeA0 = true,
    BarrySonicChargeA1 = true,
    BarrySpeedHaloArc = true,
}
for _, rootToScan in ipairs({F.Player.Character}) do
    if rootToScan then
        for _, object in ipairs(rootToScan:GetDescendants()) do
            local name = object.Name
            if legacyEffectNames[name]
                or string.match(name, "^BarrySpeedHaloA[01]_")
                or string.match(name, "^BarryTimelineRingA[01]_")
                or string.match(name, "^BarryLimbTrailA[01]_")
                or string.match(name, "^BarryLimbLightTrail_")
                or name == "WallyShockwave" then
                pcall(function() object:Destroy() end)
            end
        end
    end
end

F.Running = true
F.Connections = {}
F.Cleanup = nil
F.Character = nil
F.Humanoid = nil
F.Root = nil

F.Connect = function(signal, callback)
	local connection = signal:Connect(callback)
	table.insert(F.Connections, connection)
	return connection
end

--==================================================
-- COLORS
--==================================================

F.RED = Color3.fromRGB(210, 15, 25)
F.BRIGHT_RED = Color3.fromRGB(255, 40, 50)
F.DARK_RED = Color3.fromRGB(70, 5, 10)
F.YELLOW = Color3.fromRGB(255, 210, 35)
F.GOLD = Color3.fromRGB(255, 145, 15)
F.WHITE = Color3.fromRGB(255, 255, 255)
F.BLACK = Color3.fromRGB(7, 7, 9)
F.DARK = Color3.fromRGB(17, 17, 21)
F.GREY = Color3.fromRGB(135, 135, 145)

--==================================================
-- SPEED SETTINGS
--==================================================

F.Speed = 0
F.MaxSpeed = math.huge
F.Acceleration = 450
F.Deceleration = 800

F.HoldingE = false
F.HoldingQ = false
F.HoldingW = false
F.HoldingA = false
F.HoldingS = false
F.HoldingD = false

F.WasCinematicSpeed = false
F.HUDVisible = true

F.RUN_MUSIC_ASSET_ID = "rbxassetid://1199443456"
F.RUN_MUSIC_TARGET_VOLUME = 0.34
F.RUN_MUSIC_FADE_IN = 1.6
F.RUN_MUSIC_FADE_OUT = 2.2
F.RUN_MUSIC_MIN_SPEED = 20
F.RunMusic = Instance.new("Sound")
F.RunMusic.Name = "BarryAllenMyOrdinaryLifeMusic"
F.RunMusic.SoundId = F.RUN_MUSIC_ASSET_ID
F.RunMusic.Looped = true
F.RunMusic.Volume = 0
F.RunMusic.PlaybackSpeed = 1
F.RunMusic.Parent = F.SoundService
F.RunMusicLastPlayAttempt = 0

F.UpdateRunMusic = function(deltaTime, moving)
    if not F.RunMusic or not F.RunMusic.Parent then return end
    local shouldPlay = moving and F.Speed >= F.RUN_MUSIC_MIN_SPEED
    if shouldPlay then
        if not F.RunMusic.IsPlaying and (os.clock() - F.RunMusicLastPlayAttempt) > 8.0 then
            F.RunMusicLastPlayAttempt = os.clock()
            pcall(function() F.RunMusic:Play() end)
        end
        local blend = 1 - math.exp(-deltaTime * F.RUN_MUSIC_FADE_IN)
        F.RunMusic.Volume = F.RunMusic.Volume + (F.RUN_MUSIC_TARGET_VOLUME - F.RunMusic.Volume) * blend
    else
        F.RunMusic.Volume = math.max(0, F.RunMusic.Volume - deltaTime * F.RUN_MUSIC_FADE_OUT)
        if F.RunMusic.Volume <= 0.008 and F.RunMusic.IsPlaying then
            pcall(function() F.RunMusic:Stop() end)
        end
    end
end

F.SPEED_BEAM_START_SPEED = 400
F.SPEED_BEAM_FULL_DENSITY_SPEED = 12000
F.CINEMATIC_THRESHOLD = 1400
F.REALITY_WARP_THRESHOLD = 2000
F.TIME_RIFT_THRESHOLD = 5000
F.LIGHTNING_REFRESH = 0.045
F.REALITY_WARP_BEAM_COUNT = 56
F.TIME_RIFT_STREAK_COUNT = 18
F.TIME_RIFT_RING_COUNT = 0
F.TIME_RIFT_RING_SEGMENTS = 24

--==================================================
-- WORLD VFX FOLDER
--==================================================

F.VFXFolder = Instance.new("Folder")
F.VFXFolder.Name = "BarryAllen_LocalVFX"
F.VFXFolder.Parent = workspace

--==================================================
-- GUI HELPERS
--==================================================

F.AddCorner = function(parent, radius)
	local corner = Instance.new("UICorner")
	corner.CornerRadius = UDim.new(0, radius)
	corner.Parent = parent
	return corner
end

F.AddStroke = function(parent, color, thickness)
	local stroke = Instance.new("UIStroke")
	stroke.Color = color
	stroke.Thickness = thickness
	stroke.Parent = parent
	return stroke
end

F.MakeLabel = function(parent, name, size, position, text, color, font, textSize, zIndex)
	local label = Instance.new("TextLabel")
	label.Name = name
	label.Size = size
	label.Position = position
	label.BackgroundTransparency = 1
	label.Text = text
	label.TextColor3 = color
	label.Font = font
	label.TextSize = textSize
	label.ZIndex = zIndex or 8
	label.Parent = parent
	return label
end

--==================================================
-- HUD
--==================================================

F.GUI = Instance.new("ScreenGui")
F.GUI.Name = "BarryAllenSpeedForceHUD"
F.GUI.ResetOnSpawn = false
F.GUI.IgnoreGuiInset = false
F.GUI.DisplayOrder = 999999
F.GUI.Parent = F.PlayerGui

F.Shadow = Instance.new("Frame")
F.Shadow.Name = "Shadow"
F.Shadow.Size = UDim2.new(0, 520, 0, 208)
F.Shadow.Position = UDim2.new(0.5, -252, 0.75, 8)
F.Shadow.BackgroundColor3 = Color3.new(0, 0, 0)
F.Shadow.BackgroundTransparency = 0.4
F.Shadow.BorderSizePixel = 0
F.Shadow.ZIndex = 1
F.Shadow.Parent = F.GUI
F.AddCorner(F.Shadow, 18)

F.Main = Instance.new("Frame")
F.Main.Name = "Main"
F.Main.Size = UDim2.new(0, 520, 0, 208)
F.Main.Position = UDim2.new(0.5, -260, 0.75, 0)
F.Main.BackgroundColor3 = F.BLACK
F.Main.BackgroundTransparency = 0.02
F.Main.BorderSizePixel = 0
F.Main.Active = true
F.Main.ZIndex = 2
F.Main.Parent = F.GUI
F.AddCorner(F.Main, 18)
F.MainStroke = F.AddStroke(F.Main, F.RED, 2)
F.MainStroke.Transparency = 0.12

F.MainGradient = Instance.new("UIGradient")
F.MainGradient.Rotation = 12
F.MainGradient.Color = ColorSequence.new({
    ColorSequenceKeypoint.new(0, Color3.fromRGB(16, 10, 14)),
    ColorSequenceKeypoint.new(0.48, Color3.fromRGB(8, 9, 13)),
    ColorSequenceKeypoint.new(1, Color3.fromRGB(18, 10, 12)),
})
F.MainGradient.Parent = F.Main

F.TelemetryPanel = Instance.new("Frame")
F.TelemetryPanel.Name = "TelemetryPanel"
F.TelemetryPanel.Position = UDim2.fromOffset(14, 58)
F.TelemetryPanel.Size = UDim2.fromOffset(296, 119)
F.TelemetryPanel.BackgroundColor3 = Color3.fromRGB(13, 14, 19)
F.TelemetryPanel.BackgroundTransparency = 0.10
F.TelemetryPanel.BorderSizePixel = 0
F.TelemetryPanel.ZIndex = 3
F.TelemetryPanel.Parent = F.Main
F.AddCorner(F.TelemetryPanel, 11)
F.TelemetryPanelStroke = F.AddStroke(F.TelemetryPanel, Color3.fromRGB(95, 28, 31), 1)
F.TelemetryPanelStroke.Transparency = 0.38

F.ControlPanel = Instance.new("Frame")
F.ControlPanel.Name = "ControlPanel"
F.ControlPanel.Position = UDim2.fromOffset(317, 58)
F.ControlPanel.Size = UDim2.fromOffset(191, 119)
F.ControlPanel.BackgroundColor3 = Color3.fromRGB(13, 14, 19)
F.ControlPanel.BackgroundTransparency = 0.08
F.ControlPanel.BorderSizePixel = 0
F.ControlPanel.ZIndex = 3
F.ControlPanel.Parent = F.Main
F.AddCorner(F.ControlPanel, 11)
F.ControlPanelStroke = F.AddStroke(F.ControlPanel, Color3.fromRGB(95, 28, 31), 1)
F.ControlPanelStroke.Transparency = 0.38

F.HeaderDivider = Instance.new("Frame")
F.HeaderDivider.Name = "HeaderDivider"
F.HeaderDivider.Position = UDim2.fromOffset(16, 55)
F.HeaderDivider.Size = UDim2.new(1, -32, 0, 1)
F.HeaderDivider.BackgroundColor3 = Color3.fromRGB(102, 31, 35)
F.HeaderDivider.BackgroundTransparency = 0.18
F.HeaderDivider.BorderSizePixel = 0
F.HeaderDivider.ZIndex = 6
F.HeaderDivider.Parent = F.Main

F.LeftEdgeAccent = Instance.new("Frame")
F.LeftEdgeAccent.Name = "LeftEdgeAccent"
F.LeftEdgeAccent.Position = UDim2.fromOffset(0, 15)
F.LeftEdgeAccent.Size = UDim2.new(0, 3, 1, -30)
F.LeftEdgeAccent.BackgroundColor3 = F.RED
F.LeftEdgeAccent.BorderSizePixel = 0
F.LeftEdgeAccent.ZIndex = 6
F.LeftEdgeAccent.Parent = F.Main
F.AddCorner(F.LeftEdgeAccent, 2)
local edgeGradient = Instance.new("UIGradient")
edgeGradient.Color = ColorSequence.new({
    ColorSequenceKeypoint.new(0, F.RED),
    ColorSequenceKeypoint.new(0.55, F.YELLOW),
    ColorSequenceKeypoint.new(1, F.RED),
})
edgeGradient.Rotation = 90
edgeGradient.Parent = F.LeftEdgeAccent

task.defer(function()
    if not F.Main.Parent then return end
    local camera = workspace.CurrentCamera or F.Camera
    if not camera then return end
    local viewport = camera.ViewportSize
    local x = viewport.X * F.Main.Position.X.Scale + F.Main.Position.X.Offset
    local y = viewport.Y * F.Main.Position.Y.Scale + F.Main.Position.Y.Offset
    x = math.clamp(x, 0, math.max(0, viewport.X - F.Main.AbsoluteSize.X))
    y = math.clamp(y, 0, math.max(0, viewport.Y - F.Main.AbsoluteSize.Y))
    F.Main.Position = UDim2.fromOffset(x, y)
    F.Shadow.Position = UDim2.fromOffset(
        math.clamp(x + 7, 0, math.max(0, viewport.X - F.Shadow.AbsoluteSize.X)),
        math.clamp(y + 8, 0, math.max(0, viewport.Y - F.Shadow.AbsoluteSize.Y))
    )
end)

F.TopLine = Instance.new("Frame")
F.TopLine.Name = "TopAccent"
F.TopLine.Size = UDim2.new(1, 0, 0, 5)
F.TopLine.BackgroundColor3 = F.RED
F.TopLine.BorderSizePixel = 0
F.TopLine.ZIndex = 5
F.TopLine.Parent = F.Main
F.AddCorner(F.TopLine, 18)

F.TopGradient = Instance.new("UIGradient")
F.TopGradient.Color = ColorSequence.new({
	ColorSequenceKeypoint.new(0, F.RED),
	ColorSequenceKeypoint.new(0.3, F.BRIGHT_RED),
	ColorSequenceKeypoint.new(0.55, F.YELLOW),
	ColorSequenceKeypoint.new(0.7, F.WHITE),
	ColorSequenceKeypoint.new(1, F.RED),
})
F.TopGradient.Parent = F.TopLine

F.Header = Instance.new("Frame")
F.Header.Name = "DragHeader"
F.Header.Size = UDim2.new(1, -18, 0, 43)
F.Header.Position = UDim2.new(0, 9, 0, 10)
F.Header.BackgroundTransparency = 1
F.Header.Active = true
F.Header.ZIndex = 7
F.Header.Parent = F.Main

F.MakeLabel(F.Header, "Logo", UDim2.new(0, 42, 0, 42), UDim2.new(0, 0, 0, 0), "ϟ", F.YELLOW, Enum.Font.GothamBlack, 34, 8)
F.Title = F.MakeLabel(F.Header, "Title", UDim2.new(0, 300, 0, 22), UDim2.new(0, 45, 0, 1), "THE FLASH  /  SPEED FORCE", F.WHITE, Enum.Font.GothamBlack, 18, 8)
F.Title.TextXAlignment = Enum.TextXAlignment.Left
F.Subtitle = F.MakeLabel(F.Header, "Subtitle", UDim2.new(0, 286, 0, 16), UDim2.new(0, 46, 0, 23), "BARRY ALLEN  •  VELOCITY INTERFACE", F.GREY, Enum.Font.Code, 9, 8)
F.Subtitle.TextXAlignment = Enum.TextXAlignment.Left

F.Status = Instance.new("TextLabel")
F.Status.Name = "Status"
F.Status.Size = UDim2.new(0, 91, 0, 25)
F.Status.Position = UDim2.new(1, -165, 0, 6)
F.Status.BackgroundColor3 = F.DARK_RED
F.Status.Text = "STANDBY"
F.Status.TextColor3 = F.GREY
F.Status.Font = Enum.Font.GothamBold
F.Status.TextSize = 9
F.Status.BorderSizePixel = 0
F.Status.ZIndex = 10
F.Status.Parent = F.Main
F.AddCorner(F.Status, 8)
F.AddStroke(F.Status, F.RED, 1)

F.HideButton = Instance.new("TextButton")
F.HideButton.Name = "HideButton"
F.HideButton.Size = UDim2.new(0, 52, 0, 25)
F.HideButton.Position = UDim2.new(1, -108, 0, 6)
F.HideButton.BackgroundColor3 = F.DARK
F.HideButton.Text = "HIDE"
F.HideButton.TextColor3 = F.YELLOW
F.HideButton.Font = Enum.Font.GothamBold
F.HideButton.TextSize = 8
F.HideButton.BorderSizePixel = 0
F.HideButton.ZIndex = 15
F.HideButton.Parent = F.Main
F.AddCorner(F.HideButton, 8)
F.AddStroke(F.HideButton, F.YELLOW, 1)

F.CloseButton = Instance.new("TextButton")
F.CloseButton.Name = "CloseButton"
F.CloseButton.Size = UDim2.new(0, 28, 0, 28)
F.CloseButton.Position = UDim2.new(1, -34, 0, 4)
F.CloseButton.BackgroundColor3 = Color3.fromRGB(38, 7, 10)
F.CloseButton.Text = "×"
F.CloseButton.TextColor3 = F.BRIGHT_RED
F.CloseButton.Font = Enum.Font.GothamBold
F.CloseButton.TextSize = 20
F.CloseButton.BorderSizePixel = 0
F.CloseButton.ZIndex = 20
F.CloseButton.Active = true
F.CloseButton.Selectable = true
F.CloseButton.AutoButtonColor = true
F.CloseButton.Parent = F.Main
F.AddCorner(F.CloseButton, 8)
F.AddStroke(F.CloseButton, F.RED, 1.2)

F.Connect(F.CloseButton.Activated, function()
    if F.Cleanup then
        pcall(F.Cleanup)
    else
        F.Running = false
        for _, connection in ipairs(F.Connections) do
            pcall(function() connection:Disconnect() end)
        end
        table.clear(F.Connections)
        pcall(function() F.RunService:UnbindFromRenderStep(F.CameraBindName) end)
        if F.VFXFolder and F.VFXFolder.Parent then pcall(function() F.VFXFolder:Destroy() end) end
        if F.GUI and F.GUI.Parent then pcall(function() F.GUI:Destroy() end) end
    end
end)

F.TelemetryTag = F.MakeLabel(F.Main, "TelemetryTag", UDim2.fromOffset(180, 12), UDim2.fromOffset(25, 61), "LIVE VELOCITY / STUDS PER SECOND", F.GREY, Enum.Font.Code, 8, 8)
F.TelemetryTag.TextXAlignment = Enum.TextXAlignment.Left
F.ControlTag = F.MakeLabel(F.Main, "ControlTag", UDim2.fromOffset(170, 13), UDim2.fromOffset(329, 63), "MANUAL OVERRIDE", F.YELLOW, Enum.Font.Code, 9, 8)
F.ControlTag.TextXAlignment = Enum.TextXAlignment.Left
F.ControlHint = F.MakeLabel(F.Main, "ControlHint", UDim2.fromOffset(168, 14), UDim2.fromOffset(329, 135), "HOLD KEY TO ADJUST SPEED", F.GREY, Enum.Font.Code, 7, 8)
F.ControlHint.TextXAlignment = Enum.TextXAlignment.Left

F.SpeedNumber = F.MakeLabel(F.Main, "SpeedNumber", UDim2.new(0, 255, 0, 45), UDim2.new(0, 22, 0, 73), "0", F.GREY, Enum.Font.GothamBlack, 42, 8)
F.SpeedNumber.TextXAlignment = Enum.TextXAlignment.Left
F.SpeedStroke = F.AddStroke(F.SpeedNumber, F.RED, 1)
F.SpeedStroke.Transparency = 0.45

F.Units = F.MakeLabel(F.Main, "Units", UDim2.new(0, 190, 0, 15), UDim2.new(0, 25, 0, 119), "VELOCITY UNIT: STUDS/SEC", F.GREY, Enum.Font.Code, 10, 8)
F.Units.TextXAlignment = Enum.TextXAlignment.Left

F.VelocityLabel = F.MakeLabel(F.Main, "VelocityLabel", UDim2.new(0, 130, 0, 13), UDim2.new(0, 25, 0, 140), "VELOCITY LOAD", F.YELLOW, Enum.Font.Code, 9, 8)
F.VelocityLabel.TextXAlignment = Enum.TextXAlignment.Left

F.BarBack = Instance.new("Frame")
F.BarBack.Name = "BarBack"
F.BarBack.Size = UDim2.new(0, 278, 0, 9)
F.BarBack.Position = UDim2.new(0, 25, 0, 157)
F.BarBack.BackgroundColor3 = Color3.fromRGB(35, 19, 22)
F.BarBack.BorderSizePixel = 0
F.BarBack.ZIndex = 7
F.BarBack.Parent = F.Main
F.AddCorner(F.BarBack, 5)

F.BarGlow = Instance.new("Frame")
F.BarGlow.Name = "BarGlow"
F.BarGlow.Size = UDim2.new(0, 0, 1, 0)
F.BarGlow.BackgroundColor3 = F.RED
F.BarGlow.BackgroundTransparency = 0.55
F.BarGlow.BorderSizePixel = 0
F.BarGlow.ZIndex = 6
F.BarGlow.Parent = F.BarBack
F.AddCorner(F.BarGlow, 5)

F.Fill = Instance.new("Frame")
F.Fill.Name = "Fill"
F.Fill.Size = UDim2.new(0, 0, 1, 0)
F.Fill.BackgroundColor3 = F.RED
F.Fill.BorderSizePixel = 0
F.Fill.ZIndex = 8
F.Fill.Parent = F.BarBack
F.AddCorner(F.Fill, 5)

F.FillGradient = Instance.new("UIGradient")
F.FillGradient.Color = ColorSequence.new({
	ColorSequenceKeypoint.new(0, F.RED),
	ColorSequenceKeypoint.new(0.35, F.BRIGHT_RED),
	ColorSequenceKeypoint.new(0.72, F.YELLOW),
	ColorSequenceKeypoint.new(1, F.WHITE),
})
F.FillGradient.Parent = F.Fill

F.CreateKeyButton = function(letter, label, position, color)
	local button = Instance.new("TextButton")
	button.Name = letter .. "Button"
	button.Size = UDim2.new(0, 82, 0, 42)
	button.Position = position
	button.BackgroundColor3 = F.DARK
	button.Text = ""
	button.BorderSizePixel = 0
	button.ZIndex = 10
	button.Parent = F.Main
	F.AddCorner(button, 10)
	local stroke = F.AddStroke(button, color, 1.2)

	F.MakeLabel(button, "Key", UDim2.new(0, 27, 1, 0), UDim2.new(0, 7, 0, 0), letter, color, Enum.Font.GothamBlack, 20, 11)
	F.MakeLabel(button, "Action", UDim2.new(0, 46, 1, 0), UDim2.new(0, 38, 0, 0), label, F.WHITE, Enum.Font.Code, 8, 11)
	return button, stroke
end

F.EButton, F.EStroke = F.CreateKeyButton("E", "ACCEL", UDim2.new(1, -190, 0, 83), F.YELLOW)
F.QButton, F.QStroke = F.CreateKeyButton("Q", "BRAKE", UDim2.new(1, -98, 0, 83), F.BRIGHT_RED)

F.MobileHoldingE = false
F.MobileHoldingQ = false
F.ActiveEButtonInput = nil
F.ActiveQButtonInput = nil

F.IsHoldPointer = function(input)
    return input.UserInputType == Enum.UserInputType.MouseButton1
        or input.UserInputType == Enum.UserInputType.Touch
end

F.Connect(F.EButton.InputBegan, function(input)
    if F.IsHoldPointer(input) then
        F.ActiveEButtonInput = input
        F.MobileHoldingE = true
        F.EStroke.Thickness = 2.8
    end
end)

F.Connect(F.QButton.InputBegan, function(input)
    if F.IsHoldPointer(input) then
        F.ActiveQButtonInput = input
        F.MobileHoldingQ = true
        F.QStroke.Thickness = 2.8
    end
end)

F.Connect(F.EButton.InputEnded, function(input)
    if F.IsHoldPointer(input) then
        F.MobileHoldingE = false
        F.ActiveEButtonInput = nil
        F.EStroke.Thickness = 1.2
    end
end)
F.Connect(F.QButton.InputEnded, function(input)
    if F.IsHoldPointer(input) then
        F.MobileHoldingQ = false
        F.ActiveQButtonInput = nil
        F.QStroke.Thickness = 1.2
    end
end)

F.Footer = F.MakeLabel(F.Main, "Footer", UDim2.new(0, 472, 0, 16), UDim2.new(0, 25, 1, -22), "W A S D  STEER     HOLD E  ACCELERATE     HOLD Q  BRAKE     F10  CLOSE     SPEED  ∞", F.GREY, Enum.Font.Code, 8, 8)
F.Footer.TextXAlignment = Enum.TextXAlignment.Left
F.Footer.TextSize = 7
F.Footer.TextTransparency = 0.08

--==================================================
-- DRAGGABLE HUD
--==================================================

F.Dragging = false
F.DragStart = nil
F.StartPos = nil
F.DragInput = nil

F.Connect(F.Header.InputBegan, function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1
		or input.UserInputType == Enum.UserInputType.Touch then
		F.Dragging = true
		F.DragStart = input.Position
		F.StartPos = F.Main.Position
	end
end)

F.Connect(F.UIS.InputEnded, function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1
		or input.UserInputType == Enum.UserInputType.Touch then
		F.Dragging = false
	end
end)

F.Connect(F.Header.InputChanged, function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement
		or input.UserInputType == Enum.UserInputType.Touch then
		F.DragInput = input
	end
end)

F.Connect(F.UIS.InputChanged, function(input)
	if F.Dragging and input == F.DragInput then
		local delta = input.Position - F.DragStart
		local newPosition = UDim2.new(
			F.StartPos.X.Scale,
			F.StartPos.X.Offset + delta.X,
			F.StartPos.Y.Scale,
			F.StartPos.Y.Offset + delta.Y
		)

        local camera = workspace.CurrentCamera or F.Camera
        local viewport = camera and camera.ViewportSize or Vector2.new(1280, 720)
        local pixelX = viewport.X * newPosition.X.Scale + newPosition.X.Offset
        local pixelY = viewport.Y * newPosition.Y.Scale + newPosition.Y.Offset
        local maxX = math.max(0, viewport.X - F.Main.AbsoluteSize.X)
        local maxY = math.max(0, viewport.Y - F.Main.AbsoluteSize.Y)
        pixelX = math.clamp(pixelX, 0, maxX)
        pixelY = math.clamp(pixelY, 0, maxY)
        newPosition = UDim2.fromOffset(pixelX, pixelY)

		F.Main.Position = newPosition
		F.Shadow.Position = UDim2.fromOffset(
            math.clamp(pixelX + 7, 0, maxX),
            math.clamp(pixelY + 8, 0, maxY)
        )
	end
end)

F.SetHUDVisible = function(visible)
	F.HUDVisible = visible
	for _, object in ipairs({
		F.SpeedNumber, F.Units, F.VelocityLabel, F.BarBack,
		F.EButton, F.QButton, F.Footer, F.TelemetryPanel, F.ControlPanel,
        F.TelemetryTag, F.ControlTag, F.ControlHint,
	}) do
		object.Visible = visible
	end

	if visible then
		F.Main.Size = UDim2.new(0, 520, 0, 208)
		F.Shadow.Size = UDim2.new(0, 520, 0, 208)
		F.HideButton.Text = "HIDE"
	else
		F.Main.Size = UDim2.new(0, 520, 0, 65)
		F.Shadow.Size = UDim2.new(0, 520, 0, 65)
		F.HideButton.Text = "OPEN"
	end
end

F.Connect(F.HideButton.MouseButton1Click, function()
	F.SetHUDVisible(not F.HUDVisible)
end)

--==================================================
-- CINEMATIC COLOR / BLOOM
--==================================================

F.CinematicGrade = Instance.new("ColorCorrectionEffect")
F.CinematicGrade.Name = "BarryAllenCinematicColorGrade"
F.CinematicGrade.Enabled = false
F.CinematicGrade.Brightness = 0
F.CinematicGrade.Contrast = 0
F.CinematicGrade.Saturation = 0
F.CinematicGrade.TintColor = F.WHITE
F.CinematicGrade.Parent = F.Lighting

F.CinematicBloom = Instance.new("BloomEffect")
F.CinematicBloom.Name = "BarryAllenCinematicBloom"
F.CinematicBloom.Enabled = false
F.CinematicBloom.Intensity = 0.12
F.CinematicBloom.Size = 22
F.CinematicBloom.Threshold = 1.55
F.CinematicBloom.Parent = F.Lighting

--==================================================
-- TIME RIFT POST-PROCESSING
--==================================================

F.TimeRiftGrade = Instance.new("ColorCorrectionEffect")
F.TimeRiftGrade.Name = "BarryAllenTimeRiftGrade"
F.TimeRiftGrade.Enabled = false
F.TimeRiftGrade.Brightness = 0
F.TimeRiftGrade.Contrast = 0
F.TimeRiftGrade.Saturation = 0
F.TimeRiftGrade.TintColor = F.WHITE
F.TimeRiftGrade.Parent = F.Lighting

F.TimeRiftBloom = Instance.new("BloomEffect")
F.TimeRiftBloom.Name = "BarryAllenTimeRiftBloom"
F.TimeRiftBloom.Enabled = false
F.TimeRiftBloom.Intensity = 0.35
F.TimeRiftBloom.Size = 42
F.TimeRiftBloom.Threshold = 0.9
F.TimeRiftBloom.Parent = F.Lighting

--==================================================
-- CHARACTER VFX REFERENCES
--==================================================

F.CinematicHighlight = nil
F.CinematicLight = nil
F.CinematicSpark = nil
F.CinematicSparkAttachment = nil
F.CinematicBeams = {}
F.CinematicArcs = {}
F.CinematicWakeBolts = {}
F.CinematicAttachments = {}
F.CinematicWakeTrails = {}
F.CinematicLimbTrails = {} -- kept empty; limb trails were removed
F.CinematicBlurStreaks = {}

-- CURVED TRAIL: the wake and blur are laid along a "spine" that bends when you steer.
-- Each spine segment uses the heading from a little further in the past, so turning
-- makes the whole trail sweep around in an arc instead of snapping stiffly.
F.TRAIL_SEGMENTS = 22          -- spine segments (22 x 4 = 88 studs of curve)
F.TRAIL_SEGMENT_LENGTH = 4
F.TRAIL_CURVE_LAG = 0.35       -- seconds of steering history across the trail (bigger = longer, lazier curves)
F.TRAIL_TURN_RATE = 7          -- how fast the trail heading follows your steering (smaller = rounder turns)
F.TrailHeading = nil
F.TrailHistory = {}
F.TrailSpine = {}
F.TrailHeadings = {}
F.CinematicGroundHaze = nil
F.CinematicGroundAttachment = nil

F.RealityWarpBeams = {}
F.RealityWarpAttachments = {}
F.RealityWarpDistance = 0
F.RealityWarpActiveBeamCount = 0
F.RealityWarpSpawnCredit = 0
F.RealityWarpQualityScale = 1
F.RealityWarpQualityTimer = 0
F.RealityWarpQualityFrameTotal = 0
F.RealityWarpQualityFrameSamples = 0

F.TimeRiftBeams = {}
F.TimeRiftRingBeams = {}
F.TimeRiftAttachments = {}
F.TimeRiftDistance = 0
F.TimeRiftRotation = 0

F.BodyRootMotor = nil
F.BodyPartBaseline = {}
F.LastBodyOffset = 0
F.LastBodyBaseTransform = nil
F.LastBodyAppliedTransform = nil
F.BodyWasPhasing = false

F.WorldSlowMotionTracks = {}
F.WorldSlowMotionTimer = 0
F.WORLD_SLOW_RADIUS = 350
F.WORLD_SLOW_THRESHOLD = 2000

F.IsVisualObject = function(object)
	return object:IsA("SpecialMesh")
		or object:IsA("SurfaceAppearance")
		or object:IsA("Decal")
		or object:IsA("Texture")
end

F.RemoveNonVisualChildren = function(part)
	for _, child in ipairs(part:GetDescendants()) do
		if not F.IsVisualObject(child) then
			pcall(function() child:Destroy() end)
		end
	end
end

--==================================================
-- NORMAL SPEED LIGHT
--==================================================

F.SetupTrail = function(char)
	local torso = char:FindFirstChild("UpperTorso")
		or char:FindFirstChild("Torso")
		or char:FindFirstChild("HumanoidRootPart")
	if not torso then return end

	for _, object in ipairs(char:GetDescendants()) do
		if object:IsA("Trail") and (string.match(object.Name, "^WallyTrail")
			or string.match(object.Name, "^WallyCinematic")
			or string.match(object.Name, "^WallyLeftArmStreak")
			or string.match(object.Name, "^WallyRightArmStreak")
			or string.match(object.Name, "^WallyLeftFootStreak")
			or string.match(object.Name, "^WallyRightFootStreak")
			or string.match(object.Name, "^BarryLimbLightTrail_")) then
			object:Destroy()
		elseif string.match(object.Name, "^WallyTrail") or object.Name == "WallySpeedLight" then
			object:Destroy()
		end
	end

	local light = Instance.new("PointLight")
	light.Name = "WallySpeedLight"
	light.Color = F.YELLOW
	light.Range = 13
	light.Brightness = 0
	light.Shadows = false
	light.Parent = torso
end

--==================================================
-- SMOKE WAKE
--==================================================

F.SetupSmoke = function(char)
	local root = char:FindFirstChild("HumanoidRootPart")
	if not root then return end

	local old = root:FindFirstChild("WallySmokeWake")
	if old then old:Destroy() end

	local attachment = Instance.new("Attachment")
	attachment.Name = "WallySmokeWake"
	attachment.Position = Vector3.new(0, -2.5, 1.8)
	attachment.Parent = root

	local dust = Instance.new("ParticleEmitter")
	dust.Name = "Dust"
	dust.Texture = "rbxasset://textures/particles/smoke_main.dds"
	dust.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, Color3.fromRGB(235, 235, 235)),
		ColorSequenceKeypoint.new(0.45, Color3.fromRGB(180, 180, 180)),
		ColorSequenceKeypoint.new(1, Color3.fromRGB(105, 105, 105)),
	})
	dust.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 2),
		NumberSequenceKeypoint.new(0.35, 4.5),
		NumberSequenceKeypoint.new(0.75, 7),
		NumberSequenceKeypoint.new(1, 11),
	})
	dust.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.16),
		NumberSequenceKeypoint.new(0.4, 0.33),
		NumberSequenceKeypoint.new(1, 1),
	})
	dust.Lifetime = NumberRange.new(0.5, 0.95)
	dust.Speed = NumberRange.new(4, 11)
	dust.SpreadAngle = Vector2.new(38, 38)
	dust.Rotation = NumberRange.new(-180, 180)
	dust.RotSpeed = NumberRange.new(-70, 70)
	dust.Drag = 5
	dust.Rate = 0
	dust.Parent = attachment

	local fastDust = Instance.new("ParticleEmitter")
	fastDust.Name = "FastDust"
	fastDust.Texture = "rbxasset://textures/particles/smoke_main.dds"
	fastDust.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, F.WHITE),
		ColorSequenceKeypoint.new(0.35, F.YELLOW),
		ColorSequenceKeypoint.new(1, F.GOLD),
	})
	fastDust.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.7),
		NumberSequenceKeypoint.new(0.45, 2),
		NumberSequenceKeypoint.new(1, 4),
	})
	fastDust.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.3),
		NumberSequenceKeypoint.new(1, 1),
	})
	fastDust.Lifetime = NumberRange.new(0.18, 0.38)
	fastDust.Speed = NumberRange.new(15, 32)
	fastDust.SpreadAngle = Vector2.new(18, 18)
	fastDust.Drag = 4
	fastDust.LightEmission = 0.6
	fastDust.Rate = 0
	fastDust.Parent = attachment

	local energy = Instance.new("ParticleEmitter")
	energy.Name = "EnergyDust"
	energy.Texture = "rbxasset://textures/particles/smoke_main.dds"
	energy.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, F.YELLOW),
		ColorSequenceKeypoint.new(0.5, F.GOLD),
		ColorSequenceKeypoint.new(1, F.RED),
	})
	energy.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.5),
		NumberSequenceKeypoint.new(0.5, 2),
		NumberSequenceKeypoint.new(1, 4.5),
	})
	energy.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.35),
		NumberSequenceKeypoint.new(1, 1),
	})
	energy.Lifetime = NumberRange.new(0.18, 0.4)
	energy.Speed = NumberRange.new(8, 20)
	energy.SpreadAngle = Vector2.new(35, 35)
	energy.Drag = 5
	energy.LightEmission = 0.8
	energy.Rate = 0
	energy.Parent = attachment
end

--==================================================
-- BODY ENERGY PARTICLES
--==================================================

F.SetupEnergy = function(char)
	local torso = char:FindFirstChild("UpperTorso")
		or char:FindFirstChild("Torso")
		or char:FindFirstChild("HumanoidRootPart")
	if not torso then return end

	local old = torso:FindFirstChild("WallyEnergyAttachment")
	if old then old:Destroy() end

	local attachment = Instance.new("Attachment")
	attachment.Name = "WallyEnergyAttachment"
	attachment.Parent = torso

	local particle = Instance.new("ParticleEmitter")
	particle.Name = "WallyEnergy"
	particle.Texture = "rbxassetid://7335682855"
	particle.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, F.WHITE),
		ColorSequenceKeypoint.new(0.35, F.YELLOW),
		ColorSequenceKeypoint.new(1, F.GOLD),
	})
	particle.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 1.5),
		NumberSequenceKeypoint.new(1, 0),
	})
	particle.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.25),
		NumberSequenceKeypoint.new(1, 1),
	})
	particle.Lifetime = NumberRange.new(0.12, 0.28)
	particle.Speed = NumberRange.new(0, 3)
	particle.Rotation = NumberRange.new(-360, 360)
	particle.Rate = 0
	particle.LightEmission = 1
	particle.Parent = attachment
end

--==================================================
-- CINEMATIC CHARACTER SETUP: BODY GLOW + LIGHTNING
--==================================================

F.DestroyCinematicCharacterEffects = function()
	for _, trail in ipairs(F.CinematicWakeTrails) do
		pcall(function() trail:Destroy() end)
	end
	table.clear(F.CinematicWakeTrails)
	for _, entry in ipairs(F.CinematicLimbTrails) do
		local trail = entry.Trail or entry
		if trail then pcall(function() trail:Destroy() end) end
	end
	table.clear(F.CinematicLimbTrails)

	for _, beam in ipairs(F.CinematicBeams) do
		pcall(function() beam:Destroy() end)
	end
	table.clear(F.CinematicBeams)
    for _, bolt in ipairs(F.CinematicWakeBolts) do
        for _, beam in ipairs(bolt.Beams or {}) do
            pcall(function() beam:Destroy() end)
        end
    end
    table.clear(F.CinematicWakeBolts)
	table.clear(F.CinematicArcs)
	table.clear(F.CinematicBlurStreaks)
	F.CinematicGroundHaze = nil
	F.CinematicGroundAttachment = nil

	for _, attachment in ipairs(F.CinematicAttachments) do
		pcall(function() attachment:Destroy() end)
	end
	table.clear(F.CinematicAttachments)

	if F.CinematicHighlight then
		F.CinematicHighlight:Destroy()
		F.CinematicHighlight = nil
	end
	if F.CinematicLight then
		F.CinematicLight:Destroy()
		F.CinematicLight = nil
	end
	if F.CinematicSparkAttachment then
		F.CinematicSparkAttachment:Destroy()
		F.CinematicSparkAttachment = nil
		F.CinematicSpark = nil
	end
end

F.SetupCinematicCharacter = function(char)
	F.DestroyCinematicCharacterEffects()

	local torso = char:FindFirstChild("UpperTorso")
		or char:FindFirstChild("Torso")
		or char:FindFirstChild("HumanoidRootPart")
	local root = char:FindFirstChild("HumanoidRootPart")
	if not torso or not root then return end

	local function getPart(name)
		local part = char:FindFirstChild(name)
		if part and part:IsA("BasePart") then return part end
		return nil
	end

	F.CinematicHighlight = Instance.new("Highlight")
	F.CinematicHighlight.Name = "WallyCinematicHighlight"
	F.CinematicHighlight.Adornee = char
	F.CinematicHighlight.FillColor = F.GOLD
	F.CinematicHighlight.OutlineColor = F.YELLOW
	F.CinematicHighlight.FillTransparency = 0.7
	F.CinematicHighlight.OutlineTransparency = 0.2
	F.CinematicHighlight.DepthMode = Enum.HighlightDepthMode.Occluded
	F.CinematicHighlight.Enabled = false
	F.CinematicHighlight.Parent = F.VFXFolder

	F.CinematicLight = Instance.new("PointLight")
	F.CinematicLight.Name = "WallyCinematicLight"
	F.CinematicLight.Color = Color3.fromRGB(255, 135, 40)
	F.CinematicLight.Brightness = 0
	F.CinematicLight.Range = 25
	F.CinematicLight.Shadows = false
	F.CinematicLight.Parent = torso

	F.CinematicSparkAttachment = Instance.new("Attachment")
	F.CinematicSparkAttachment.Name = "WallyCinematicSparkAttach"
	F.CinematicSparkAttachment.Position = Vector3.new(0, -0.35, 1.0)
	F.CinematicSparkAttachment.Parent = root

	F.CinematicSpark = Instance.new("ParticleEmitter")
	F.CinematicSpark.Name = "WallyCinematicSpark"
	F.CinematicSpark.Texture = "rbxasset://textures/particles/sparkles_main.dds"
	F.CinematicSpark.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, F.WHITE),
		ColorSequenceKeypoint.new(0.35, F.YELLOW),
		ColorSequenceKeypoint.new(1, F.GOLD),
	})
	F.CinematicSpark.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.42),
		NumberSequenceKeypoint.new(0.45, 0.26),
		NumberSequenceKeypoint.new(1, 0),
	})
	F.CinematicSpark.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.1),
		NumberSequenceKeypoint.new(1, 1),
	})
	F.CinematicSpark.Lifetime = NumberRange.new(0.14, 0.26)
	F.CinematicSpark.Speed = NumberRange.new(7, 16)
	F.CinematicSpark.SpreadAngle = Vector2.new(22, 22)
	F.CinematicSpark.EmissionDirection = Enum.NormalId.Front
	F.CinematicSpark.Orientation = Enum.ParticleOrientation.VelocityParallel
	F.CinematicSpark.LightEmission = 1
	F.CinematicSpark.Rate = 0
	F.CinematicSpark.Parent = F.CinematicSparkAttachment

	-- COMIC-STYLE WAKE: long, thin, jagged gold lightning that fans out behind Barry.
	-- No limb Trails are created; this Beam wake is the only trailing geometry.
	local WAKE_POINTS = 8
	local WAKE_LENGTH = 62
	local function pickPart(names)
		for _, n in ipairs(names) do
			local candidate = getPart(n)
			if candidate then return candidate end
		end
		return torso
	end
	local anchorParts = {
		head  = pickPart({"Head"}),
		chest = pickPart({"UpperTorso", "Torso"}),
		waist = pickPart({"LowerTorso", "Torso"}),
		lhand = pickPart({"LeftHand", "Left Arm"}),
		rhand = pickPart({"RightHand", "Right Arm"}),
		lknee = pickPart({"LeftLowerLeg", "Left Leg"}),
		rknee = pickPart({"RightLowerLeg", "Right Leg"}),
		lfoot = pickPart({"LeftFoot", "Left Leg"}),
		rfoot = pickPart({"RightFoot", "Right Leg"}),
	}
	-- {name, startX, startY, spread, lengthScale, anchor}
	local wakeBoltDefinitions = {
		{"Core",   0.00,  0.10, 1.00, 1.00, "chest"},
		{"UpperL", -0.30, 0.45, 1.15, 0.90, "chest"},
		{"UpperR",  0.30, 0.40, 1.15, 0.90, "chest"},
		{"HeadA",   0.00, 0.25, 1.30, 0.90, "head"},
		{"HeadB",  -0.15,-0.20, 1.50, 0.75, "head"},
		{"Waist",   0.00, 0.00, 1.30, 0.85, "waist"},
		{"KneeL",  -0.10, 0.00, 1.40, 0.75, "lknee"},
		{"KneeR",   0.10, 0.00, 1.40, 0.75, "rknee"},
		{"LowerL", -0.15, 0.00, 1.20, 0.85, "lfoot"},
		{"LowerR",  0.15, 0.00, 1.20, 0.85, "rfoot"},
		{"WideL",  -0.20, 0.00, 1.90, 0.65, "lhand"},
		{"WideR",   0.20, 0.00, 1.90, 0.65, "rhand"},
	}
	for boltIndex, def in ipairs(wakeBoltDefinitions) do
		local attachments, basePoints, beams = {}, {}, {}
		for p = 1, WAKE_POINTS do
			local t = (p - 1) / (WAKE_POINTS - 1)
			local point = Vector3.new(def[2], def[3], math.pow(t, 1.2) * WAKE_LENGTH * def[5])
			local attachment = Instance.new("Attachment")
			attachment.Name = "BarryWakeBolt_" .. def[1] .. "_A" .. p
			attachment.Position = point
			attachment.Parent = root
			table.insert(F.CinematicAttachments, attachment)
			table.insert(attachments, attachment)
			table.insert(basePoints, point)
		end
		for s = 1, WAKE_POINTS - 1 do
			local t = (s - 1) / (WAKE_POINTS - 1)
			local beam = Instance.new("Beam")
			beam.Name = "BarryJaggedWakeLightning"
			beam.Attachment0 = attachments[s]
			beam.Attachment1 = attachments[s + 1]
			beam.Color = ColorSequence.new({
				ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 244, 190)),
				ColorSequenceKeypoint.new(0.5, Color3.fromRGB(255, 220, 90)),
				ColorSequenceKeypoint.new(1, F.GOLD),
			})
			beam.Transparency = NumberSequence.new(math.clamp(0.08 + t * 0.6, 0, 0.9))
			beam.Width0 = 0.05
			beam.Width1 = 0.03
			beam.Segments = 1
			beam.FaceCamera = true
			beam.LightEmission = 0.85
			beam.LightInfluence = 0
			beam.Enabled = false
			beam.Parent = F.VFXFolder
			table.insert(beams, beam)
		end
		table.insert(F.CinematicWakeBolts, {
			Name = def[1], Attachments = attachments, BasePoints = basePoints, Beams = beams,
			Spread = def[4], Phase = math.random() * math.pi * 2, LastRefresh = 0, Index = boltIndex,
			Anchor = anchorParts[def[6]] or torso, Jitter = {},
		})
	end

	-- RED/ORANGE MOTION BLUR: soft, wide, low-opacity bands built from several short
	-- segments so they can bend with the curved trail. They start on the torso/feet/hands.
	local function lerpStops(stops, t, lerpFn)
		for i = 1, #stops - 1 do
			local lo, hi = stops[i], stops[i + 1]
			if t <= hi[1] then
				return lerpFn(lo[2], hi[2], (t - lo[1]) / (hi[1] - lo[1]))
			end
		end
		return stops[#stops][2]
	end
	local blurColorStops = {
		{0, Color3.fromRGB(255, 160, 40)},
		{0.35, Color3.fromRGB(255, 100, 25)},
		{0.75, Color3.fromRGB(220, 40, 20)},
		{1, Color3.fromRGB(140, 15, 15)},
	}
	local blurAlphaStops = {{0, 0.55}, {0.35, 0.74}, {0.75, 0.92}, {1, 1}}
	local function blurColorAt(t)
		return lerpStops(blurColorStops, t, function(x, y, f) return x:Lerp(y, f) end)
	end
	local function blurAlphaAt(t)
		return lerpStops(blurAlphaStops, t, function(x, y, f) return x + (y - x) * f end)
	end

	local BLUR_SEGMENTS = 4
	local blurDefinitions = {
		-- {name, anchor, x, y, width, length}: several thin streaks of different lengths
		{"HeadA",  "head",  0.00,  0.30, 0.55, 46},
		{"HeadB",  "head",  0.00, -0.25, 0.45, 64},
		{"ChestA", "chest", 0.00,  0.55, 0.70, 60},
		{"ChestB", "chest", 0.00, -0.45, 0.80, 44},
		{"WaistA", "waist", 0.00,  0.20, 0.75, 66},
		{"WaistB", "waist", 0.00, -0.40, 0.55, 40},
		{"HandL",  "lhand", 0.00,  0.00, 0.50, 42},
		{"HandR",  "rhand", 0.00,  0.00, 0.50, 42},
		{"KneeL",  "lknee", 0.00,  0.00, 0.50, 46},
		{"KneeR",  "rknee", 0.00,  0.00, 0.50, 46},
		{"FootL",  "lfoot", 0.00,  0.10, 0.55, 52},
		{"FootR",  "rfoot", 0.00,  0.10, 0.55, 52},
		{"GroundL", "lfoot", -0.20, -0.70, 1.10, 56},
		{"GroundR", "rfoot",  0.20, -0.70, 1.10, 56},
	}
	for _, def in ipairs(blurDefinitions) do
		local attachments, beams = {}, {}
		for seg = 0, BLUR_SEGMENTS do
			local attachment = Instance.new("Attachment")
			attachment.Name = "BarryBlurA" .. seg .. "_" .. def[1]
			attachment.Parent = root
			table.insert(F.CinematicAttachments, attachment)
			table.insert(attachments, attachment)
		end
		for seg = 1, BLUR_SEGMENTS do
			local t0, t1 = (seg - 1) / BLUR_SEGMENTS, seg / BLUR_SEGMENTS
			local beam = Instance.new("Beam")
			beam.Name = "BarrySpeedBlur"
			beam.Attachment0 = attachments[seg]
			beam.Attachment1 = attachments[seg + 1]
			beam.Color = ColorSequence.new({
				ColorSequenceKeypoint.new(0, blurColorAt(t0)),
				ColorSequenceKeypoint.new(1, blurColorAt(t1)),
			})
			beam.Transparency = NumberSequence.new({
				NumberSequenceKeypoint.new(0, blurAlphaAt(t0)),
				NumberSequenceKeypoint.new(1, blurAlphaAt(t1)),
			})
			beam.Width0 = def[5]
			beam.Width1 = def[5]
			beam.Segments = 1
			beam.FaceCamera = true
			beam.LightEmission = 0.35
			beam.LightInfluence = 0
			beam.Enabled = false
			beam.Parent = F.VFXFolder
			table.insert(F.CinematicBeams, beam)
			table.insert(beams, beam)
		end
		table.insert(F.CinematicBlurStreaks, {
			Beams = beams, Attachments = attachments, Anchor = anchorParts[def[2]] or torso,
			X = def[3], Y = def[4], Width = def[5], Length = def[6],
			Phase = math.random() * math.pi * 2,
		})
	end

	-- Small, warm haze at foot level.
	local groundAttachment = Instance.new("Attachment")
	groundAttachment.Name = "WallyCinematicGroundHazeAttach"
	groundAttachment.Position = Vector3.new(0, -2.0, 1.2)
	groundAttachment.Parent = root
	F.CinematicGroundAttachment = groundAttachment
	table.insert(F.CinematicAttachments, groundAttachment)

	F.CinematicGroundHaze = Instance.new("ParticleEmitter")
	F.CinematicGroundHaze.Name = "WallyCinematicGroundHaze"
	F.CinematicGroundHaze.Texture = "rbxasset://textures/particles/smoke_main.dds"
	F.CinematicGroundHaze.Color = ColorSequence.new({
		ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 245, 190)),
		ColorSequenceKeypoint.new(0.28, F.YELLOW),
		ColorSequenceKeypoint.new(0.7, F.GOLD),
		ColorSequenceKeypoint.new(1, F.BRIGHT_RED),
	})
	F.CinematicGroundHaze.Size = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 1.25),
		NumberSequenceKeypoint.new(0.38, 3.6),
		NumberSequenceKeypoint.new(1, 6.5),
	})
	F.CinematicGroundHaze.Transparency = NumberSequence.new({
		NumberSequenceKeypoint.new(0, 0.38),
		NumberSequenceKeypoint.new(0.35, 0.58),
		NumberSequenceKeypoint.new(1, 1),
	})
	F.CinematicGroundHaze.Lifetime = NumberRange.new(0.22, 0.4)
	F.CinematicGroundHaze.Speed = NumberRange.new(4, 11)
	F.CinematicGroundHaze.SpreadAngle = Vector2.new(12, 12)
	F.CinematicGroundHaze.EmissionDirection = Enum.NormalId.Front
	F.CinematicGroundHaze.Drag = 5
	F.CinematicGroundHaze.LightEmission = 1
	F.CinematicGroundHaze.Rate = 0
	F.CinematicGroundHaze.Parent = groundAttachment

	-- Body lightning: angular three-segment bolts between neighboring joints.
	local function addArc(part0, pos0, part1, pos1, arcName)
		if not part0 or not part1 then return end

		local endpointA = Instance.new("Attachment")
		endpointA.Name = "BarryBoltStart_" .. arcName
		endpointA.Position = pos0
		endpointA.Parent = part0
		table.insert(F.CinematicAttachments, endpointA)

		local endpointB = Instance.new("Attachment")
		endpointB.Name = "BarryBoltEnd_" .. arcName
		endpointB.Position = pos1
		endpointB.Parent = part1
		table.insert(F.CinematicAttachments, endpointB)

		local bendA = Instance.new("Attachment")
		bendA.Name = "BarryBoltBendA_" .. arcName
		bendA.Parent = root
		table.insert(F.CinematicAttachments, bendA)

		local bendB = Instance.new("Attachment")
		bendB.Name = "BarryBoltBendB_" .. arcName
		bendB.Parent = root
		table.insert(F.CinematicAttachments, bendB)

		local segmentPairs = {
			{endpointA, bendA},
			{bendA, bendB},
			{bendB, endpointB},
		}
		local segments = {}

		for index, pair in ipairs(segmentPairs) do
			local beam = Instance.new("Beam")
			beam.Name = "BarrySpeedForceLightning"
			beam.Attachment0 = pair[1]
			beam.Attachment1 = pair[2]
			beam.Color = ColorSequence.new({
				ColorSequenceKeypoint.new(0, F.WHITE),
				ColorSequenceKeypoint.new(0.35, Color3.fromRGB(255, 250, 210)),
				ColorSequenceKeypoint.new(0.72, F.YELLOW),
				ColorSequenceKeypoint.new(1, F.GOLD),
			})
			beam.Transparency = NumberSequence.new({
				NumberSequenceKeypoint.new(0, 0.04),
				NumberSequenceKeypoint.new(1, 0.18),
			})
			beam.Width0 = index == 2 and 0.075 or 0.065
			beam.Width1 = 0.025
			beam.Segments = 1
			beam.FaceCamera = true
			beam.LightEmission = 1
			beam.LightInfluence = 0
			beam.Enabled = false
			beam.Parent = F.VFXFolder
			table.insert(F.CinematicBeams, beam)
			table.insert(segments, beam)
		end

		table.insert(F.CinematicArcs, {
			Name = arcName,
			A = endpointA,
			B = endpointB,
			BendA = bendA,
			BendB = bendB,
			Segments = segments,
			Phase = math.random() * math.pi * 2,
			LastRefresh = 0,
		})
	end

	local upperTorso = getPart("UpperTorso")
	local lowerTorso = getPart("LowerTorso")
	local torsoPart = getPart("Torso")
	local head = getPart("Head")

	if upperTorso and lowerTorso then
		addArc(upperTorso, Vector3.new(0, -upperTorso.Size.Y * 0.43, 0),
			lowerTorso, Vector3.new(0, lowerTorso.Size.Y * 0.43, 0), "Spine")
	end
	if head and upperTorso then
		addArc(head, Vector3.new(0, -head.Size.Y * 0.42, 0),
			upperTorso, Vector3.new(0, upperTorso.Size.Y * 0.43, 0), "Neck")
	end

	local limbLinks = {
		{"LeftUpperArm", "LeftLowerArm", "LArm"},
		{"RightUpperArm", "RightLowerArm", "RArm"},
		{"LeftUpperLeg", "LeftLowerLeg", "LLeg"},
		{"RightUpperLeg", "RightLowerLeg", "RLeg"},
		{"LeftLowerLeg", "LeftFoot", "LFoot"},
		{"RightLowerLeg", "RightFoot", "RFoot"},
	}

	for _, link in ipairs(limbLinks) do
		local upper = getPart(link[1])
		local lower = getPart(link[2])
		if upper and lower then
			addArc(
				upper,
				Vector3.new(0, -upper.Size.Y * 0.42, 0),
				lower,
				Vector3.new(0, lower.Size.Y * 0.42, 0),
				link[3]
			)
		end
	end

	if torsoPart then
		for _, side in ipairs({
			{Sign = -1, Arm = "Left Arm", Leg = "Left Leg", Tag = "L"},
			{Sign = 1, Arm = "Right Arm", Leg = "Right Leg", Tag = "R"},
		}) do
			local arm = getPart(side.Arm)
			if arm then
				addArc(torsoPart,
					Vector3.new(side.Sign * torsoPart.Size.X * 0.46, torsoPart.Size.Y * 0.28, 0),
					arm, Vector3.new(0, arm.Size.Y * 0.43, 0), side.Tag .. "Arm")
			end
			local leg = getPart(side.Leg)
			if leg then
				addArc(torsoPart,
					Vector3.new(side.Sign * torsoPart.Size.X * 0.22, -torsoPart.Size.Y * 0.47, 0),
					leg, Vector3.new(0, leg.Size.Y * 0.43, 0), side.Tag .. "Leg")
			end
		end
	end
end

--==================================================
-- ADAPTIVE SPEED BEAMS: 400+ SPEED (UNCHANGED)
--==================================================

F.ClearRealityWarpBeams = function()
    for _, entry in ipairs(F.RealityWarpBeams) do
        if entry.Beam then
            pcall(function() entry.Beam:Destroy() end)
        end
    end
    table.clear(F.RealityWarpBeams)

    for _, attachment in ipairs(F.RealityWarpAttachments) do
        if attachment then
            pcall(function() attachment:Destroy() end)
        end
    end
    table.clear(F.RealityWarpAttachments)

    F.RealityWarpDistance = 0
    F.RealityWarpActiveBeamCount = 0
    F.RealityWarpSpawnCredit = 0
    F.RealityWarpQualityTimer = 0
    F.RealityWarpQualityFrameTotal = 0
    F.RealityWarpQualityFrameSamples = 0
    F.RealityWarpQualityScale = 1
end

F.GetSpeedBeamProgress = function()
    if F.Speed < F.SPEED_BEAM_START_SPEED then
        return 0
    end

    if F.Speed == math.huge or F.Speed >= F.SPEED_BEAM_FULL_DENSITY_SPEED then
        return 1
    end

    local normalized = math.log(F.Speed / F.SPEED_BEAM_START_SPEED)
        / math.log(F.SPEED_BEAM_FULL_DENSITY_SPEED / F.SPEED_BEAM_START_SPEED)

    return math.clamp(normalized, 0, 1)
end

F.GetTargetSpeedBeamCount = function(progress)
    local minimumCount = 4
    local visibleCeiling = math.floor(F.REALITY_WARP_BEAM_COUNT * 0.75)
    local scaled = math.pow(math.clamp(progress, 0, 1), 1.35)
    local desired = minimumCount
        + math.floor(scaled * (visibleCeiling - minimumCount))

    if F.RealityWarpQualityScale < 0.999 then
        desired = math.max(minimumCount, math.floor(desired * F.RealityWarpQualityScale))
    end

    return math.clamp(desired, minimumCount, math.floor(F.REALITY_WARP_BEAM_COUNT * 0.75))
end

F.SetupRealityWarpBeams = function(char)
    F.ClearRealityWarpBeams()

    local root = char and char:FindFirstChild("HumanoidRootPart")
    if not root then
        return
    end

    local goldenAngle = math.pi * (3 - math.sqrt(5))

    for i = 1, F.REALITY_WARP_BEAM_COUNT do
        local a0 = Instance.new("Attachment")
        a0.Name = "BarryRealityWarpA" .. i
        a0.Parent = root
        table.insert(F.RealityWarpAttachments, a0)

        local a1 = Instance.new("Attachment")
        a1.Name = "BarryRealityWarpB" .. i
        a1.Parent = root
        table.insert(F.RealityWarpAttachments, a1)

        local beam = Instance.new("Beam")
        beam.Name = "BarryRealityWarpLightBeam"
        beam.Attachment0 = a0
        beam.Attachment1 = a1
        beam.Segments = 1
        beam.FaceCamera = true
        beam.LightEmission = 1
        beam.LightInfluence = 0
        beam.Width0 = 0.028
        beam.Width1 = 0.008
        beam.Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 0.36),
            NumberSequenceKeypoint.new(0.12, 0.13),
            NumberSequenceKeypoint.new(0.76, 0.24),
            NumberSequenceKeypoint.new(1, 1),
        })
        beam.Enabled = false
        beam.Parent = F.VFXFolder

        local isWhiteHot = (i % 9 == 0) or (i % 17 == 0)
        local isAmber = (i % 4 == 0)
        local baseWidth
        local radius
        local length
        local layer

        local lane = ((i - 1) % 12) + 1
        if lane <= 4 then
            layer = 1
            radius = math.random(42, 82) / 10
            length = math.random(125, 255) / 10
            baseWidth = math.random(22, 36) / 1000
        elseif lane <= 9 then
            layer = 2
            radius = math.random(100, 205) / 10
            length = math.random(220, 450) / 10
            baseWidth = math.random(27, 43) / 1000
        else
            layer = 3
            radius = math.random(200, 365) / 10
            length = math.random(320, 650) / 10
            baseWidth = math.random(30, 48) / 1000
        end

        if isWhiteHot then
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, F.WHITE),
                ColorSequenceKeypoint.new(0.24, Color3.fromRGB(255, 252, 235)),
                ColorSequenceKeypoint.new(0.67, F.YELLOW),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 176, 56)),
            })
            beam.Transparency = NumberSequence.new({
                NumberSequenceKeypoint.new(0, 0.22),
                NumberSequenceKeypoint.new(0.1, 0.035),
                NumberSequenceKeypoint.new(0.78, 0.12),
                NumberSequenceKeypoint.new(1, 1),
            })
        elseif isAmber then
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, F.YELLOW),
                ColorSequenceKeypoint.new(0.52, F.GOLD),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 102, 28)),
            })
            beam.Transparency = NumberSequence.new({
                NumberSequenceKeypoint.new(0, 0.44),
                NumberSequenceKeypoint.new(0.14, 0.16),
                NumberSequenceKeypoint.new(0.74, 0.31),
                NumberSequenceKeypoint.new(1, 1),
            })
        else
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 247, 211)),
                ColorSequenceKeypoint.new(0.28, F.YELLOW),
                ColorSequenceKeypoint.new(0.72, F.GOLD),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 135, 35)),
            })
        end

        local angle = (i - 1) * goldenAngle
            + (math.random() - 0.5) * 0.24
        local phase = ((i - 1) / F.REALITY_WARP_BEAM_COUNT) * 260
            + math.random() * 9
        local drift = (math.random() - 0.5) * 0.66
        local pulsePhase = math.random() * math.pi * 2
        local pulseRate = math.random(78, 125) / 100
        local flow = math.random(78, 128) / 100
        local verticalBias = (math.random() - 0.5) * 0.55

        table.insert(F.RealityWarpBeams, {
            Beam = beam,
            A0 = a0,
            A1 = a1,
            Angle = angle,
            Radius = radius,
            Phase = phase,
            Length = length,
            Drift = drift,
            Index = i,
            Layer = layer,
            BaseWidth = baseWidth,
            IsWhiteHot = isWhiteHot,
            IsAmber = isAmber,
            Ahead = (lane == 3 or lane == 8 or lane == 11),
            SideLane = (lane == 1 or lane == 4 or lane == 7 or lane == 10),
            SideSign = (i % 2 == 0) and -1 or 1,
            PulsePhase = pulsePhase,
            PulseRate = pulseRate,
            Flow = flow,
            VerticalBias = verticalBias,
        })
    end
end

F.UpdateRealityWarpBeams = function(deltaTime, isMoving)
    local active = F.Speed >= F.SPEED_BEAM_START_SPEED
        and isMoving
        and F.Root ~= nil
        and F.Root.Parent ~= nil

    if not active then
        for _, entry in ipairs(F.RealityWarpBeams) do
            if entry.Beam and entry.Beam.Enabled then
                entry.Beam.Enabled = false
            end
        end
        F.RealityWarpActiveBeamCount = 0
        F.RealityWarpSpawnCredit = 0
        return
    end

    local progress = F.GetSpeedBeamProgress()
    local targetCount = F.GetTargetSpeedBeamCount(progress)
    if F.Speed >= F.TIME_RIFT_THRESHOLD then
        local riftIntensity
        if F.Speed == math.huge then
            riftIntensity = 1
        else
            local ratio = math.max(F.Speed / F.TIME_RIFT_THRESHOLD, 1)
            riftIntensity = 0.04 + math.clamp(math.log(ratio) / math.log(50), 0, 1) * 0.96
        end
        local handoff = 0.12 + 0.24 * riftIntensity
        targetCount = math.max(28, math.floor(targetCount * (1 - handoff)))
    end
    local clock = os.clock()
    local sideAxis, upAxis, travelAxis = F.GetBeamBasisLocal()

    if F.RealityWarpActiveBeamCount < 1 then
        F.RealityWarpActiveBeamCount = 1
    end

    if F.RealityWarpActiveBeamCount < targetCount then
        local spawnRate = 9 + math.pow(progress, 0.82) * 65
        F.RealityWarpSpawnCredit += deltaTime * spawnRate

        local ready = math.floor(F.RealityWarpSpawnCredit)
        local addCount = math.min(ready, targetCount - math.floor(F.RealityWarpActiveBeamCount), 6)
        if addCount > 0 then
            F.RealityWarpActiveBeamCount += addCount
            F.RealityWarpSpawnCredit -= addCount
        end
    elseif F.RealityWarpActiveBeamCount > targetCount then
        F.RealityWarpActiveBeamCount = math.max(
            targetCount,
            F.RealityWarpActiveBeamCount - deltaTime * 84
        )
        F.RealityWarpSpawnCredit = 0
    else
        F.RealityWarpSpawnCredit = math.min(F.RealityWarpSpawnCredit, 0.99)
    end

    local activeCount = math.clamp(
        math.floor(F.RealityWarpActiveBeamCount),
        1,
        F.REALITY_WARP_BEAM_COUNT
    )

    local intensity = math.pow(progress, 0.92)

    local flowRate = 140 + math.pow(progress, 0.88) * 1280
    if F.Speed >= F.TIME_RIFT_THRESHOLD then
        local riftProgress
        if F.Speed == math.huge then
            riftProgress = 1
        else
            riftProgress = math.clamp(
                math.log(math.max(F.Speed / F.TIME_RIFT_THRESHOLD, 1)) / math.log(50),
                0,
                1
            )
        end
        local riftIntensity = 0.04 + riftProgress * 0.96
        flowRate = 920 - riftIntensity * 460
    end

    F.RealityWarpDistance = (F.RealityWarpDistance + flowRate * deltaTime) % 260

    local pulseFrequency = 2.5 + intensity * 3.5
    local flickerCutoff = 0.005 + intensity * 0.025

    for _, entry in ipairs(F.RealityWarpBeams) do
        local beam = entry.Beam
        local spawned = entry.Index <= activeCount

        if not spawned then
            beam.Enabled = false
        elseif entry.A0.Parent and entry.A1.Parent then
            local phaseDistance = (entry.Phase + F.RealityWarpDistance * entry.Flow) % 260
            local z
            if entry.Ahead then
                local leadPhase = (entry.Phase + F.RealityWarpDistance * entry.Flow * 0.76) % 235
                z = -255 + leadPhase
            else
                z = 3.25 + phaseDistance
            end
            local pulse = 0.5 + 0.5 * math.sin(
                clock * pulseFrequency * entry.PulseRate + entry.PulsePhase
            )
            local flutter = math.sin(
                clock * (0.9 + intensity * 1.6) + entry.PulsePhase * 1.31
            )

            local angle = entry.Angle + flutter * (0.018 + intensity * 0.055)
            local radialGrowth = 1 + intensity * (entry.Layer == 1 and 0.22 or 0.52)
            local radius = entry.Radius * radialGrowth

            local lengthMultiplier = 0.58 + intensity * 1.22
            if entry.Layer == 1 then
                lengthMultiplier *= 0.84 + intensity * 0.18
            elseif entry.Layer == 3 then
                lengthMultiplier *= 1.10 + intensity * 0.25
            end
            local streakLength = entry.Length * lengthMultiplier

            local p0, p1
            local x0, y0
            if entry.SideLane then
                local sideLimit = entry.Layer == 1 and 8.0
                    or (entry.Layer == 2 and 20 or 34)
                local sideMinimum = entry.Layer == 1 and 3.7 or 6.2
                local sideOffset = math.clamp(entry.Radius * 0.74, sideMinimum, sideLimit)
                local sideWobble = math.sin(clock * (0.45 + entry.Flow * 0.18) + entry.PulsePhase)
                    * (0.35 + intensity * 0.85)
                x0 = entry.SideSign * (sideOffset + sideWobble)
                y0 = math.sin(angle) * math.min(radius * 0.28, 8)
                    + entry.VerticalBias * (1 + intensity * 2)
            else
                x0 = math.cos(angle) * radius
                y0 = math.sin(angle) * radius + entry.VerticalBias * (1 + intensity * 3)
            end

            local endZ
            if entry.Ahead then
                endZ = math.min(z + streakLength, -2.8)
            else
                endZ = z + streakLength
            end

            p0 = sideAxis * x0 + upAxis * y0 + travelAxis * z
            p1 = sideAxis * x0 + upAxis * y0 + travelAxis * endZ

            entry.A0.Position = p0
            entry.A1.Position = p1

            beam.Enabled = pulse > flickerCutoff or progress < 0.04

            local widthPulse = 0.76 + pulse * 0.42
            local distanceScale = (entry.Layer == 1) and 1.0
                or ((entry.Layer == 2) and 0.82 or 0.68)
            beam.Width0 = entry.BaseWidth
                * (0.72 + intensity * 1.72)
                * widthPulse * distanceScale
            beam.Width1 = math.max(0.006, beam.Width0 * (0.18 + intensity * 0.07))

            beam.LightEmission = 0.78 + pulse * 0.22
        end
    end
end

F.UpdateRealityWarpQuality = function(frameDeltaTime)
    F.RealityWarpQualityTimer += frameDeltaTime
    F.RealityWarpQualityFrameTotal += frameDeltaTime
    F.RealityWarpQualityFrameSamples += 1

    if F.RealityWarpQualityTimer >= 0.75 then
        local averageFrameTime = F.RealityWarpQualityFrameTotal
            / math.max(F.RealityWarpQualityFrameSamples, 1)

        if averageFrameTime > 0.028 then
            F.RealityWarpQualityScale = math.max(0.68, F.RealityWarpQualityScale - 0.08)
        elseif averageFrameTime < 0.019 then
            F.RealityWarpQualityScale = math.min(1, F.RealityWarpQualityScale + 0.04)
        end

        F.RealityWarpQualityTimer = 0
        F.RealityWarpQualityFrameTotal = 0
        F.RealityWarpQualityFrameSamples = 0
    end
end

--==================================================
-- TIME RIFT (UNCHANGED)
--==================================================

F.ClearTimeRiftEffects = function()
    for _, entry in ipairs(F.TimeRiftBeams) do
        if entry.Beam then pcall(function() entry.Beam:Destroy() end) end
    end
    for _, entry in ipairs(F.TimeRiftRingBeams) do
        if entry.Beam then pcall(function() entry.Beam:Destroy() end) end
    end
    for _, attachment in ipairs(F.TimeRiftAttachments) do
        if attachment then pcall(function() attachment:Destroy() end) end
    end
    table.clear(F.TimeRiftBeams)
    table.clear(F.TimeRiftRingBeams)
    table.clear(F.TimeRiftAttachments)
    F.TimeRiftDistance = 0
    F.TimeRiftRotation = 0
end

F.GetTimeRiftIntensity = function()
    if F.Speed < F.TIME_RIFT_THRESHOLD then return 0 end
    if F.Speed == math.huge then return 1 end
    local ratio = math.max(F.Speed / F.TIME_RIFT_THRESHOLD, 1)
    local progress = math.clamp(math.log(ratio) / math.log(50), 0, 1)
    return 0.04 + progress * 0.96
end

F.SetupTimeRiftEffects = function(char)
    F.ClearTimeRiftEffects()
    local root = char and char:FindFirstChild("HumanoidRootPart")
    if not root then return end

    for i = 1, F.TIME_RIFT_STREAK_COUNT do
        local a0 = Instance.new("Attachment")
        a0.Name = "BarryTimeRiftStreakA0_" .. i
        a0.Parent = root
        table.insert(F.TimeRiftAttachments, a0)

        local a1 = Instance.new("Attachment")
        a1.Name = "BarryTimeRiftStreakA1_" .. i
        a1.Parent = root
        table.insert(F.TimeRiftAttachments, a1)

        local beam = Instance.new("Beam")
        beam.Name = "BarryTimeRiftGoldLightStreak"
        beam.Attachment0 = a0
        beam.Attachment1 = a1
        beam.Segments = 1
        beam.FaceCamera = true
        beam.LightEmission = 1
        beam.LightInfluence = 0
        beam.Width0 = 0.038
        beam.Width1 = 0.009
        beam.Transparency = NumberSequence.new(0.14)
        beam.Enabled = false
        beam.Parent = F.VFXFolder

        if i % 7 == 0 then
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, F.WHITE),
                ColorSequenceKeypoint.new(0.38, Color3.fromRGB(255, 250, 226)),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 190, 80)),
            })
        elseif i % 4 == 0 then
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 246, 205)),
                ColorSequenceKeypoint.new(0.52, F.YELLOW),
                ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 116, 28)),
            })
        else
            beam.Color = ColorSequence.new({
                ColorSequenceKeypoint.new(0, F.WHITE),
                ColorSequenceKeypoint.new(0.42, Color3.fromRGB(255, 225, 132)),
                ColorSequenceKeypoint.new(1, F.GOLD),
            })
        end

        table.insert(F.TimeRiftBeams, {
            Beam = beam,
            A0 = a0,
            A1 = a1,
            Index = i,
            Angle = (i / F.TIME_RIFT_STREAK_COUNT) * math.pi * 2 + (math.random() - 0.5) * 0.2,
            InnerRadius = math.random(42, 78) / 10,
            Radius = math.random(100, 340) / 10,
            Phase = math.random() * 330,
            Length = math.random(260, 880) / 10,
            Drift = (math.random() - 0.5) * 1.5,
            Flow = math.random(82, 122) / 100,
            Ahead = (i % 4 == 3),
            SideLane = (i % 4 == 1 or i % 4 == 2),
            SideSign = (i % 2 == 0) and -1 or 1,
            Pulse = math.random() * math.pi * 2,
        })
    end

    local planes = {
        CFrame.new(),
        CFrame.Angles(math.rad(76), math.rad(22), math.rad(14)),
        CFrame.Angles(math.rad(27), math.rad(-38), math.rad(48)),
    }
    local radii = {3.6, 5.7, 8.1}

    for ringIndex = 1, F.TIME_RIFT_RING_COUNT do
        for segment = 1, F.TIME_RIFT_RING_SEGMENTS do
            local a0 = Instance.new("Attachment")
            a0.Name = "BarryTimelineRingA0_" .. ringIndex .. "_" .. segment
            a0.Parent = root
            table.insert(F.TimeRiftAttachments, a0)

            local a1 = Instance.new("Attachment")
            a1.Name = "BarryTimelineRingA1_" .. ringIndex .. "_" .. segment
            a1.Parent = root
            table.insert(F.TimeRiftAttachments, a1)

            local beam = Instance.new("Beam")
            beam.Name = "BarryTimelineGoldFracture"
            beam.Attachment0 = a0
            beam.Attachment1 = a1
            beam.Segments = 2
            beam.FaceCamera = true
            beam.LightEmission = 1
            beam.LightInfluence = 0
            beam.Width0 = (ringIndex == 1 and 0.13) or (ringIndex == 2 and 0.095) or 0.075
            beam.Width1 = 0.028
            beam.Transparency = NumberSequence.new(0.16)
            beam.Enabled = false
            beam.Parent = F.VFXFolder

            if ringIndex == 1 then
                beam.Color = ColorSequence.new({
                    ColorSequenceKeypoint.new(0, F.WHITE),
                    ColorSequenceKeypoint.new(0.52, F.YELLOW),
                    ColorSequenceKeypoint.new(1, F.GOLD),
                })
            else
                beam.Color = ColorSequence.new({
                    ColorSequenceKeypoint.new(0, F.GOLD),
                    ColorSequenceKeypoint.new(0.5, Color3.fromRGB(255, 235, 170)),
                    ColorSequenceKeypoint.new(1, F.WHITE),
                })
            end

            table.insert(F.TimeRiftRingBeams, {
                Beam = beam,
                A0 = a0,
                A1 = a1,
                Ring = ringIndex,
                Segment = segment,
                Segments = F.TIME_RIFT_RING_SEGMENTS,
                Plane = planes[ringIndex],
                BaseRadius = radii[ringIndex],
                Phase = ringIndex * 0.37,
            })
        end
    end
end

F.UpdateTimeRiftEffects = function(deltaTime, isMoving)
    local active = F.Speed >= F.TIME_RIFT_THRESHOLD and F.Root and F.Root.Parent
    local intensity = F.GetTimeRiftIntensity()
    local sideAxis, upAxis, travelAxis = F.GetBeamBasisLocal()

    F.TimeRiftGrade.Enabled = active and true or false
    F.TimeRiftBloom.Enabled = active and true or false

    if not active then
        for _, entry in ipairs(F.TimeRiftBeams) do
            if entry.Beam then entry.Beam.Enabled = false end
        end
        for _, entry in ipairs(F.TimeRiftRingBeams) do
            if entry.Beam then entry.Beam.Enabled = false end
        end
        return
    end

    F.TimeRiftGrade.Brightness = -0.015 - intensity * 0.285
    F.TimeRiftGrade.Contrast = 0.08 + intensity * 0.62
    F.TimeRiftGrade.Saturation = 0.03 - intensity * 0.78
    F.TimeRiftGrade.TintColor = F.WHITE:Lerp(Color3.fromRGB(255, 211, 158), intensity * 0.38)

    F.TimeRiftBloom.Intensity = 0.22 + intensity * 1.08
    F.TimeRiftBloom.Size = 26 + intensity * 38
    F.TimeRiftBloom.Threshold = 1.28 - intensity * 0.58

    local flowRate = 900 - intensity * 440
    if isMoving then
        F.TimeRiftDistance = F.TimeRiftDistance + flowRate * deltaTime
        if F.TimeRiftDistance > 1e12 then F.TimeRiftDistance = F.TimeRiftDistance % 330 end
    end
    local ringSpinRate = isMoving and (0.42 + intensity * 1.35) or 0.10
    F.TimeRiftRotation = F.TimeRiftRotation - deltaTime * ringSpinRate

    local qualityLimit = math.max(6, math.floor(F.TIME_RIFT_STREAK_COUNT * F.RealityWarpQualityScale))
    local startingCount = math.min(6, qualityLimit)
    local activeCount = math.clamp(
        startingCount + math.floor(intensity * (qualityLimit - startingCount)),
        startingCount,
        qualityLimit
    )

    for _, entry in ipairs(F.TimeRiftBeams) do
        local beam = entry.Beam
        local enabled = isMoving and entry.Index <= activeCount
        beam.Enabled = enabled

        if enabled and entry.A0.Parent and entry.A1.Parent then
            local phaseDistance = entry.Phase + F.TimeRiftDistance * entry.Flow
            local z
            if entry.Ahead then
                z = -280 + (phaseDistance % 255)
            else
                z = 3.25 + (phaseDistance % 330)
            end
            local pulse = math.sin(os.clock() * (1.6 + intensity * 2.4) + entry.Pulse)
            local angle = entry.Angle + math.sin(os.clock() * (1.1 + intensity * 1.5) + entry.Index) * (0.025 + intensity * 0.07)
            local innerRadius = entry.InnerRadius + pulse * (0.08 + intensity * 0.22)
            local streakLength = entry.Length * (0.68 + intensity * 0.72)

            local p0, p1
            local x0, y0
            if entry.SideLane then
                local sideOffset = math.clamp(entry.Radius * 0.70, 4.0, 29)
                local sideWobble = math.sin(os.clock() * (0.38 + entry.Flow * 0.14) + entry.Pulse)
                    * (0.25 + intensity * 0.65)
                x0 = entry.SideSign * (sideOffset + sideWobble)
                y0 = math.sin(angle) * math.min(entry.Radius * 0.22, 10)
            else
                x0 = math.cos(angle) * innerRadius
                y0 = math.sin(angle) * innerRadius
            end

            local endZ = entry.Ahead and math.min(z + streakLength, -2.8) or (z + streakLength)
            p0 = sideAxis * x0 + upAxis * y0 + travelAxis * z
            p1 = sideAxis * x0 + upAxis * y0 + travelAxis * endZ

            entry.A0.Position = p0
            entry.A1.Position = p1

            beam.Width0 = 0.032 + intensity * 0.048
            beam.Width1 = 0.007 + intensity * 0.017
            beam.Transparency = NumberSequence.new(0.16 - intensity * 0.095)
        end
    end

    for _, entry in ipairs(F.TimeRiftRingBeams) do
        local beam = entry.Beam
        beam.Enabled = true
        local spinSign = (entry.Ring % 2 == 0) and 1 or -1
        local spin = F.TimeRiftRotation * spinSign + entry.Phase
        local pulse = 1 + math.sin(os.clock() * (1.8 + intensity * 0.55) + entry.Ring * 1.7) * (0.008 + intensity * 0.014)
        local radius = entry.BaseRadius * pulse * (1 + intensity * 0.12)
        local fullStep = math.pi * 2 / entry.Segments
        local a0 = ((entry.Segment - 1) / entry.Segments) * math.pi * 2 + spin
        local a1 = a0 + fullStep * 0.97
        local p0 = entry.Plane:VectorToWorldSpace(Vector3.new(math.cos(a0) * radius, math.sin(a0) * radius, 0))
        local p1 = entry.Plane:VectorToWorldSpace(Vector3.new(math.cos(a1) * radius, math.sin(a1) * radius, 0))
        entry.A0.Position = p0
        entry.A1.Position = p1
        local ringCore = (entry.Ring == 1 and 0.085) or (entry.Ring == 2 and 0.068) or 0.052
        local ringBoost = (entry.Ring == 1 and 0.115) or (entry.Ring == 2 and 0.092) or 0.075
        local segmentPulse = 0.88 + 0.12 * math.max(0, math.sin(os.clock() * (2.1 + intensity * 1.2) + entry.Segment * 0.16 + entry.Phase))
        beam.Transparency = NumberSequence.new(0.12 + (1 - segmentPulse) * 0.20 - intensity * 0.055)
        beam.Width0 = (ringCore + intensity * ringBoost) * pulse * segmentPulse
        beam.Width1 = 0.010 + intensity * 0.045 * segmentPulse
        beam.LightEmission = 0.9 + segmentPulse * 0.1
    end
end

--==================================================
-- POSE AFTERIMAGE SYSTEM
--==================================================

F.Echoes = {}
F.PoseHistory = {}
F.SourceParts = {}
F.SourceIndex = {}
F.MAX_ECHOES = 2
F.HISTORY_SIZE = 8

F.ClearEchoes = function()
	for _, echo in ipairs(F.Echoes) do
		if echo.Model then
			pcall(function() echo.Model:Destroy() end)
		end
	end
	table.clear(F.Echoes)
	table.clear(F.PoseHistory)
end

F.RefreshSourceParts = function()
	table.clear(F.SourceParts)
	table.clear(F.SourceIndex)

	if not F.Character then return end
	for _, object in ipairs(F.Character:GetDescendants()) do
		if object:IsA("BasePart")
			and object.Name ~= "HumanoidRootPart"
			and object.Transparency < 1 then
			table.insert(F.SourceParts, object)
			F.SourceIndex[object] = #F.SourceParts
		end
	end
end

F.BuildEcho = function(char)
	local echoModel = Instance.new("Model")
	echoModel.Name = "WallyRealityEcho"
	echoModel.Parent = F.VFXFolder

	local echoParts = {}
	for _, original in ipairs(F.SourceParts) do
		local clone
		local ok = pcall(function()
			clone = original:Clone()
		end)

		if ok and clone and clone:IsA("BasePart") then
			F.RemoveNonVisualChildren(clone)
			clone.Anchored = true
			clone.CanCollide = false
			clone.CanTouch = false
			clone.CanQuery = false
			clone.CastShadow = false
			clone.Massless = true
			clone.Transparency = 1
			clone.Parent = echoModel

			table.insert(echoParts, {
				Original = original,
				Clone = clone,
				SourceIndex = F.SourceIndex[original],
				BaseColor = clone.Color,
				BaseTransparency = original.Transparency,
			})
		end
	end

	local highlight = Instance.new("Highlight")
	highlight.Name = "RealityWarpHighlight"
	highlight.Adornee = echoModel
	highlight.FillColor = F.YELLOW
	highlight.OutlineColor = F.WHITE
	highlight.FillTransparency = 0.75
	highlight.OutlineTransparency = 0.2
	highlight.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
	highlight.Enabled = false
	highlight.Parent = echoModel

	local data = {Model = echoModel, Parts = echoParts, Highlight = highlight}
	table.insert(F.Echoes, data)
	return data
end

F.BuildAllEchoes = function(char)
	F.ClearEchoes()
	F.RefreshSourceParts()
	for _ = 1, F.MAX_ECHOES do
		F.BuildEcho(char)
	end
end

F.CapturePose = function()
	if not F.Character or not F.Root or not F.Root.Parent then return end
	local pivot = F.Character:GetPivot()
	local pose = table.create(#F.SourceParts)

	for index, part in ipairs(F.SourceParts) do
		if part and part.Parent then
			pose[index] = pivot:ToObjectSpace(part.CFrame)
		end
	end

	table.insert(F.PoseHistory, 1, {Pivot = pivot, Pose = pose})
	while #F.PoseHistory > F.HISTORY_SIZE do
		table.remove(F.PoseHistory)
	end
end

F.GetCurrentSnapshot = function()
	if not F.Character or not F.Root or not F.Root.Parent then return nil end
	local pivot = F.Character:GetPivot()
	local pose = table.create(#F.SourceParts)
	for index, part in ipairs(F.SourceParts) do
		if part and part.Parent then
			pose[index] = pivot:ToObjectSpace(part.CFrame)
		end
	end
	return {Pivot = pivot, Pose = pose}
end

F.ApplyPose = function(echo, snapshot, extraOffset, transparency, tint, lateralOffset)
	if not snapshot then return end
	local poseRoot = snapshot.Pivot * CFrame.new(lateralOffset or 0, 0, extraOffset or 0)

	for _, partInfo in ipairs(echo.Parts) do
		local clone = partInfo.Clone
		local index = partInfo.SourceIndex
		local localCF = index and snapshot.Pose[index]

		if clone and clone.Parent and localCF then
			clone.CFrame = poseRoot * localCF
			clone.Transparency = math.clamp(
				transparency + (partInfo.BaseTransparency * 0.25),
				0, 1
			)
			clone.Color = partInfo.BaseColor:Lerp(tint, 0.68)
		end
	end

	if echo.Highlight then
		echo.Highlight.Enabled = transparency < 0.95
		echo.Highlight.FillColor = tint
		echo.Highlight.FillTransparency = math.clamp(transparency + 0.05, 0.5, 1)
	end
end

F.HideEcho = function(echo)
	if echo.Highlight then echo.Highlight.Enabled = false end
	for _, info in ipairs(echo.Parts) do
		if info.Clone then info.Clone.Transparency = 1 end
	end
end

F.UpdateIdlePhasing = function()
	if #F.Echoes < 2 then return end
	local snapshot = F.GetCurrentSnapshot()
	if not snapshot then return end
	local t = os.clock()
	local phaseIntensity = 0
	if F.Speed > F.CINEMATIC_THRESHOLD then
		local ratio = F.Speed / F.CINEMATIC_THRESHOLD
		phaseIntensity = (ratio >= 120) and 1 or math.clamp(math.log(ratio) / math.log(120), 0, 1)
	end
	local frequency = 10 + phaseIntensity * 32
	local sideShift = math.sin(t * frequency * math.pi * 2) * (0.025 + phaseIntensity * 0.34)
	local ghostFade = phaseIntensity * 0.14

	F.ApplyPose(F.Echoes[1], snapshot, 0, math.clamp(0.79 + ghostFade + math.sin(t * (frequency + 3)) * 0.025, 0, 0.99), F.GOLD, sideShift)
	F.ApplyPose(F.Echoes[2], snapshot, 0.015, math.clamp(0.84 + ghostFade + math.sin(t * (frequency + 7) + 1) * 0.03, 0, 0.995), F.YELLOW, -sideShift * 0.82)

	for i = 3, #F.Echoes do F.HideEcho(F.Echoes[i]) end
end

F.UpdateMovingEchoes = function()
	if #F.Echoes == 0 or #F.PoseHistory < 2 then return end
	local maxEcho = math.min(3, #F.Echoes)

	for i = 1, maxEcho do
		local historyIndex = ({3, 6, 9})[i]
		historyIndex = math.clamp(historyIndex, 1, #F.PoseHistory)
		local snapshot = F.PoseHistory[historyIndex]
		local transparency = 0.58 + ((i - 1) * 0.09)
		local tint = (i % 2 == 1) and F.GOLD or F.YELLOW
		F.ApplyPose(F.Echoes[i], snapshot, 0.2 + ((i - 1) * 0.12), transparency, tint)
	end

	if F.Echoes[4] then F.HideEcho(F.Echoes[4]) end
end

F.HideAllEchoes = function()
	for _, echo in ipairs(F.Echoes) do F.HideEcho(echo) end
end

--==================================================
-- MOVEMENT DIRECTION
--==================================================

F.GetDirection = function()
    if F.UIS:GetFocusedTextBox() then
        return Vector3.zero
    end

	local forward = 0
	local right = 0

	local w = F.HoldingW or F.UIS:IsKeyDown(Enum.KeyCode.W)
	local a = F.HoldingA or F.UIS:IsKeyDown(Enum.KeyCode.A)
	local s = F.HoldingS or F.UIS:IsKeyDown(Enum.KeyCode.S)
	local d = F.HoldingD or F.UIS:IsKeyDown(Enum.KeyCode.D)

	if w then forward += 1 end
	if s then forward -= 1 end
	if d then right += 1 end
	if a then right -= 1 end

	if forward == 0 and right == 0 then
		if F.Humanoid and F.Humanoid.MoveDirection.Magnitude > 0 then
			return F.Humanoid.MoveDirection.Unit
		end
		return Vector3.zero
	end

	local camera = workspace.CurrentCamera or F.Camera
	if not camera then return Vector3.zero end

	local look = camera.CFrame.LookVector
	local cameraRight = camera.CFrame.RightVector
	look = Vector3.new(look.X, 0, look.Z)
	cameraRight = Vector3.new(cameraRight.X, 0, cameraRight.Z)

	if look.Magnitude > 0 then look = look.Unit end
	if cameraRight.Magnitude > 0 then cameraRight = cameraRight.Unit end

	local direction = (look * forward) + (cameraRight * right)
	if direction.Magnitude > 0 then return direction.Unit end
	return Vector3.zero
end

-- Travel-aligned basis in HumanoidRootPart local space: side, up, backward (+Z = behind).
F.GetBeamBasisLocal = function()
    local root = F.Root
    if not root or not root.Parent then
        return Vector3.xAxis, Vector3.yAxis, Vector3.zAxis
    end

    local direction = F.GetDirection and F.GetDirection() or Vector3.zero
    if direction.Magnitude < 0.05 and F.Humanoid and F.Humanoid.Parent then
        direction = F.Humanoid.MoveDirection
    end

    direction = Vector3.new(direction.X, 0, direction.Z)
    if direction.Magnitude < 0.05 then
        local look = root.CFrame.LookVector
        direction = Vector3.new(look.X, 0, look.Z)
    end
    if direction.Magnitude < 0.05 then
        direction = Vector3.new(0, 0, -1)
    else
        direction = direction.Unit
    end

    local sideWorld = direction:Cross(Vector3.yAxis)
    if sideWorld.Magnitude < 0.05 then
        sideWorld = root.CFrame.RightVector
    else
        sideWorld = sideWorld.Unit
    end
    local upWorld = Vector3.yAxis
    local axisWorld = -direction

    return root.CFrame:VectorToObjectSpace(sideWorld),
        root.CFrame:VectorToObjectSpace(upWorld),
        root.CFrame:VectorToObjectSpace(axisWorld)
end

--==================================================
-- VFX UPDATE FUNCTIONS
--==================================================

F.UpdateLightningArcs = function(active, strength, now, forceRefresh)
	for _, arc in ipairs(F.CinematicArcs) do
		local visible = active and (math.sin(now * 37 + arc.Phase) > -0.72)
		for _, segment in ipairs(arc.Segments) do
			segment.Enabled = visible
			segment.Width0 = 0.045 + strength * 0.075
			segment.Width1 = 0.018 + strength * 0.025
		end

		local refreshInterval = F.LIGHTNING_REFRESH / (1 + strength * 0.42)
		if active and (forceRefresh or now - arc.LastRefresh >= refreshInterval) then
			arc.LastRefresh = now
			local pointA = arc.A.WorldPosition
			local pointB = arc.B.WorldPosition
			local line = pointB - pointA
			local length = line.Magnitude
			if length > 0.025 and F.Root and F.Root.Parent then
				local axis = line.Unit
				local side = axis:Cross(Vector3.new(0, 1, 0))
				if side.Magnitude < 0.08 then
					side = axis:Cross(Vector3.new(1, 0, 0))
				end
				side = side.Unit
				local depth = axis:Cross(side).Unit
				local amplitude = 0.10 + strength * 0.30
				local n1 = side * ((math.random() * 2 - 1) * amplitude)
					+ depth * ((math.random() * 2 - 1) * amplitude * 0.72)
				local n2 = side * ((math.random() * 2 - 1) * amplitude)
					+ depth * ((math.random() * 2 - 1) * amplitude * 0.72)
				local worldA = pointA + line * 0.34 + n1
				local worldB = pointA + line * 0.69 + n2
				arc.BendA.Position = F.Root.CFrame:PointToObjectSpace(worldA)
				arc.BendB.Position = F.Root.CFrame:PointToObjectSpace(worldB)
			end
		end
	end
end

-- Build the curved spine behind the character (world-space points, [0] = root).
-- Segment j uses the (smoothed) heading from j/N * TRAIL_CURVE_LAG seconds ago.
F.UpdateTrailSpine = function(deltaTime, direction, active)
    local root = F.Root
    if not root or not root.Parent then return end
    local now = os.clock()

    local target = Vector3.new(direction.X, 0, direction.Z)
    if target.Magnitude < 0.05 then
        local look = root.CFrame.LookVector
        target = Vector3.new(look.X, 0, look.Z)
        if target.Magnitude < 0.05 then target = Vector3.new(0, 0, -1) end
    end
    target = target.Unit

    if not F.TrailHeading or not active then
        -- Snap while idle so every new run starts with a straight trail.
        F.TrailHeading = target
        table.clear(F.TrailHistory)
        return
    end

    local blend = 1 - math.exp(-F.TRAIL_TURN_RATE * deltaTime)
    local heading = F.TrailHeading:Lerp(target, blend)
    if heading.Magnitude < 0.05 then heading = target end
    F.TrailHeading = heading.Unit

    local history = F.TrailHistory
    table.insert(history, 1, {t = now, dir = F.TrailHeading})
    while #history > 2 and now - history[#history].t > F.TRAIL_CURVE_LAG + 0.15 do
        table.remove(history)
    end

    local spine, headings = F.TrailSpine, F.TrailHeadings
    local position = root.Position
    spine[0] = position
    local index = 1
    for j = 1, F.TRAIL_SEGMENTS do
        local lagTime = now - (j / F.TRAIL_SEGMENTS) * F.TRAIL_CURVE_LAG
        while index < #history and history[index].t > lagTime do
            index += 1
        end
        local h = history[index].dir
        headings[j] = h
        position = position - h * F.TRAIL_SEGMENT_LENGTH
        spine[j] = position
    end
end

-- Position + forward heading on the spine at "distance" studs behind the root.
F.SampleTrail = function(distance)
    local segmentLength = F.TRAIL_SEGMENT_LENGTH
    local count = F.TRAIL_SEGMENTS
    local spine, headings = F.TrailSpine, F.TrailHeadings
    distance = math.max(distance, 0)
    local scaled = distance / segmentLength
    local k = math.floor(scaled)
    if k >= count then
        local h = headings[count]
        return spine[count] - h * (distance - count * segmentLength), h
    end
    return spine[k]:Lerp(spine[k + 1], scaled - k), headings[k + 1]
end

-- Offset (from the root) of the back edge of a body part along the travel direction.
-- Measured from the part's real size and current rotation every frame, so the trail starts
-- exactly at the back of the head/torso/limbs whatever animation is playing.
F.GetTrailingEdgeOffset = function(part, rootPosition)
    local heading = F.TrailHeadings[1] or Vector3.new(0, 0, -1)
    local cf = part.CFrame
    local size = part.Size
    local extent = 0.5 * (
        math.abs(heading:Dot(cf.RightVector)) * size.X
        + math.abs(heading:Dot(cf.UpVector)) * size.Y
        + math.abs(heading:Dot(cf.LookVector)) * size.Z
    )
    return part.Position - heading * (extent - 0.15) - rootPosition
end

-- A point on the curved trail, converted to HumanoidRootPart local space.
F.TrailPoint = function(rootCF, distance, x, y, anchorOffset)
    local position, heading = F.SampleTrail(distance)
    local side = heading:Cross(Vector3.yAxis)
    if side.Magnitude > 0.05 then side = side.Unit else side = Vector3.xAxis end
    local world = position + anchorOffset + side * x + Vector3.yAxis * y
    return rootCF:PointToObjectSpace(world)
end

-- Comic-style wake on the curved spine. Every bolt starts on an animated body part
-- (torso/feet/hands), so forward-leaning animations never leave a gap.
F.UpdateWakeLightning = function(active, strength, now)
    strength = math.clamp(strength, 0, 1)
    if not active or not F.Root or not F.Root.Parent or not F.TrailSpine[F.TRAIL_SEGMENTS] then
        for _, bolt in ipairs(F.CinematicWakeBolts) do
            for _, beam in ipairs(bolt.Beams) do beam.Enabled = false end
        end
        return
    end
    local refreshEvery = 0.07 - strength * 0.025
    local rootCF = F.Root.CFrame
    local rootPosition = rootCF.Position

    for _, bolt in ipairs(F.CinematicWakeBolts) do
        local visible = math.sin(now * 14 + bolt.Phase) > -0.8
        local count = #bolt.Attachments
        local refresh = now - bolt.LastRefresh >= refreshEvery
        if refresh then bolt.LastRefresh = now end

        local anchorOffset = Vector3.zero
        if bolt.Anchor and bolt.Anchor.Parent then
            anchorOffset = F.GetTrailingEdgeOffset(bolt.Anchor, rootPosition)
        end

        for i, attachment in ipairs(bolt.Attachments) do
            local jitter = bolt.Jitter[i]
            if refresh or not jitter then
                local t = (i - 1) / (count - 1)
                local amp = (i == 1) and 0.05 or ((0.15 + t * (1.6 + strength * 1.8)) * bolt.Spread)
                local zig = (i % 2 == 0) and 1 or -1
                jitter = Vector3.new(
                    (zig * 0.6 + (math.random() * 2 - 1) * 0.7) * amp,
                    (math.random() * 2 - 1) * amp * 0.7,
                    (math.random() * 2 - 1) * 0.6 * t
                )
                bolt.Jitter[i] = jitter
            end
            local base = bolt.BasePoints[i]
            attachment.Position = F.TrailPoint(
                rootCF, base.Z + jitter.Z, base.X + jitter.X, base.Y + jitter.Y, anchorOffset
            )
        end

        for segmentIndex, beam in ipairs(bolt.Beams) do
            beam.Enabled = visible
            local taper = 1 - (segmentIndex - 1) / #bolt.Beams * 0.6
            beam.Width0 = (0.045 + strength * 0.03) * taper
            beam.Width1 = math.max(0.012, beam.Width0 * 0.55)
        end
    end
end

-- Soft red/orange motion-blur bands that bend with the curved trail.
F.UpdateSpeedBlur = function(active, strength, now)
    strength = math.clamp(strength, 0, 1)
    if not active or not F.Root or not F.Root.Parent or not F.TrailSpine[F.TRAIL_SEGMENTS] then
        for _, streak in ipairs(F.CinematicBlurStreaks) do
            for _, beam in ipairs(streak.Beams) do beam.Enabled = false end
        end
        return
    end
    local rootCF = F.Root.CFrame
    local rootPosition = rootCF.Position

    for _, streak in ipairs(F.CinematicBlurStreaks) do
        local anchorOffset = Vector3.zero
        if streak.Anchor and streak.Anchor.Parent then
            anchorOffset = F.GetTrailingEdgeOffset(streak.Anchor, rootPosition)
        end
        local flicker = 0.88 + 0.12 * math.sin(now * 11 + streak.Phase)
        local totalLength = streak.Length * (0.55 + strength * 0.6)
        local width = streak.Width * (0.8 + strength * 0.5) * flicker
        local segmentCount = #streak.Beams

        for seg = 0, segmentCount do
            streak.Attachments[seg + 1].Position = F.TrailPoint(
                rootCF, totalLength * (seg / segmentCount), streak.X, streak.Y, anchorOffset
            )
        end
        for seg, beam in ipairs(streak.Beams) do
            beam.Width0 = width * (1 - 0.88 * ((seg - 1) / segmentCount))
            beam.Width1 = width * (1 - 0.88 * (seg / segmentCount))
            beam.Enabled = true
        end
    end
end

F.UpdateCinematicMode = function(isMoving, moveDirection)
	local active = F.Speed >= F.CINEMATIC_THRESHOLD
    local runningWake = F.Speed >= F.SPEED_BEAM_START_SPEED and isMoving
	local strength = 0
	local now = os.clock()

	if active then
		strength = 0.35 + 0.65 * math.clamp(
			(F.Speed - F.CINEMATIC_THRESHOLD) / 2600,
			0, 1
		)
	end

	if F.CinematicHighlight then
		F.CinematicHighlight.Enabled = active
		if F.Speed >= F.TIME_RIFT_THRESHOLD then
			local riftIntensity = F.GetTimeRiftIntensity()
			F.CinematicHighlight.FillColor = Color3.fromRGB(255, 180, 75)
			F.CinematicHighlight.OutlineColor = Color3.fromRGB(255, 248, 220)
			F.CinematicHighlight.FillTransparency = 0.76 - riftIntensity * 0.20
			F.CinematicHighlight.OutlineTransparency = 0.04 - riftIntensity * 0.025
			F.CinematicHighlight.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
		else
			F.CinematicHighlight.FillColor = F.GOLD
			F.CinematicHighlight.OutlineColor = F.YELLOW
			F.CinematicHighlight.FillTransparency = active and (0.94 - strength * 0.08) or 1
			F.CinematicHighlight.OutlineTransparency = active and (0.30 - strength * 0.18) or 1
			F.CinematicHighlight.DepthMode = Enum.HighlightDepthMode.Occluded
		end
	end

	if F.CinematicLight then
		local flicker = (math.sin(now * 34) > 0.25) and 0.45 or 0
		F.CinematicLight.Brightness = active and (0.75 + strength * 2.7 + flicker) or 0
		F.CinematicLight.Range = 14 + strength * 14
	end

	F.UpdateLightningArcs(active, strength, now, false)
	local wakeStrength = 0.16 + F.GetSpeedBeamProgress() * 0.84
    -- (wake + blur now update every frame from Heartbeat so the curve stays smooth)

	if F.CinematicGroundAttachment and F.Root and F.Root.Parent and moveDirection and moveDirection.Magnitude > 0.05 then
		local backward = -moveDirection.Unit
		local worldPosition = F.Root.Position - Vector3.new(0, 1.95, 0)
		local desiredWorld = CFrame.lookAt(worldPosition, worldPosition + backward)
		F.CinematicGroundAttachment.CFrame = F.Root.CFrame:ToObjectSpace(desiredWorld)
	end

	if F.CinematicGroundHaze then
		F.CinematicGroundHaze.Rate = 0 -- puffs read as separate balls at high speed; a continuous ground streak replaces them
	end

    local warmGradeActive = active and F.Speed < F.TIME_RIFT_THRESHOLD
	F.CinematicGrade.Enabled = warmGradeActive
	F.CinematicBloom.Enabled = warmGradeActive
	F.CinematicGrade.TintColor = F.WHITE:Lerp(Color3.fromRGB(255, 178, 104), strength * 0.23)
	F.CinematicGrade.Brightness = strength * 0.006
	F.CinematicGrade.Contrast = strength * 0.11
	F.CinematicGrade.Saturation = strength * 0.10
	F.CinematicBloom.Intensity = 0.12 + strength * 0.42
	F.CinematicBloom.Threshold = 1.55 - strength * 0.25

	if F.CinematicSparkAttachment and F.Root and F.Root.Parent and moveDirection and moveDirection.Magnitude > 0.05 then
		local sparkPosition = F.Root.Position - Vector3.new(0, 0.45, 0) - moveDirection.Unit * 0.65
		local sparkWorld = CFrame.lookAt(sparkPosition, sparkPosition - moveDirection.Unit)
		F.CinematicSparkAttachment.CFrame = F.Root.CFrame:ToObjectSpace(sparkWorld)
	end

	if F.CinematicSpark then
		F.CinematicSpark.Rate = runningWake and (5 + math.floor(wakeStrength * 18)) or 0
	end
end

F.UpdateTrailAndParticles = function(isMoving)
	if not F.Character or not F.Root then return end
	local torso = F.Character:FindFirstChild("UpperTorso") or F.Character:FindFirstChild("Torso") or F.Root
	if torso then
		local light = torso:FindFirstChild("WallySpeedLight")
		local energyAttachment = torso:FindFirstChild("WallyEnergyAttachment")
		local energy = energyAttachment and energyAttachment:FindFirstChild("WallyEnergy")

		local lowSpeedRunning = F.Speed > 5 and isMoving and F.Speed < F.SPEED_BEAM_START_SPEED
		local intensity = math.clamp(F.Speed / 700, 0, 1)
		if light then
			light.Brightness = lowSpeedRunning and (0.35 + intensity * 1.3) or 0
			light.Range = 10 + intensity * 5
		end
		if energy then
			energy.Rate = lowSpeedRunning and (4 + math.floor(intensity * 12)) or 0
		end
	end

	local smokeAttachment = F.Root:FindFirstChild("WallySmokeWake")
	if smokeAttachment then
		local dust = smokeAttachment:FindFirstChild("Dust")
		local fastDust = smokeAttachment:FindFirstChild("FastDust")
		local energyDust = smokeAttachment:FindFirstChild("EnergyDust")

		if F.Speed > 30 and isMoving then
			local power = math.clamp(F.Speed / 1500, 0, 1)
			local cinematicRunning = F.Speed >= F.SPEED_BEAM_START_SPEED
			if dust then
				dust.Rate = cinematicRunning and 0 or math.clamp(F.Speed * 0.07, 12, 100)
				dust.Size = NumberSequence.new({
					NumberSequenceKeypoint.new(0, 2 + power),
					NumberSequenceKeypoint.new(0.4, 4 + power * 3),
					NumberSequenceKeypoint.new(1, 8 + power * 5),
				})
			end
			if fastDust then
				fastDust.Rate = cinematicRunning and 0 or math.clamp(F.Speed * 0.025, 4, 40)
			end
			if energyDust then
				energyDust.Rate = cinematicRunning and 0 or math.clamp(F.Speed * 0.018, 3, 30)
			end
		else
			if dust then dust.Rate = 0 end
			if fastDust then fastDust.Rate = 0 end
			if energyDust then energyDust.Rate = 0 end
		end
	end
end

--==================================================
-- LIMB OVERSPEED: SMOOTH RUN CYCLE
--==================================================

F.LimbOverspeedMotors = {}
F.LimbRunPhase = 0
F.LimbOverlayIntensity = 0
F.LimbCurrentFrequency = 1.6
F.LIMB_OVERLAY_FADE_RATE = 9.0
F.LIMB_MIN_FREQUENCY = 1.6
F.LIMB_MAX_FREQUENCY = 6.8

F.RestoreLimbSpeedOverlay = function()
    for _, entry in ipairs(F.LimbOverspeedMotors) do
        local motor = entry.Motor
        if motor and motor.Parent and entry.LastApplied and motor.Transform == entry.LastApplied then
            pcall(function()
                motor.Transform = entry.LastBase or CFrame.new()
            end)
        end
        entry.LastApplied = nil
        entry.LastBase = nil
    end
end

F.SetupLimbSpeedOverlay = function(char)
    F.RestoreLimbSpeedOverlay()
    table.clear(F.LimbOverspeedMotors)
    F.LimbRunPhase = 0
    F.LimbOverlayIntensity = 0
    F.LimbCurrentFrequency = F.LIMB_MIN_FREQUENCY
    if not char then return end

    for _, object in ipairs(char:GetDescendants()) do
        if object:IsA("Motor6D") and object.Part1 then
            local jointName = string.lower(object.Name)
            local partName = string.lower(object.Part1.Name)

            local isArmJoint = string.find(jointName, "shoulder", 1, true)
                or string.find(jointName, "elbow", 1, true)
                or string.find(jointName, "wrist", 1, true)
                or string.find(partName, "arm", 1, true)
                or string.find(partName, "hand", 1, true)
            local isLegJoint = string.find(jointName, "hip", 1, true)
                or string.find(jointName, "knee", 1, true)
                or string.find(jointName, "ankle", 1, true)
                or string.find(partName, "leg", 1, true)
                or string.find(partName, "foot", 1, true)

            if isArmJoint or isLegJoint then
                local kind = isArmJoint and "arm" or "leg"
                local isRight = string.find(jointName, "right", 1, true)
                    or string.find(partName, "right", 1, true)
                local sidePhase = isRight and math.pi or 0
                local kindPhase = (kind == "arm") and math.pi or 0

                local jointType = "upper"
                if string.find(jointName, "shoulder", 1, true) then
                    jointType = "shoulder"
                elseif string.find(jointName, "elbow", 1, true) then
                    jointType = "elbow"
                elseif string.find(jointName, "wrist", 1, true) then
                    jointType = "wrist"
                elseif string.find(jointName, "hip", 1, true) then
                    jointType = "hip"
                elseif string.find(jointName, "knee", 1, true) then
                    jointType = "knee"
                elseif string.find(jointName, "ankle", 1, true) then
                    jointType = "ankle"
                elseif string.find(partName, "lowerarm", 1, true)
                    or string.find(partName, "forearm", 1, true) then
                    jointType = "elbow"
                elseif string.find(partName, "lowerleg", 1, true) then
                    jointType = "knee"
                elseif string.find(partName, "foot", 1, true) then
                    jointType = "ankle"
                end

                local jointPhase = 0
                if jointType == "elbow" or jointType == "knee" then
                    jointPhase = 0.72
                elseif jointType == "wrist" or jointType == "ankle" then
                    jointPhase = 1.12
                end

                local weight = 1
                if jointType == "elbow" or jointType == "knee" then
                    weight = 0.62
                elseif jointType == "wrist" or jointType == "ankle" then
                    weight = 0.28
                end

                table.insert(F.LimbOverspeedMotors, {
                    Motor = object,
                    Kind = kind,
                    JointType = jointType,
                    Weight = weight,
                    Phase = sidePhase + kindPhase + jointPhase,
                    LastBase = nil,
                    LastApplied = nil,
                })
            end
        end
    end
end

F.UpdateLimbSpeedOverlay = function(deltaTime)
    if not F.Running or not F.Character or not F.Character.Parent or not F.Root or not F.Root.Parent then
        F.RestoreLimbSpeedOverlay()
        F.LimbOverlayIntensity = 0
        return
    end

    local direction = F.GetDirection()
    local moving = direction.Magnitude > 0.05 and F.Speed >= F.SPEED_BEAM_START_SPEED
    if not moving then
        F.RestoreLimbSpeedOverlay()
        F.LimbOverlayIntensity = 0
        F.LimbCurrentFrequency = F.LIMB_MIN_FREQUENCY
        return
    end
    local targetIntensity = F.GetSpeedBeamProgress()

    local dt = math.clamp(tonumber(deltaTime) or 1 / 60, 1 / 240, 1 / 20)
    local blend = 1 - math.exp(-F.LIMB_OVERLAY_FADE_RATE * dt)
    F.LimbOverlayIntensity += (targetIntensity - F.LimbOverlayIntensity) * blend

    if F.LimbOverlayIntensity <= 0.006 then
        F.RestoreLimbSpeedOverlay()
        return
    end

    local desiredFrequency = F.LIMB_MIN_FREQUENCY
        + (F.LIMB_MAX_FREQUENCY - F.LIMB_MIN_FREQUENCY) * F.LimbOverlayIntensity
    F.LimbCurrentFrequency += (desiredFrequency - F.LimbCurrentFrequency)
        * (1 - math.exp(-5.5 * dt))
    F.LimbRunPhase = (F.LimbRunPhase + dt * F.LimbCurrentFrequency * math.pi * 2) % (math.pi * 2)

    for _, entry in ipairs(F.LimbOverspeedMotors) do
        local motor = entry.Motor
        if motor and motor.Parent then
            if entry.LastApplied and motor.Transform == entry.LastApplied then
                motor.Transform = entry.LastBase or CFrame.new()
            end
            entry.LastApplied = nil
            entry.LastBase = nil

            local gait = F.LimbRunPhase + entry.Phase
            local stride = math.sin(gait)
            local recovery = math.max(0, math.sin(gait + 0.9))
            local baseSwing = math.rad(7 + 20 * F.LimbOverlayIntensity) * entry.Weight
            local x, y, z = 0, 0, 0

            if entry.JointType == "shoulder" then
                x = stride * baseSwing * 1.0
                z = math.sin(gait + 0.35) * math.rad(1.5 + 3.0 * F.LimbOverlayIntensity)
                    * entry.Weight
            elseif entry.JointType == "hip" then
                x = stride * baseSwing * 1.05
                z = math.sin(gait + 0.25) * math.rad(0.8 + 1.6 * F.LimbOverlayIntensity)
                    * entry.Weight
            elseif entry.JointType == "elbow" then
                x = (recovery - 0.34) * math.rad(5 + 13 * F.LimbOverlayIntensity)
                    * entry.Weight
            elseif entry.JointType == "knee" then
                x = recovery * math.rad(6 + 19 * F.LimbOverlayIntensity) * entry.Weight
            elseif entry.JointType == "wrist" then
                x = math.sin(gait + 0.65) * math.rad(1.5 + 4 * F.LimbOverlayIntensity)
                    * entry.Weight
            elseif entry.JointType == "ankle" then
                x = -recovery * math.rad(2 + 6 * F.LimbOverlayIntensity) * entry.Weight
            else
                x = stride * baseSwing * 0.55
            end

            local base = motor.Transform
            local applied = base * CFrame.Angles(x, y, z)
            entry.LastBase = base
            entry.LastApplied = applied
            motor.Transform = applied
        end
    end
end

F.Connect(F.RunService.PreSimulation, F.UpdateLimbSpeedOverlay)

--==================================================
-- HIGH-SPEED BODY PHASING + LOCAL SLOW-MOTION ILLUSION
--==================================================

F.GetSpeedIntensity = function(referenceSpeed, ratioToFull)
	if F.Speed <= referenceSpeed then return 0 end
	if F.Speed == math.huge or F.Speed >= referenceSpeed * ratioToFull then return 1 end
	return math.clamp(math.log(F.Speed / referenceSpeed) / math.log(ratioToFull), 0, 1)
end

F.UndoBodyTransform = function()
	if F.BodyRootMotor and F.BodyRootMotor.Parent and F.LastBodyAppliedTransform
		and F.BodyRootMotor.Transform == F.LastBodyAppliedTransform then
		pcall(function()
			F.BodyRootMotor.Transform = F.LastBodyBaseTransform or CFrame.new()
		end)
	end
	F.LastBodyOffset = 0
	F.LastBodyBaseTransform = nil
	F.LastBodyAppliedTransform = nil
end

F.RestoreBodyPhasing = function()
	F.UndoBodyTransform()

	for part, original in pairs(F.BodyPartBaseline) do
		if part and part.Parent then
			pcall(function() part.LocalTransparencyModifier = original end)
		end
	end
	table.clear(F.BodyPartBaseline)
	F.BodyRootMotor = nil
	F.BodyWasPhasing = false
end

F.SetupBodyPhasing = function(char)
	F.RestoreBodyPhasing()
	if not char then return end

	local root = char:FindFirstChild("HumanoidRootPart")
	for _, object in ipairs(char:GetDescendants()) do
		if object:IsA("BasePart") then
			F.BodyPartBaseline[object] = object.LocalTransparencyModifier
		elseif root and object:IsA("Motor6D") and object.Part0 == root and object.Part1 then
			F.BodyRootMotor = object
		end
	end
end

F.RestoreBodyVisibilityOnly = function()
	for part, original in pairs(F.BodyPartBaseline) do
		if part and part.Parent then
			pcall(function() part.LocalTransparencyModifier = original end)
		end
	end
	F.BodyWasPhasing = false
end

F.UpdateBodyPhasing = function()
	F.UndoBodyTransform()

	if not F.Running or not F.Root or not F.Root.Parent or not F.Humanoid or not F.Humanoid.Parent then
		if F.BodyWasPhasing then F.RestoreBodyVisibilityOnly() end
		return
	end

	local direction = F.GetDirection()
	local isStandingStill = direction.Magnitude < 0.05 and F.Humanoid.MoveDirection.Magnitude < 0.05
	if F.Speed < F.CINEMATIC_THRESHOLD or not isStandingStill then
		if F.BodyWasPhasing then F.RestoreBodyVisibilityOnly() end
		return
	end

	local intensity = F.GetSpeedIntensity(F.CINEMATIC_THRESHOLD, 120)
	local now = os.clock()
	local frequency = 8 + intensity * 27
	local amplitude = 0.025 + intensity * 0.25
	local offset = math.sin(now * frequency * math.pi * 2) * amplitude

	if F.BodyRootMotor and F.BodyRootMotor.Parent then
		F.LastBodyBaseTransform = F.BodyRootMotor.Transform
		F.BodyRootMotor.Transform = CFrame.new(offset, 0, 0) * F.LastBodyBaseTransform
		F.LastBodyAppliedTransform = F.BodyRootMotor.Transform
		F.LastBodyOffset = offset
	end

	local alpha = 0.025 + intensity * 0.955
	local vanishPulse = math.sin(now * (22 + intensity * 92)) > 0.52
	if intensity > 0.82 and vanishPulse then alpha = 1 end
	alpha = math.clamp(alpha, 0, 1)

	if F.CinematicHighlight then
		F.CinematicHighlight.FillTransparency = math.clamp(0.94 + intensity * 0.055, 0.94, 0.995)
		F.CinematicHighlight.OutlineTransparency = math.clamp(0.30 + intensity * 0.66, 0.30, 0.99)
		if intensity > 0.82 and vanishPulse then
			F.CinematicHighlight.OutlineTransparency = 1
		end
	end

	for part, original in pairs(F.BodyPartBaseline) do
		if part and part.Parent then
			part.LocalTransparencyModifier = original + (1 - original) * alpha
		end
	end
	F.BodyWasPhasing = true
end

F.RestoreWorldSlowMotion = function()
	for track, originalSpeed in pairs(F.WorldSlowMotionTracks) do
		pcall(function()
			if track and track.IsPlaying then
				track:AdjustSpeed(originalSpeed)
			end
		end)
		F.WorldSlowMotionTracks[track] = nil
	end
end

F.UpdateWorldSlowMotion = function()
	if F.Speed < F.WORLD_SLOW_THRESHOLD or not F.Root or not F.Root.Parent then
		F.RestoreWorldSlowMotion()
		return
	end

	local intensity = F.GetSpeedIntensity(F.WORLD_SLOW_THRESHOLD, 100)
	local slowFactor
	if F.Speed >= F.TIME_RIFT_THRESHOLD then
		local timeIntensity = F.GetSpeedIntensity(F.TIME_RIFT_THRESHOLD, 120)
		slowFactor = 0.20 - timeIntensity * 0.15
	else
		slowFactor = 1 - intensity * 0.80
	end
	local seen = {}
	local maxDistanceSquared = F.WORLD_SLOW_RADIUS * F.WORLD_SLOW_RADIUS

	for _, otherPlayer in ipairs(F.Players:GetPlayers()) do
		if otherPlayer ~= F.Player then
			local otherCharacter = otherPlayer.Character
			local otherRoot = otherCharacter and otherCharacter:FindFirstChild("HumanoidRootPart")
			local otherHumanoid = otherCharacter and otherCharacter:FindFirstChildOfClass("Humanoid")
			local animator = otherHumanoid and otherHumanoid:FindFirstChildOfClass("Animator")

			if otherRoot and otherHumanoid and animator
				and (otherRoot.Position - F.Root.Position).Magnitude^2 <= maxDistanceSquared then
				for _, track in ipairs(animator:GetPlayingAnimationTracks()) do
					seen[track] = true
					if F.WorldSlowMotionTracks[track] == nil then
						F.WorldSlowMotionTracks[track] = track.Speed
					end
					local originalSpeed = F.WorldSlowMotionTracks[track]
					local targetSpeed = (originalSpeed == 0) and 0 or math.max(0.04, originalSpeed * slowFactor)
					if math.abs(track.Speed - targetSpeed) > 0.025 then
						pcall(function() track:AdjustSpeed(targetSpeed) end)
					end
				end
			end
		end
	end

	for track, originalSpeed in pairs(F.WorldSlowMotionTracks) do
		if not seen[track] then
			pcall(function()
				if track and track.IsPlaying then track:AdjustSpeed(originalSpeed) end
			end)
			F.WorldSlowMotionTracks[track] = nil
		end
	end
end

F.Connect(F.RunService.PreSimulation, F.UpdateBodyPhasing)

--==================================================
-- INPUT
--==================================================

F.HandleSpeedHold = function(actionName, inputState, _inputObject)
    local isAccel = actionName == F.AccelActionName
    local focused = F.UIS:GetFocusedTextBox() ~= nil

    if inputState == Enum.UserInputState.Begin then
        if isAccel then
            F.HoldingE = not focused
        else
            F.HoldingQ = not focused
        end
    elseif inputState == Enum.UserInputState.End or inputState == Enum.UserInputState.Cancel then
        if isAccel then F.HoldingE = false else F.HoldingQ = false end
    end

    if focused then
        return Enum.ContextActionResult.Pass
    end
    return Enum.ContextActionResult.Sink
end

F.ContextActionService:BindActionAtPriority(
    F.AccelActionName, F.HandleSpeedHold, false, 4000, Enum.KeyCode.E
)
F.ContextActionService:BindActionAtPriority(
    F.BrakeActionName, F.HandleSpeedHold, false, 4000, Enum.KeyCode.Q
)

F.Connect(F.UIS.InputBegan, function(input, gameProcessed)
    local focused = F.UIS:GetFocusedTextBox() ~= nil

    if not focused then
        if input.KeyCode == Enum.KeyCode.E then
            F.HoldingE = true
        elseif input.KeyCode == Enum.KeyCode.Q then
            F.HoldingQ = true
        elseif input.KeyCode == Enum.KeyCode.Z and not gameProcessed then
            F.SetHUDVisible(not F.HUDVisible)
            return
        elseif input.KeyCode == Enum.KeyCode.F9 and not gameProcessed then
            F.Speed = 0
            F.WasCinematicSpeed = false
            F.RealityWarpDistance = 0
            F.TimeRiftDistance = 0
            F.TimeRiftRotation = 0
            F.RealityWarpActiveBeamCount = 0
            F.RealityWarpSpawnCredit = 0
            F.HideAllEchoes()
            return
        elseif input.KeyCode == Enum.KeyCode.F10 then
            if F.Cleanup then pcall(F.Cleanup) end
            return
        end
    end

    if gameProcessed or focused then return end
    if input.KeyCode == Enum.KeyCode.W then
        F.HoldingW = true
    elseif input.KeyCode == Enum.KeyCode.A then
        F.HoldingA = true
    elseif input.KeyCode == Enum.KeyCode.S then
        F.HoldingS = true
    elseif input.KeyCode == Enum.KeyCode.D then
        F.HoldingD = true
    end
end)

F.Connect(F.UIS.InputEnded, function(input)
    if input == F.ActiveEButtonInput then
        F.ActiveEButtonInput = nil
        F.MobileHoldingE = false
        F.EStroke.Thickness = 1.2
    end
    if input == F.ActiveQButtonInput then
        F.ActiveQButtonInput = nil
        F.MobileHoldingQ = false
        F.QStroke.Thickness = 1.2
    end

    if input.KeyCode == Enum.KeyCode.E then
        F.HoldingE = false
    elseif input.KeyCode == Enum.KeyCode.Q then
        F.HoldingQ = false
    elseif input.KeyCode == Enum.KeyCode.W then
        F.HoldingW = false
    elseif input.KeyCode == Enum.KeyCode.A then
        F.HoldingA = false
    elseif input.KeyCode == Enum.KeyCode.S then
        F.HoldingS = false
    elseif input.KeyCode == Enum.KeyCode.D then
        F.HoldingD = false
    end
end)

F.Connect(F.UIS.WindowFocusReleased, function()
    F.HoldingE, F.HoldingQ = false, false
    F.HoldingW, F.HoldingA, F.HoldingS, F.HoldingD = false, false, false, false
    F.MobileHoldingE, F.MobileHoldingQ = false, false
    F.ActiveEButtonInput, F.ActiveQButtonInput = nil, nil
    F.EStroke.Thickness, F.QStroke.Thickness = 1.2, 1.2
end)

--==================================================
-- CHARACTER SETUP
--==================================================

F.SetupCharacter = function(char)
	F.Character = char
	F.Humanoid = char:WaitForChild("Humanoid")
	F.Root = char:WaitForChild("HumanoidRootPart")
	F.SetupTrail(char)
	F.SetupSmoke(char)
	F.SetupEnergy(char)
	F.SetupCinematicCharacter(char)
	F.SetupRealityWarpBeams(char)
	F.SetupTimeRiftEffects(char)
	F.BuildAllEchoes(char)
	F.SetupBodyPhasing(char)
	F.SetupLimbSpeedOverlay(char)
end

F.Character = F.Player.Character or F.Player.CharacterAdded:Wait()
F.Humanoid = F.Character:WaitForChild("Humanoid")
F.Root = F.Character:WaitForChild("HumanoidRootPart")
F.SetupTrail(F.Character)
F.SetupSmoke(F.Character)
F.SetupEnergy(F.Character)
F.SetupCinematicCharacter(F.Character)
F.SetupRealityWarpBeams(F.Character)
F.SetupTimeRiftEffects(F.Character)
F.BuildAllEchoes(F.Character)
F.SetupBodyPhasing(F.Character)
F.SetupLimbSpeedOverlay(F.Character)

--==================================================
-- MAIN UPDATE LOOP
--==================================================

F.PoseTimer = 0
F.CinematicTimer = 0
F.VFXTimer = 0
F.GUIUpdateTimer = 0
F.EchoUpdateTimer = 0
F.RealityWarpTimer = 0
F.TimeRiftTimer = 0

F.Connect(F.RunService.Heartbeat, function(deltaTime)
	if not F.Running then return end
	if not F.Character or not F.Humanoid or not F.Root or not F.Root.Parent then return end

    local textFocused = F.UIS:GetFocusedTextBox() ~= nil
	local eDown = (not textFocused) and (F.HoldingE or F.MobileHoldingE or F.UIS:IsKeyDown(Enum.KeyCode.E))
	local qDown = (not textFocused) and (F.HoldingQ or F.MobileHoldingQ or F.UIS:IsKeyDown(Enum.KeyCode.Q))

	if eDown then
		F.Speed = math.min(F.Speed + F.Acceleration * deltaTime, F.MaxSpeed)
	elseif qDown then
		F.Speed = math.max(F.Speed - F.Deceleration * deltaTime, 0)
	end

	local direction = F.GetDirection()
	local moving = direction.Magnitude > 0
	F.UpdateRunMusic(deltaTime, moving)

	F.UpdateRealityWarpQuality(deltaTime)

	F.RealityWarpTimer += deltaTime
	local beamInterval
    if F.Speed >= F.TIME_RIFT_THRESHOLD then
        beamInterval = (F.RealityWarpQualityScale < 0.82) and 0.05 or 0.0333333333
    else
        beamInterval = 0.05
    end
	if F.RealityWarpTimer >= beamInterval then
		F.RealityWarpTimer -= beamInterval
		F.UpdateRealityWarpBeams(beamInterval, moving)
	end

	F.TimeRiftTimer += deltaTime
	if F.TimeRiftTimer >= 0.05 then
		local riftDelta = F.TimeRiftTimer
		F.TimeRiftTimer = 0
		F.UpdateTimeRiftEffects(riftDelta, moving)
	end

	F.WorldSlowMotionTimer += deltaTime
	if F.WorldSlowMotionTimer >= 0.25 then
		F.WorldSlowMotionTimer = 0
		F.UpdateWorldSlowMotion()
	end

	if F.Speed > 0 and moving then
        local frameDistance = F.Speed * deltaTime
        if frameDistance ~= frameDistance or frameDistance == math.huge then
            frameDistance = 1000
        else
            frameDistance = math.clamp(frameDistance, 0, 1000)
        end
		local destination = F.Root.Position + direction * frameDistance
		F.Root.CFrame = CFrame.lookAt(destination, destination + direction)
	end

	if moving and F.Speed >= 150 then
		F.PoseTimer += deltaTime
		if F.PoseTimer >= 0.05 then
			F.PoseTimer = 0
			F.CapturePose()
		end
	else
		F.PoseTimer = 0
	end

	F.EchoUpdateTimer += deltaTime
	if F.EchoUpdateTimer >= (1 / 30) then
		F.EchoUpdateTimer = 0
		if F.Speed >= F.REALITY_WARP_THRESHOLD then
			if moving then
				F.UpdateMovingEchoes()
			else
				F.UpdateIdlePhasing()
			end
		else
			F.HideAllEchoes()
		end
	end

	-- Curved trail: refresh the steering spine, then lay the wake and blur along it.
	local trailActive = moving and F.Speed >= F.SPEED_BEAM_START_SPEED
	F.UpdateTrailSpine(deltaTime, direction, trailActive)
	local trailStrength = 0.16 + F.GetSpeedBeamProgress() * 0.84
	local trailNow = os.clock()
	F.UpdateWakeLightning(trailActive, trailStrength, trailNow)
	F.UpdateSpeedBlur(trailActive, trailStrength, trailNow)

	local fovBoost = math.clamp(F.Speed / 3000, 0, 1) * 17
	if F.Speed >= F.TIME_RIFT_THRESHOLD then
		local timeIntensity = F.GetSpeedIntensity(F.TIME_RIFT_THRESHOLD, 120)
		fovBoost += 5 + timeIntensity * 7
	end
	local targetFOV = math.clamp(F.OriginalCameraFOV + fovBoost, 1, 120)
	local camera = workspace.CurrentCamera or F.Camera
	if camera then
		local blend = 1 - math.exp(-deltaTime * 6.5)
		camera.FieldOfView += (targetFOV - camera.FieldOfView) * blend
	end

	F.CinematicTimer += deltaTime
	if F.CinematicTimer >= 0.04 then
		F.CinematicTimer = 0
		F.UpdateCinematicMode(moving, direction)
	end

	F.VFXTimer += deltaTime
	if F.VFXTimer >= 0.05 then
		F.VFXTimer = 0
		F.UpdateTrailAndParticles(moving)
	end

	F.WasCinematicSpeed = F.Speed >= F.CINEMATIC_THRESHOLD

	F.GUIUpdateTimer += deltaTime
	if F.GUIUpdateTimer >= 0.04 then
		F.GUIUpdateTimer = 0
		if F.Speed == math.huge then
			F.SpeedNumber.Text = "∞"
		elseif F.Speed >= 1e12 then
			F.SpeedNumber.Text = string.format("%.3e", F.Speed)
		else
			F.SpeedNumber.Text = tostring(math.floor(F.Speed))
		end

        local barPercent
        if F.Speed < F.SPEED_BEAM_START_SPEED then
            barPercent = 0.12 * math.clamp(F.Speed / F.SPEED_BEAM_START_SPEED, 0, 1)
        elseif F.Speed < F.CINEMATIC_THRESHOLD then
            barPercent = 0.12 + 0.26 * math.clamp(
                (F.Speed - F.SPEED_BEAM_START_SPEED) / (F.CINEMATIC_THRESHOLD - F.SPEED_BEAM_START_SPEED), 0, 1
            )
        elseif F.Speed < F.REALITY_WARP_THRESHOLD then
            barPercent = 0.38 + 0.24 * math.clamp(
                (F.Speed - F.CINEMATIC_THRESHOLD) / (F.REALITY_WARP_THRESHOLD - F.CINEMATIC_THRESHOLD), 0, 1
            )
        elseif F.Speed < F.TIME_RIFT_THRESHOLD then
            barPercent = 0.62 + 0.20 * math.clamp(
                (F.Speed - F.REALITY_WARP_THRESHOLD) / (F.TIME_RIFT_THRESHOLD - F.REALITY_WARP_THRESHOLD), 0, 1
            )
        else
            barPercent = 0.82 + 0.18 * F.GetTimeRiftIntensity()
        end
        if F.Speed == math.huge then barPercent = 1 end
        barPercent = math.clamp(barPercent, 0, 1)
		F.Fill.Size = UDim2.new(barPercent, 0, 1, 0)
		F.BarGlow.Size = UDim2.new(barPercent, 0, 1, 0)

		if F.Speed >= F.TIME_RIFT_THRESHOLD then
			F.Status.Text = "TIME RIFT"
			F.Status.TextColor3 = Color3.fromRGB(205, 220, 255)
			F.Status.BackgroundColor3 = Color3.fromRGB(25, 19, 54)
		elseif F.Speed >= F.REALITY_WARP_THRESHOLD then
			F.Status.Text = "REALITY WARP"
			F.Status.TextColor3 = F.WHITE
			F.Status.BackgroundColor3 = Color3.fromRGB(80, 24, 5)
		elseif F.Speed >= F.CINEMATIC_THRESHOLD then
			F.Status.Text = "SPEED FORCE"
			F.Status.TextColor3 = F.YELLOW
			F.Status.BackgroundColor3 = Color3.fromRGB(80, 35, 4)
		elseif eDown then
			F.Status.Text = "ACCEL"
			F.Status.TextColor3 = F.YELLOW
			F.Status.BackgroundColor3 = Color3.fromRGB(55, 37, 4)
		elseif qDown then
			F.Status.Text = "BRAKING"
			F.Status.TextColor3 = F.BRIGHT_RED
			F.Status.BackgroundColor3 = F.DARK_RED
		elseif F.Speed > 0 then
			F.Status.Text = "CRUISING"
			F.Status.TextColor3 = F.YELLOW
			F.Status.BackgroundColor3 = Color3.fromRGB(44, 31, 5)
		else
			F.Status.Text = "STANDBY"
			F.Status.TextColor3 = F.GREY
			F.Status.BackgroundColor3 = F.DARK
		end

		if F.Speed >= F.TIME_RIFT_THRESHOLD then
			F.SpeedNumber.TextColor3 = Color3.fromRGB(205, 220, 255)
		elseif F.Speed >= F.CINEMATIC_THRESHOLD then
			F.SpeedNumber.TextColor3 = F.YELLOW
		elseif F.Speed >= 700 then
			F.SpeedNumber.TextColor3 = F.GOLD
		elseif F.Speed > 0 then
			F.SpeedNumber.TextColor3 = F.WHITE
		else
			F.SpeedNumber.TextColor3 = F.GREY
		end

		if F.Speed >= F.TIME_RIFT_THRESHOLD then
			local pulse = 0.7 + math.sin(os.clock() * 19) * 0.3
			F.MainStroke.Color = Color3.fromRGB(165, 175, 255)
			F.MainStroke.Thickness = 2 + pulse
			F.TopGradient.Offset = Vector2.new(((os.clock() * 2.4) % 2) - 1, 0)
		elseif F.Speed >= F.CINEMATIC_THRESHOLD then
			local pulse = 0.7 + math.sin(os.clock() * 10) * 0.3
			F.MainStroke.Color = F.YELLOW
			F.MainStroke.Thickness = 2 + pulse
			F.TopGradient.Offset = Vector2.new(((os.clock() * 1.6) % 2) - 1, 0)
		elseif F.Speed >= 700 then
			F.MainStroke.Color = F.BRIGHT_RED
			F.MainStroke.Thickness = 2
		else
			F.MainStroke.Color = F.RED
			F.MainStroke.Thickness = 2
		end

		F.EStroke.Thickness = eDown and 2.8 or 1.2
		F.QStroke.Thickness = qDown and 2.8 or 1.2
	end
end)

-- Tiny speed-sense camera roll (under 0.3 degrees), applied after Roblox's camera update.
F.RunService:BindToRenderStep(F.CameraBindName, Enum.RenderPriority.Camera.Value + 1, function()
	if not F.Running then return end
	local camera = workspace.CurrentCamera
	if not camera or F.UIS:GetFocusedTextBox() then return end
	local intensity = math.clamp((F.Speed - 850) / 4500, 0, 1)
	if intensity <= 0 then return end
	local riftIntensity = (F.Speed >= F.TIME_RIFT_THRESHOLD) and (0.35 + F.GetSpeedIntensity(F.TIME_RIFT_THRESHOLD, 120) * 0.65) or 0
	local roll = math.sin(os.clock() * (13 + intensity * 12 + riftIntensity * 16)) * math.rad(0.28 + riftIntensity * 0.12) * intensity
	camera.CFrame = camera.CFrame * CFrame.Angles(0, 0, roll)
end)

--==================================================
-- RESPAWN SUPPORT
--==================================================

F.Connect(F.Player.CharacterAdded, function(newCharacter)
    F.Speed = 0
    F.HoldingE, F.HoldingQ = false, false
    F.HoldingW, F.HoldingA, F.HoldingS, F.HoldingD = false, false, false, false
    F.MobileHoldingE, F.MobileHoldingQ = false, false
    F.ActiveEButtonInput, F.ActiveQButtonInput = nil, nil
    F.WasCinematicSpeed = false
    F.RestoreWorldSlowMotion()
    F.RestoreBodyPhasing()
    F.RestoreLimbSpeedOverlay()
    F.Character = newCharacter
    F.Humanoid = nil
    F.Root = nil
    F.PoseTimer = 0
    F.EchoUpdateTimer = 0
    F.RealityWarpActiveBeamCount = 0
    F.RealityWarpSpawnCredit = 0
    F.RealityWarpDistance = 0
    F.TimeRiftDistance = 0
    F.TimeRiftRotation = 0
    task.wait(0.2)
    if not F.Running then return end
    F.SetupCharacter(newCharacter)
end)

--==================================================
-- FULL CLEANUP
--==================================================

F.Cleanup = function()
	if not F.Running then return end
	F.Running = false

	for _, connection in ipairs(F.Connections) do
		pcall(function() connection:Disconnect() end)
	end
	table.clear(F.Connections)

	F.RunService:UnbindFromRenderStep(F.CameraBindName)
    pcall(function() F.ContextActionService:UnbindAction(F.AccelActionName) end)
    pcall(function() F.ContextActionService:UnbindAction(F.BrakeActionName) end)
	F.RestoreBodyPhasing()
	F.RestoreLimbSpeedOverlay()
	F.RestoreWorldSlowMotion()
	if F.RunMusic then pcall(function() F.RunMusic:Stop(); F.RunMusic:Destroy() end) end
	local camera = workspace.CurrentCamera or F.Camera
	if camera then camera.FieldOfView = F.OriginalCameraFOV end

	F.CinematicGrade:Destroy()
	F.CinematicBloom:Destroy()
	F.TimeRiftGrade:Destroy()
	F.TimeRiftBloom:Destroy()
	F.DestroyCinematicCharacterEffects()
	F.ClearRealityWarpBeams()
	F.ClearTimeRiftEffects()
	F.ClearEchoes()

	if F.Character then
		for _, object in ipairs(F.Character:GetDescendants()) do
			if object.Name == "WallyTrailOuter"
				or object.Name == "WallyTrailCore"
				or object.Name == "WallyTrailTop"
				or object.Name == "WallyTrailBottom"
				or object.Name == "WallyTrailCoreTop"
				or object.Name == "WallyTrailCoreBottom"
				or object.Name == "WallySmokeWake"
				or object.Name == "WallyEnergyAttachment"
				or object.Name == "WallySpeedLight" then
				pcall(function() object:Destroy() end)
			end
		end
	end

	if F.VFXFolder then F.VFXFolder:Destroy() end
	if F.GUI then F.GUI:Destroy() end
	_G.WallySpeedForceCleanup = nil
end

_G.WallySpeedForceCleanup = F.Cleanup
end

local __ok, __err = xpcall(__BarryAllenStart, function(err)
    local message = tostring(err)
    if debug and debug.traceback then
        local traceOk, trace = pcall(debug.traceback, message, 2)
        if traceOk and trace then message = trace end
    end
    return message
end)

if not __ok then
    warn("[Barry Allen Speed Force] Startup failed:\n" .. tostring(__err))

    pcall(function()
        if F.Connections then
            for _, connection in ipairs(F.Connections) do
                pcall(function() connection:Disconnect() end)
            end
        end
    end)
    pcall(function()
        local runService = game:GetService("RunService")
        if F.CameraBindName then runService:UnbindFromRenderStep(F.CameraBindName) end
        local cas = game:GetService("ContextActionService")
        if F.AccelActionName then cas:UnbindAction(F.AccelActionName) end
        if F.BrakeActionName then cas:UnbindAction(F.BrakeActionName) end
    end)
    pcall(function() if F.VFXFolder then F.VFXFolder:Destroy() end end)
    pcall(function() if F.GUI then F.GUI:Destroy() end end)

    pcall(function()
        local player = game:GetService("Players").LocalPlayer
        local playerGui = player and player:FindFirstChild("PlayerGui")
        if not playerGui then return end
        local old = playerGui:FindFirstChild("BarryAllenStartupError")
        if old then old:Destroy() end
        local diag = Instance.new("ScreenGui")
        diag.Name = "BarryAllenStartupError"
        diag.ResetOnSpawn = false
        diag.DisplayOrder = 1000001
        diag.Parent = playerGui
        local panel = Instance.new("Frame")
        panel.AnchorPoint = Vector2.new(0.5, 0.5)
        panel.Position = UDim2.fromScale(0.5, 0.5)
        panel.Size = UDim2.new(0, 560, 0, 220)
        panel.BackgroundColor3 = Color3.fromRGB(25, 8, 10)
        panel.BorderSizePixel = 0
        panel.Parent = diag
        local corner = Instance.new("UICorner")
        corner.CornerRadius = UDim.new(0, 12)
        corner.Parent = panel
        local stroke = Instance.new("UIStroke")
        stroke.Color = Color3.fromRGB(255, 55, 65)
        stroke.Thickness = 2
        stroke.Parent = panel
        local title = Instance.new("TextLabel")
        title.BackgroundTransparency = 1
        title.Position = UDim2.new(0, 16, 0, 10)
        title.Size = UDim2.new(1, -32, 0, 30)
        title.Font = Enum.Font.GothamBold
        title.TextSize = 18
        title.TextXAlignment = Enum.TextXAlignment.Left
        title.TextColor3 = Color3.fromRGB(255, 90, 90)
        title.Text = "SPEED FORCE FAILED TO START"
        title.Parent = panel
        local details = Instance.new("TextLabel")
        details.BackgroundTransparency = 1
        details.Position = UDim2.new(0, 16, 0, 48)
        details.Size = UDim2.new(1, -32, 1, -60)
        details.Font = Enum.Font.Code
        details.TextSize = 12
        details.TextWrapped = true
        details.TextYAlignment = Enum.TextYAlignment.Top
        details.TextXAlignment = Enum.TextXAlignment.Left
        details.TextColor3 = Color3.fromRGB(245, 225, 225)
        details.Text = string.sub(tostring(__err), 1, 1800) .. "\n\nSee the Output window for the full error."
        details.Parent = panel
        local close = Instance.new("TextButton")
        close.AnchorPoint = Vector2.new(1, 0)
        close.Position = UDim2.new(1, -10, 0, 8)
        close.Size = UDim2.new(0, 30, 0, 28)
        close.Text = "X"
        close.Font = Enum.Font.GothamBold
        close.TextSize = 16
        close.TextColor3 = Color3.new(1, 1, 1)
        close.BackgroundColor3 = Color3.fromRGB(120, 20, 25)
        close.Parent = panel
        close.Activated:Connect(function() diag:Destroy() end)
    end)
end

How to Execute Universal Script – The Flash (i tried)

Step 1: Copy Code: Click the Copy Code button in the viewer above to grab the clean Lua loadstring.

Step 2: Launch Executor: Open a compatible, unpatched executor. If you need one, check our Roblox Executors Directory.

Step 3: Join Experience: Launch Roblox and join Universal Script.

Step 4: Attach & Run: Attach/inject your executor into the Roblox process, paste the code into the script tab, and press Execute.

Created By

killerX
killerX
Script Creator
View Author Profile

Features & Information

Execute Universal Script – The Flash (i tried). Key system required, created by killerX, updated Oct 22, 2026. Tested and working on supported executors.

Script Changelog (2)

@QueueSpeedDemonOct 23, 2026

Edited during review before approval

@killerXOct 22, 2026

Create script

Community Comments (0)

No comments yet for this script.

Frequently Asked Questions

How do I execute Universal Script – The Flash (i tried) in Roblox?

To run Universal Script – The Flash (i tried), copy the Lua loadstring from the code viewer above, launch Roblox and join Universal Script, attach a working executor (such as Potassium, Solara, or Delta from our Executors directory), paste the code into your executor console, and click Execute.

Is Universal Script – The Flash (i tried) keyless or does it require an access key?

Universal Script – The Flash (i tried) requires an access key. You can retrieve the official key directly using the Get Script Key link provided above.

Is Universal Script – The Flash (i tried) currently safe and working?

This script is active and operational. Always test scripts using a secondary (alt) Roblox account to safeguard your main profile against anti-cheat bans.