-- Neverlose if game.GameId~=6035872082 then warn("[Neverlose for RIVALS] This script only supports RIVALS");return end local source=[=====[ -- Neverlose -- BEGIN GENERATED STARTUP GUARD local STARTUP_SOURCE=[====[ -- Read-only startup checks. Never require a controller while the native loader owns it. local M={universeId=6035872082} local function find(root,path) for part in path:gmatch('[^/]+')do root=root and root:FindFirstChild(part)end return root end function M.probe() if game.GameId~=0 and game.GameId~=M.universeId then return nil,'wrong game' end if not game:IsLoaded()then return nil,'Roblox loading' end if game.GameId~=M.universeId then return nil,'wrong game' end local p=game:GetService('Players').LocalPlayer local ps=p and p:FindFirstChild('PlayerScripts');local pg=p and p:FindFirstChild('PlayerGui') if not (ps and pg and workspace.CurrentCamera)then return nil,'waiting for player/camera' end -- The same native ScreenGui moves from its module into PlayerGui, then is destroyed -- after Close() finishes. Check both locations, including the closing blur effect. local rf=game:GetService('ReplicatedFirst') if find(rf,'Root/LoadingScreen/LoadingScreen')or pg:FindFirstChild('LoadingScreen')or game:GetService('Lighting'):FindFirstChild('LoadingScreen')then return nil,'RIVALS loading screen' end local gui=pg:FindFirstChild('MainGui');if not gui then return nil,'waiting for game interface' end local rs=game:GetService('ReplicatedStorage') local token={ps,pg,gui,workspace.CurrentCamera} local fighter=find(ps,'Controllers/FighterController') if fighter then for _,spec in ipairs({ {ps,'Controllers/FighterController'},{ps,'Controllers/CameraController'}, {ps,'Controllers/MechanicsController'},{ps,'Modules/ClientReplicatedClasses/ClientFighter/ClientItem/ClientViewModel'}, {ps,'Modules/ItemTypes/Gun'},{rs,'Modules/ItemLibrary'},{rs,'Modules/CosmeticLibrary'},{rs,'Modules/Utility'}, })do local dependency=find(spec[1],spec[2]);if not dependency then return nil,'waiting for game modules' end table.insert(token,dependency) end else for _,path in ipairs({'Modules/Client/Controllers/GunController','Modules/Client/Controllers/CameraController','Modules/Client/CameraPOV','Assets/Operators/Operator1'})do local dependency=find(rs,path);if not dependency then return nil,'waiting for game modules' end table.insert(token,dependency) end end return token,'ready' end function M.same(a,b) if not a or not b or #a~=#b then return false end for i,v in ipairs(a)do if v~=b[i]then return false end end return true end function M.wait(timeout,cancel) local deadline=os.clock()+(timeout or 180);local stable,since;local reason repeat if cancel and cancel()then return false,'cancelled' end local token;token,reason=M.probe() if reason=='wrong game'then return false,reason end if not M.same(token,stable)then stable,since=token,os.clock()end if token and os.clock()-(since or os.clock())>=2 then return true end task.wait(.25) until os.clock()>=deadline return false,'Timed out waiting for '..tostring(reason) end return M ]====] local Startup=assert(loadstring(STARTUP_SOURCE,"Neverlose for RIVALS / Startup"))() local startupReady,startupReason=Startup.wait(180) if not startupReady then warn("[Neverlose for RIVALS] "..tostring(startupReason));return end -- END GENERATED STARTUP GUARD local cloneref = cloneref or function(o) return o end local Players = cloneref(game:GetService("Players")) local TweenService = cloneref(game:GetService("TweenService")) local UserInputService = cloneref(game:GetService("UserInputService")) local HttpService = cloneref(game:GetService("HttpService")) local RunService = cloneref(game:GetService("RunService")) local LocalPlayer = Players.LocalPlayer local httpRequest = request or http_request or (syn and syn.request) local ROOT = "neverlose_ui" local ICON_DIR = ROOT .. "/icons_v3" local ICON_DATA -- filled in at the bottom of the file local function rgb(r, g, b) return Color3.fromRGB(r, g, b) end -- Colours sampled from 1080p footage of the menu and the official docs screenshots. local Theme = { Content = rgb(8, 8, 13), Group = rgb(3, 13, 26), Line = rgb(5, 26, 38), Field = rgb(7, 15, 24), FieldStroke = rgb(3, 28, 46), Label = rgb(153, 176, 189), Title = rgb(232, 238, 242), Dim = rgb(96, 112, 126), NavHeader = rgb(60, 69, 82), NavText = rgb(232, 239, 250), NavTextActive = rgb(215, 244, 254), NavIcon = rgb(72, 147, 178), NavIconActive = rgb(66, 153, 194), NavActive = rgb(8, 47, 66), SidebarEdge = rgb(15, 20, 28), SidebarTint = rgb(2, 11, 24), SidebarSeeThrough = 0.12, Logo = rgb(254, 254, 255), HeaderIcon = rgb(247, 246, 251), Button = rgb(13, 126, 168), ButtonHover = rgb(20, 141, 186), TabActive = rgb(5, 69, 102), KnobOff = rgb(125, 138, 148), TrackOff = rgb(3, 5, 13), KnobOn = rgb(26, 149, 209), TrackOn = rgb(4, 40, 62), TrackOnStroke = rgb(5, 66, 96), SliderTrack = rgb(11, 25, 41), SliderFill = rgb(52, 110, 196), SliderKnob = rgb(78, 136, 222), Value = rgb(120, 134, 148), Name = rgb(231, 242, 252), Link = rgb(61, 149, 194), Popup = rgb(8, 18, 30), PopupHover = rgb(12, 29, 46), } -- Window metrics (pixels, measured at 1080p) local WIN_W, WIN_H = 835, 688 local WIN_RADIUS = 8 local SIDEBAR_W = 192 local CONTENT_W = WIN_W - SIDEBAR_W local HEADER_H = 69 local COL_W = 296 local ROW_H = 31 --------------------------------------------------------------------------------------------- -- Assets --------------------------------------------------------------------------------------------- local function ensureFolder(path) if not isfolder(path) then makefolder(path) end end local function download(path, url) if isfile(path) then return true end if not httpRequest then return false end local ok, res = pcall(httpRequest, { Url = url, Method = "GET" }) if ok and res and res.StatusCode == 200 and res.Body and #res.Body > 1000 then writefile(path, res.Body) return true end return false end local B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" local B64_LOOKUP = {} for i = 1, #B64 do B64_LOOKUP[B64:sub(i, i)] = i - 1 end local function base64Decode(data) data = data:gsub("[^%w%+/]", "") local out = table.create and table.create(#data) or {} local n = 0 for i = 1, #data, 4 do local a = B64_LOOKUP[data:sub(i, i)] or 0 local b = B64_LOOKUP[data:sub(i + 1, i + 1)] or 0 local c = B64_LOOKUP[data:sub(i + 2, i + 2)] local d = B64_LOOKUP[data:sub(i + 3, i + 3)] local v = a * 262144 + b * 4096 + (c or 0) * 64 + (d or 0) n += 1 out[n] = string.char(bit32.rshift(v, 16) % 256) if c then n += 1 out[n] = string.char(bit32.rshift(v, 8) % 256) end if d then n += 1 out[n] = string.char(v % 256) end end return table.concat(out, "", 1, n) end local MULISH_URL = "https://raw.githubusercontent.com/googlefonts/mulish/main/fonts/ttf/" local function loadFontFamily() local faces = { { "Regular", 400, "Mulish-Regular.ttf" }, { "Medium", 500, "Mulish-Medium.ttf" }, { "SemiBold", 600, "Mulish-SemiBold.ttf" }, { "Bold", 700, "Mulish-Bold.ttf" }, { "ExtraBold", 800, "Mulish-ExtraBold.ttf" }, } local family = { name = "NeverloseMulish", faces = {} } for _, face in ipairs(faces) do local path = ROOT .. "/fonts/" .. face[3] if download(path, MULISH_URL .. face[3]) then table.insert(family.faces, { name = face[1], weight = face[2], style = "normal", assetId = getcustomasset(path), }) end end if #family.faces == 0 then return nil end local jsonPath = ROOT .. "/fonts/mulish.json" writefile(jsonPath, HttpService:JSONEncode(family)) return getcustomasset(jsonPath) end ensureFolder(ROOT) ensureFolder(ROOT .. "/fonts") ensureFolder(ICON_DIR) -- Keep font registrations and loaded faces across menu reloads in this client session. local fontEnv = getgenv and getgenv() or {} local fontCache = fontEnv.NeverloseFontCache if type(fontCache) ~= "table" or fontCache.version ~= 1 then fontCache = { version = 1, ready = false, warmups = 0 } fontEnv.NeverloseFontCache = fontCache end local okFamily, familyId = true, fontCache.familyId if not familyId then okFamily, familyId = pcall(loadFontFamily) if okFamily then fontCache.familyId = familyId end end local function fontOf(weight) if okFamily and familyId then return Font.new(familyId, weight) end return Font.new("rbxasset://fonts/families/GothamSSm.json", weight) end local Fonts = fontCache.fonts or { Regular = fontOf(Enum.FontWeight.Regular), Medium = fontOf(Enum.FontWeight.Medium), SemiBold = fontOf(Enum.FontWeight.SemiBold), Bold = fontOf(Enum.FontWeight.Bold), ExtraBold = fontOf(Enum.FontWeight.ExtraBold), Logo = Font.new("rbxasset://fonts/families/Montserrat.json", Enum.FontWeight.ExtraBold), } fontCache.fonts = Fonts if not fontCache.ready then local textService = game:GetService("TextService") local allReady = true for name, face in pairs(Fonts) do local params = Instance.new("GetTextBoundsParams") params.Font = face params.Size = name == "Logo" and 30 or 16 params.Width = 4096 params.Text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 !?.,:;+-/%()[] °•×→" local loaded, err = pcall(function() textService:GetTextBoundsAsync(params) end) fontCache.warmups += 1 params:Destroy() if not loaded then allReady = false; fontCache.lastError = tostring(err) end end fontCache.ready = allReady end local Icons = {} local function loadIcons() for name, data in pairs(ICON_DATA) do local path = ICON_DIR .. "/" .. name .. ".png" if not isfile(path) then writefile(path, base64Decode(data)) end local ok, id = pcall(getcustomasset, path) if ok then Icons[name] = id end end end --------------------------------------------------------------------------------------------- -- Instance helpers --------------------------------------------------------------------------------------------- local function create(className, props, children) local inst = Instance.new(className) local parent = props.Parent props.Parent = nil for key, value in pairs(props) do inst[key] = value end if children then for _, child in ipairs(children) do child.Parent = inst end end if parent then inst.Parent = parent end return inst end local function corner(radius) return create("UICorner", { CornerRadius = typeof(radius) == "UDim" and radius or UDim.new(0, radius) }) end local function stroke(color, thickness) local s = create("UIStroke", { Color = color, Thickness = thickness or 1, ApplyStrokeMode = Enum.ApplyStrokeMode.Border, }) -- keep the stroke inside the frame so sizes match the reference pixel-for-pixel pcall(function() s.BorderStrokePosition = Enum.BorderStrokePosition.Inner end) return s end local function text(props) props.BackgroundTransparency = 1 props.BorderSizePixel = 0 props.TextXAlignment = props.TextXAlignment or Enum.TextXAlignment.Left props.TextYAlignment = props.TextYAlignment or Enum.TextYAlignment.Center props.FontFace = props.FontFace or Fonts.SemiBold return create("TextLabel", props) end local function icon(name, size, color, props) props = props or {} props.BackgroundTransparency = 1 props.BorderSizePixel = 0 props.Image = Icons[name .. "_" .. size] or "" props.ImageColor3 = color props.Size = UDim2.fromOffset(size, size) return create("ImageLabel", props) end local function frame(props, children) props.BorderSizePixel = 0 return create("Frame", props, children) end local function hitbox(props) props.BackgroundTransparency = 1 props.BorderSizePixel = 0 props.Text = "" props.AutoButtonColor = false return create("TextButton", props) end local function tween(inst, time, props, style) local t = TweenService:Create(inst, TweenInfo.new(time, style or Enum.EasingStyle.Quad, Enum.EasingDirection.Out), props) t:Play() return t end local function toHex(c) return string.format("#%02X%02X%02X", math.floor(c.R * 255 + 0.5), math.floor(c.G * 255 + 0.5), math.floor(c.B * 255 + 0.5)) end local function fromHex(s) s = tostring(s or ""):gsub("#", "") local r, g, b = tonumber(s:sub(1, 2), 16), tonumber(s:sub(3, 4), 16), tonumber(s:sub(5, 6), 16) if r and g and b then return Color3.fromRGB(r, g, b) end return Color3.new(1, 1, 1) end local function keyName(input) if input.UserInputType == Enum.UserInputType.Keyboard then if input.KeyCode == Enum.KeyCode.Unknown then return nil end return input.KeyCode.Name elseif input.UserInputType == Enum.UserInputType.MouseButton2 then return "MB2" elseif input.UserInputType == Enum.UserInputType.MouseButton3 then return "MB3" end return nil end local function copyValue(v) if type(v) == "table" then local t = {} for k, x in pairs(v) do t[k] = x end return t end return v end --------------------------------------------------------------------------------------------- -- Menu --------------------------------------------------------------------------------------------- local installGameAdapter = (function() -- Fighter / ClientItem runtime bridge. Older OperatorPresenter builds use their original adapters. local ShotPacket=(function() local M={} function M.read(data,key,codec) local value=data[key] if typeof(value)=='CFrame'then return value end if type(value)=='table'then return codec:DecodeCFrame(value)end end function M.write(data,key,value,codec,encoded) data[key]=value and (encoded and codec:EncodeCFrame(value)or value)or nil end return M end)() local KatanaDeflect=(function() local M={} function M.new(clock) local windows=setmetatable({},{__mode='k'}) local function katana(w)return w and (w.Name=='Katana'or w.Info and w.Info.Name=='Katana')end return { start=function(w) if katana(w)then windows[w]={hash=w._deflect_hash,expires=clock()+(tonumber(w.Info.DeflectDuration)or 0)}end end, stop=function(w)windows[w]={hash=w._deflect_hash,expires=0}end, active=function(w) if not katana(w)then return false end local window=windows[w] if window and window.hash==w._deflect_hash then return clock()0 end function M.fighter(f) if not f then return false end if M.active(f.EquippedItem)then return true end -- A holstered Riot Shield also protects its carrier's back. for _,w in pairs(f.Items or {})do if M.active(w)then return true end end return false end return M end)() return function(connect,cleanups,getValue,isMenuOpen) local Players=game:GetService('Players') local RS=game:GetService('ReplicatedStorage') local Run=game:GetService('RunService') local UIS=game:GetService('UserInputService') local Collection=game:GetService('CollectionService') local player=Players.LocalPlayer local ps=player:FindFirstChild('PlayerScripts') local controllers=ps and ps:FindFirstChild('Controllers') if not (controllers and controllers:FindFirstChild('FighterController')) then return nil end local function requireAt(root,path) for part in path:gmatch('[^/]+') do root=root and root:FindFirstChild(part) end if not root then return nil end local previous=getthreadidentity and getthreadidentity() if setthreadidentity then setthreadidentity(2)end local ok,value=pcall(require,root) if setthreadidentity and previous then setthreadidentity(previous)end return ok and value or nil end local fc=requireAt(controllers,'FighterController') local camera=requireAt(controllers,'CameraController') local mechanics=requireAt(controllers,'MechanicsController') local playerData=requireAt(controllers,'PlayerDataController') local enemies=requireAt(controllers,'EnemyController') local duels=requireAt(controllers,'DuelController') local duelLibrary=requireAt(RS,'Modules/DuelLibrary') local items=requireAt(RS,'Modules/ItemLibrary') local cosmetics=requireAt(RS,'Modules/CosmeticLibrary') local utility=requireAt(RS,'Modules/Utility') local jointsClass=requireAt(ps,'Modules/ClientReplicatedClasses/ClientFighter/ClientFighterCharacter/Joints') local vmClass=requireAt(ps,'Modules/ClientReplicatedClasses/ClientFighter/ClientItem/ClientViewModel') local gunClass=requireAt(ps,'Modules/ItemTypes/Gun') local katanaClass=requireAt(ps,'Modules/Items/Katana') local scopeClass=requireAt(ps,'Modules/ClientReplicatedClasses/ClientFighter/ClientItem/ItemInterface/Mouse/Scope') local flashClass=requireAt(ps,'Modules/ClientReplicatedClasses/ClientFighter/FighterInterface/Flashed') local smokeClass=requireAt(ps,'Modules/ClientReplicatedClasses/ClientFighter/FighterInterface/SmokeScreen') if not (fc and camera and items and vmClass and gunClass and utility) then error('Fighter runtime is not ready; re-execute after the client loads.') end local A={native=true,name='Fighter1076',thirdPerson=false,targetGroups={Head={'Head'},Body={'Body'}},skinChoices={'Original'},weaponChoices={},modelChoices={}} A.defaultFov=camera._base_fov A.mapChoices={'Select a map'} A.mapVoteSupported=duels~=nil and duelLibrary~=nil if duelLibrary and type(duelLibrary.Maps)=='table'then local names={};for name in pairs(duelLibrary.Maps)do if type(name)=='string'then table.insert(names,name)end end table.sort(names);for _,name in ipairs(names)do table.insert(A.mapChoices,name)end end local diagnostics={adapter=A.name,errors=0,skin='Original',skinApplications=0,seedSupported=false} local stopped=false local function atGameIdentity(fn) local previous=getthreadidentity and getthreadidentity() if setthreadidentity then setthreadidentity(2)end local result=table.pack(pcall(fn)) if setthreadidentity and previous then setthreadidentity(previous)end if not result[1]then error(result[2],0)end return table.unpack(result,2,result.n) end local function hook(object,name,wrap,bag) if type(object)~='table' or type(object[name])~='function' then return end local had=rawget(object,name);local original=object[name];local replacement=wrap(original) object[name]=replacement table.insert(bag or cleanups,function()if object[name]==replacement then object[name]=had end end) end local function signal() local event=Instance.new('BindableEvent') table.insert(cleanups,function()event:Destroy()end) return {Connect=function(_,fn)return event.Event:Connect(fn)end,Fire=function(_,...)event:Fire(...)end} end local function localFighter()return fc.LocalFighter end local function item()local f=localFighter();return f and f.EquippedItem end local pitchProvider local nativeCameraReplicationLoop=fc._CameraReplicationLoop A.pitchSupported=type(nativeCameraReplicationLoop)=='function'and type(utility.EncodeCameraRotation)=='function'and type(jointsClass)=='table'and type(jointsClass.Update)=='function' function A.canReplicatePitch() local f=localFighter() return f~=nil and f:Get('IsSpectating')==true and not not camera:GetPublicState() end function A.setPitchProvider(fn) local previous=pitchProvider;pitchProvider=fn return function()if pitchProvider==fn then pitchProvider=previous end end end if A.pitchSupported then hook(utility,'EncodeCameraRotation',function(original)return function(self,rotation,...) -- Only the game's periodic cosmetic camera report uses the posed pitch. -- Other encodes and all shot/camera CFrames retain the true aiming direction. if debug.info(2,'f')==nativeCameraReplicationLoop and rotation==camera.Rotation and pitchProvider then local pitch=pitchProvider() if type(pitch)=='number'then diagnostics.pitchReports=(diagnostics.pitchReports or 0)+1 rotation=Vector2.new(pitch,rotation.Y) end end return original(self,rotation,...) end end) hook(jointsClass,'Update',function(original)return function(self,dt,data,...) if self.ClientFighterCharacter.ClientFighter==localFighter()and pitchProvider and typeof(data.CameraRotationRaw)=='Vector2'then local pitch=pitchProvider() if type(pitch)=='number'then data=table.clone(data);data.CameraRotationRaw=Vector2.new(pitch,data.CameraRotationRaw.Y) end end return original(self,dt,data,...) end end) end local owners,entries={},{} local nextRefresh=0 local function refresh(force) if not force and os.clock()start and math.clamp((distance-start)/(finish-start),0,1) or (distance>start and 1 or 0) return (spec.ShootDamage or 0)*(1+((spec.RaycastDamageDropoffMultiplier or 1)-1)*blend) end function damage.Multiplier()return 1 end local gun={Fired=signal()} local beforeShot={} function A.onBeforeShot(fn) beforeShot[fn]=true;return function()beforeShot[fn]=nil end end hook(gunClass,'StartShooting',function(original)return function(self,...) if self.ClientFighter==localFighter()then for fn in pairs(beforeShot)do fn()end end return original(self,...) end end) local weapons=setmetatable({},{__mode='k'}) local function weapon() local w=item();if not w then return nil end if not weapons[w] then local wrapper={} function wrapper:TimeUntilNextPull()return math.max(0,math.max(w._shoot_cooldown or 0,w._shoot_cooldown_no_ammo or 0)-tick())end function wrapper:ReleaseTrigger()end weapons[w]=setmetatable(wrapper,{__index=function(_,key) if key=='Name' then return w.Name elseif key=='Model' then return w.ViewModel and w.ViewModel.Model elseif key=='MagAmmo' then return w:Get('Ammo') elseif key=='MaxMagSize' then return w.Info.MaxAmmo elseif key=='IsReloading' then return tick()<(w._reload_cooldown or 0) elseif key=='BurstFiring' then return false elseif key=='FireMode' then return 'auto' end end}) end return weapons[w] end setmetatable(gun,{__index=function(_,key) local f,w=localFighter(),item() if key=='Weapon' then return weapon() elseif key=='Enabled' then return f and f:IsAlive() and f:IsActive() elseif key=='AimHeld' then return w and w:Get('IsAiming') elseif key=='AimAmount' then return w and w.ViewModel and w.ViewModel.CurrentAimValue or 0 elseif key=='SwapPhase' then return w and w:IsEquipping() and 'equipping' or 'idle' elseif key=='FireHeld' then return UIS:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) elseif key=='_launcher' then return w and w.Info.IsProjectile elseif key=='_isGenericItem' then return w and w.Info.Type~='Gun' end end}) function gun:ShouldBlockWeaponInput() local f,w=localFighter(),item() return not (f and w and f:IsAlive() and f:IsActive() and camera:GetCurrentSubject()==f and atGameIdentity(function()return f:CanUseWeapon(w.Name)end)) end local function eye() local f=localFighter() return f and f.Entity and camera:GetCameraCFrame(f) or workspace.CurrentCamera.CFrame end local avatar,avatarParts,avatarSaved,avatarConnection=nil,{},{} local avatarTransparencySaved={} local avatarHiddenProvider function A.setAvatarHiddenProvider(fn) local previous=avatarHiddenProvider;avatarHiddenProvider=fn return function()if avatarHiddenProvider==fn then avatarHiddenProvider=previous end end end local function restoreAvatar() for part,value in pairs(avatarSaved)do if part.Parent then part.LocalTransparencyModifier=value if avatarTransparencySaved[part]~=nil then part.Transparency=avatarTransparencySaved[part]end end end table.clear(avatarSaved) table.clear(avatarTransparencySaved) end function A.firstPerson(owner) local r=entry(owner);local f=r and r.fighter return f and camera:GetCurrentSubject()==f and camera.CameraState:GetPublicState()=='FirstPerson' and f:IsActive()==true end function A.restoreVisibility(owner) local r=owner and entry(owner);local f=r and r.fighter or localFighter();local e=f and f.Entity if e and e.Visibility then e.Visibility:_Verify(true)end end local function enforceAvatar() local f=localFighter();local e=f and f.Entity;local model=e and e.Model if model~=avatar then restoreAvatar();if avatarConnection then avatarConnection:Disconnect()end avatar=model;table.clear(avatarParts) local function add(part)if part:IsA('BasePart')or part:IsA('Decal')then table.insert(avatarParts,part)end end if model then for _,part in ipairs(model:GetDescendants())do add(part)end avatarConnection=model.DescendantAdded:Connect(add) A.restoreVisibility() end end if A.firstPerson(player)or avatarHiddenProvider and avatarHiddenProvider()==true then for _,part in ipairs(avatarParts)do if part.Parent and part:IsDescendantOf(avatar)then if avatarSaved[part]==nil then avatarSaved[part]=part.LocalTransparencyModifier end if avatarTransparencySaved[part]==nil then avatarTransparencySaved[part]=part.Transparency end part.LocalTransparencyModifier=1 part.Transparency=1 -- The native head renderer independently resets its local modifier. elseif avatarSaved[part]~=nil then if part.Parent then part.LocalTransparencyModifier=avatarSaved[part] if avatarTransparencySaved[part]~=nil then part.Transparency=avatarTransparencySaved[part]end end avatarSaved[part]=nil avatarTransparencySaved[part]=nil end end elseif next(avatarSaved) then restoreAvatar();A.restoreVisibility()end end function A.refreshAvatarVisibility()return atGameIdentity(enforceAvatar)end table.insert(cleanups,function()atGameIdentity(function() if avatarConnection then avatarConnection:Disconnect()end restoreAvatar();A.restoreVisibility() end)end) local pov={GetEyeCFrame=eye,GetEyePosition=function()return eye().Position end} function gun:GetFireDirectionUnspread()return eye().LookVector end function gun:GetAimDirection()return self:GetFireDirectionUnspread()end function gun:GetFireDirection()return self:GetFireDirectionUnspread()end function gun:GetActiveProjectileMuzzleWorldCFrame() local w=item();local vm=w and w.ViewModel;local attachment=vm and vm:GetMuzzleAttachment() return attachment and attachment.WorldCFrame or eye() end function gun:GetMuzzleWorldPosition()return self:GetActiveProjectileMuzzleWorldCFrame().Position end function gun:_GetEffectiveBloomDeg() local f,w=localFighter(),item();if not w then return 0 end local info=w.Info local velocity=f.Entity and f.Entity.RootPart.AssemblyLinearVelocity.Magnitude or 0 local spread=(info.ShootSpread or 0)+math.min(info.ShootSpreadPerVelocityLimit or 0,velocity*(info.ShootSpreadPerVelocityUnit or 0)) return spread*math.min(w:IsFullyAiming() and (info.AimSpreadMultiplier or 1) or 1,f:IsCrouching() and .75 or 1) end function gun:StartAiming()local f=localFighter();if f then return atGameIdentity(function()return f:Input('StartAiming')end)end end function gun:StopAiming()local f=localFighter();if f then return atGameIdentity(function()return f:Input('FinishAiming')end)end end function gun:FireWeapon() if self:ShouldBlockWeaponInput() then return false end local f,w=localFighter(),item() if not (w.Info.IsRaycast and w.Info.Type=='Gun') or w:IsEquipping() or tick()0 end function bullets:PredictHit(name,origin,direction,muzzle,slack,predicate) local params=bullets.ProjectileParams() local hit=workspace:Raycast(origin,direction*10000,params) -- Native eye and muzzle must both clear the map. if hit and predicate(hit.Instance) then if muzzle and (muzzle.Position-origin).Magnitude>.1 then local clearance=workspace:Raycast(muzzle.Position,hit.Position-muzzle.Position,params) if clearance and not predicate(clearance.Instance) then return nil end end return hit.Instance end end local active=setmetatable({},{__index=function(_,key) if key=='_yawCurrent' or key=='_yawTarget' then return camera.Rotation.Y elseif key=='_pitchCurrent' or key=='_pitchTarget' then return camera.Rotation.X end end,__newindex=function(_,key,value) if key=='_yawCurrent' or key=='_yawTarget' then camera:SetRotation(Vector2.new(camera.Rotation.X,value)) elseif key=='_pitchCurrent' or key=='_pitchTarget' then camera:SetRotation(Vector2.new(value,camera.Rotation.Y)) end end}) local render={_active=active,_render=function()end} -- Mechanics owns character facing independently of the camera render pass. -- Apply the body-only pose after its final write, preserving the native movement update. hook(mechanics,'_UpdateCharacterRotation',function(original)return function(self,...) local result=table.pack(original(self,...)) if not stopped then render._render(active)end if not stopped then enforceAvatar()end return table.unpack(result,1,result.n) end end) local nativeMoveFn,nativeMoveArgs local move={SpeedMultiplier=1,GetWishDir=function() local f=localFighter() if not (nativeMoveFn and f)then return Vector3.zero end return nativeMoveFn(f,table.unpack(nativeMoveArgs or {},1,nativeMoveArgs and nativeMoveArgs.n or 0)) end} setmetatable(move,{__index=function(_,key) if key=='Velocity'then local f=localFighter();local root=f and f.Entity and f.Entity.RootPart;return root and root.AssemblyLinearVelocity or Vector3.zero end end,__newindex=function(self,key,value) if key=='Velocity'then local f=localFighter();local root=f and f.Entity and f.Entity.RootPart;if root then root.AssemblyLinearVelocity=value end else rawset(self,key,value)end end}) local lastOverride,lastPOV=camera._third_person_override,camera.CameraState._pov_state local viewOwned=false local nativeFov=workspace.CurrentCamera and workspace.CurrentCamera.FieldOfView or camera._base_fov local function gameSetting(name,fallback) if playerData then local ok,value=pcall(function()return atGameIdentity(function()return playerData:GetSetting(name)end)end);if ok and value~=nil then return value end end return fallback end A.worldStatus={requested=false,active=false,phase='first person',errors=0} local function nativeView(dt) local f,w=localFighter(),item() local requested=getValue('World/View/Thirdperson')==true local want=requested and f and f:IsAlive() and f:IsActive() and camera:GetCurrentSubject()==f if w and w.Info.AimScopePercent and w:Get('IsAiming') then want=false end if want then if not viewOwned then lastOverride=camera._third_person_override;lastPOV=camera.CameraState._pov_state;viewOwned=true end if camera._third_person_override~=true then camera:SetThirdPersonOverride(true)end if camera.CameraState._pov_state~='ThirdPerson' then camera.CameraState:_SetPOVState('ThirdPerson')end camera._pov_spring.Target=Vector3.new(1.1,.45,(tonumber(getValue('World/View/Distance')) or 120)/20) elseif viewOwned then camera:SetThirdPersonOverride(lastOverride);camera.CameraState:_SetPOVState(lastPOV or 'FirstPerson');viewOwned=false end A.thirdPerson=want==true;A.worldStatus.requested=requested;A.worldStatus.active=A.thirdPerson A.worldStatus.phase=A.thirdPerson and 'native third person' or 'first person' end hook(camera,'_Modal',function(original)return function(self,...)return isMenuOpen() or original(self,...)end end) hook(camera,'_InputChanged',function(original)return function(self,...)if not isMenuOpen()then return original(self,...)end end end) hook(camera,'Update',function(original)return function(self,dt,...) if stopped then return original(self,dt,...)end nativeView(dt) local result=table.pack(original(self,dt,...)) local cam=workspace.CurrentCamera if cam then if not self.IsFrozen and self.CameraState:GetPublicState()~=self.CameraState.States.CustomFreecam then nativeFov=cam.FieldOfView end local requestedFov=tonumber(getValue('World/View/Override FOV')) -- Apply after the native camera, so ADS, sprinting and recoil cannot alter it. if requestedFov then cam.FieldOfView=math.clamp(requestedFov,30,120)end end return table.unpack(result,1,result.n) end end) local posePending=false connect(Run.RenderStepped,function(dt) if stopped or posePending then return end;posePending=true task.defer(function() posePending=false if not stopped then render._render(active,dt);enforceAvatar()end end) end) table.insert(cleanups,function() stopped=true if viewOwned then camera:SetThirdPersonOverride(lastOverride);camera.CameraState:_SetPOVState(lastPOV or 'FirstPerson')end if workspace.CurrentCamera then workspace.CurrentCamera.FieldOfView=nativeFov end atGameIdentity(function()camera:Update(0)end) end) local boundFighter,boundItem;local fighterCleanup,itemCleanup={},{} local function clear(list)for i=#list,1,-1 do pcall(list[i]);list[i]=nil end end local lastSkinVM,lastSkinName,lastSkinInvert local shotTargetProvider,hideScopeProvider,hideShotsProvider function A.setShotTargetProvider(fn) local previous=shotTargetProvider;shotTargetProvider=fn;return function()if shotTargetProvider==fn then shotTargetProvider=previous end end end function A.setHideScopeProvider(fn) local previous=hideScopeProvider;hideScopeProvider=fn;return function()if hideScopeProvider==fn then hideScopeProvider=previous end end end function A.setHideShotsProvider(fn) local previous=hideShotsProvider;hideShotsProvider=fn;return function()if hideShotsProvider==fn then hideShotsProvider=previous end end end function A.hideShotsActive() return not stopped and hideShotsProvider~=nil and hideShotsProvider()==true end local scopeOwned=setmetatable({},{__mode='k'}) local nativeScopeActive=scopeClass and scopeClass.SetActive local function updateScope(scope) if not scope or scope._destroyed or not scope.Frame or not scope.Frame.Parent then return end if hideScopeProvider and hideScopeProvider()then scopeOwned[scope]=true;scope.Frame.Visible=false elseif scopeOwned[scope]then scopeOwned[scope]=nil;nativeScopeActive(scope,scope:IsActive())end end for _,method in ipairs({'SetActive','Update'})do hook(scopeClass,method,function(original)return function(self,...) local result=table.pack(original(self,...));updateScope(self);return table.unpack(result,1,result.n) end end) end table.insert(cleanups,function()atGameIdentity(function() for scope in pairs(scopeOwned)do if not scope._destroyed and scope.Frame.Parent then nativeScopeActive(scope,scope:IsActive())end end end)end) local visualSwap=nil local nativeGetWrap=vmClass.GetWrap local smokeParts={} local smokeEffects={} function A.scope() local w=item();local mouse=w and w.ItemInterface and w.ItemInterface.Mouse return mouse and mouse.Scope and mouse.Scope.Frame end local function skinSelection(weaponName) weaponName=weaponName or item() and item().Name local name=getValue('Skin Changer/Local/Wrap',weaponName) if getValue('Skin Changer/Local/Enabled',weaponName)~=true or name=='Original' or not (cosmetics and cosmetics.Cosmetics[name] and cosmetics.Cosmetics[name].WrapGroups) then return nil end return {Name=name,Inverted=getValue('Skin Changer/Local/Inverted',weaponName)==true} end for name in pairs(items.Items)do if items.ViewModels[name] then table.insert(A.weaponChoices,name);A.modelChoices[name]={'Original',name} end end local modelCount=0 if cosmetics then for name,info in pairs(cosmetics.Cosmetics)do if info.Type=='Skin' and A.modelChoices[info.ItemName] and items.ViewModels[name] then table.insert(A.modelChoices[info.ItemName],name);modelCount=modelCount+1 end end end table.sort(A.weaponChoices) for _,choices in pairs(A.modelChoices)do table.sort(choices,function(a,b)if a=='Original'then return true elseif b=='Original'then return false end;return a:lower().001 then ShotPacket.write(data,key,CFrame.lookAt(cf.Position,point),utility,encoded)end end data[string.char(2)]=part ShotPacket.write(data,string.char(3),offset or part.CFrame:ToObjectSpace(CFrame.new(point)),utility,encoded) -- Native local tracers pass an already sampled spread rotation. Preserve it: -- their target reference must describe the spread ray, not the center aim point. local spread=select(2,...) if typeof(spread)=='CFrame' then local cf=ShotPacket.read(data,string.char(1),utility);local params=bullets.ProjectileParams() local direction=(cf*spread).LookVector local far=cf.Position+direction*10000 local first=workspace:Raycast(cf.Position,direction*10000,params) if first then far=first.Position end local hit=workspace:Raycast(shotOrigin,far-shotOrigin,params) if hit and hit.Instance:IsA('BasePart')then data[string.char(2)]=hit.Instance ShotPacket.write(data,string.char(3),hit.Instance.CFrame:ToObjectSpace(CFrame.new(hit.Position)),utility,encoded) else data[string.char(2)]=nil;data[string.char(3)]=nil end end return data end local direction=gun:GetFireDirectionUnspread() local native=eye().LookVector if direction and (direction-native).Magnitude>1e-6 then data=table.clone(data) for _,key in ipairs({string.char(0),string.char(1)})do local cf=ShotPacket.read(data,key,utility) ShotPacket.write(data,key,CFrame.lookAt(cf.Position,cf.Position+direction),utility,encoded) end data[string.char(2)]=nil;data[string.char(3)]=nil end end return data end end,fighterCleanup) local nativeMove=f.GetMoveVector nativeMoveFn=nativeMove hook(f,'GetMoveVector',function()return function(self,...) if self~=localFighter()then return nativeMove(self,...)end local previous=nativeMoveArgs;nativeMoveArgs=table.pack(...) local result=table.pack(pcall(move.GetWishDir,move));nativeMoveArgs=previous if not result[1]then error(result[2],0)end if typeof(result[2])=='Vector3' then result[2]=result[2]*move.SpeedMultiplier end return table.unpack(result,2,result.n) end end,fighterCleanup) end end if w~=boundItem then clear(itemCleanup);boundItem=w if w and w.Shot then local c=w.Shot:Connect(function()gun.Fired:Fire()end);table.insert(itemCleanup,function()c:Disconnect()end) hook(w,'_Tracers',function(original)return function(self,data,...) if data.IsLocal and data.RaycastResults and data.RaycastResults[1] then local origin=eye().Position;local pos=data.RaycastResults[1].Position if pos then bullets.ShotEmitted:Fire(nil,origin,(pos-origin).Unit) local delta=pos-origin local hit=delta.Magnitude>.01 and workspace:Raycast(origin,delta+delta.Unit*.2,bullets.ProjectileParams()) if hit and (hit.Position-pos).Magnitude<1 then combat.LocalHit:Fire(nil,pos)end end end return original(self,data,...) end end,itemCleanup) end end local vm=w and w.ViewModel;local selected=skinSelection(w and w.Name) local name=selected and selected.Name or 'Original';local invert=selected and selected.Inverted or false if vm~=lastSkinVM or name~=lastSkinName or invert~=lastSkinInvert then if lastSkinVM and not lastSkinVM._destroyed and lastSkinVM~=vm then -- A holstered viewmodel may remain alive; restore its native wrap immediately. local old=lastSkinVM.ClientItem.ClientFighter if old==f then -- _UpdateWrap on the old model must see its native replicated cosmetic. local previous=rawget(lastSkinVM,'GetWrap') lastSkinVM.GetWrap=function(self)return nativeGetWrap(self)end local ok,err=pcall(lastSkinVM._UpdateWrap,lastSkinVM);lastSkinVM.GetWrap=previous if not ok then error(err,0)end end end lastSkinVM,lastSkinName,lastSkinInvert=vm,name,invert if vm and not vm._destroyed then vm:_UpdateWrap();diagnostics.skinApplications=diagnostics.skinApplications+1 end diagnostics.skin=name;diagnostics.weapon=w and w.Name or nil end diagnostics.model=vm and vm.Name or nil local quiet=table.find(getValue('World/Removals/Removals') or {},'Visual Recoil')~=nil if quiet then if not quietOwned then originalShake=camera._shake_enabled;quietOwned=true end camera._shake_enabled=false elseif quietOwned then camera._shake_enabled=gameSetting('Camera Shake',originalShake);quietOwned=false end local subject=camera:GetCurrentSubject() or f local mouse=subject and subject.EquippedItem and subject.EquippedItem.ItemInterface and subject.EquippedItem.ItemInterface.Mouse if mouse then updateScope(mouse.Scope)end local flash=subject and subject.FighterInterface and subject.FighterInterface.Flashed if flash then flash:_UpdateVisibility()end local hideSmoke=table.find(getValue('World/Removals/Removals') or {},'Smoke')~=nil if hideSmoke then for _,inst in ipairs(Collection:GetTagged('SmokeCloud'))do if inst:IsA('BasePart')then if smokeParts[inst]==nil then smokeParts[inst]=inst.LocalTransparencyModifier end inst.LocalTransparencyModifier=1 end local nodes=inst:GetDescendants();table.insert(nodes,inst) for _,node in ipairs(nodes)do if node:IsA('ParticleEmitter')or node:IsA('Beam')or node:IsA('Trail')or node:IsA('Smoke')or node:IsA('Fire')then if smokeEffects[node]==nil then smokeEffects[node]=node.Enabled;if node:IsA('ParticleEmitter')then node:Clear()end end node.Enabled=false end end end local screen=f and f.FighterInterface and f.FighterInterface.SmokeScreen if screen then screen:Hide()end else for part,value in pairs(smokeParts)do if part.Parent then part.LocalTransparencyModifier=value end;smokeParts[part]=nil end for node,value in pairs(smokeEffects)do if node.Parent then node.Enabled=value end;smokeEffects[node]=nil end end end local binding=false connect(Run.Heartbeat,function() if stopped or binding then return end;binding=true local ok,err=pcall(function()atGameIdentity(bind)end) binding=false if not ok then diagnostics.errors=diagnostics.errors+1;diagnostics.lastError=tostring(err);if diagnostics.errors==1 then warn('[Neverlose for RIVALS adapter] '..tostring(err))end end end) table.insert(cleanups,function()atGameIdentity(function() clear(itemCleanup);clear(fighterCleanup);if quietOwned then camera._shake_enabled=gameSetting('Camera Shake',originalShake)end restoreVisual() for _,f in pairs(fc.Objects)do local flash=f.FighterInterface and f.FighterInterface.Flashed if flash and nativeFlashVisibility then pcall(nativeFlashVisibility,flash)end end for part,value in pairs(smokeParts)do if part.Parent then part.LocalTransparencyModifier=value end end for node,value in pairs(smokeEffects)do if node.Parent then node.Enabled=value end end -- The class GetWrap hook is removed later in reverse cleanup order. Override only this VM -- during restoration, preserving native data and the original method owner. if lastSkinVM and not lastSkinVM._destroyed then local had=rawget(lastSkinVM,'GetWrap');lastSkinVM.GetWrap=function(self)return nativeGetWrap(self)end pcall(lastSkinVM._UpdateWrap,lastSkinVM);lastSkinVM.GetWrap=had end end)end) local map={ ['Shared/Participant']=participant,['Shared/Combat/Hostility']=hostility, ['Client/Controllers/MercPlayerController']=merc,['Client/Controllers/GunController']=gun, ['Client/CameraPOV']=pov,['Client/Controllers/CameraController']=render,['Client/QuakeMove']=move, ['Shared/BodyDamage']=damage,['Shared/Weapons/WeaponCartridge']={SpecFor=function(_,name)return nativeWeapons[name]end}, ['Client/Controllers/BulletController']=bullets,['Registries/Weapons']=nativeWeapons,['Registries/BulletDefs']=bulletDefs, ['Client/CombatSignals']=combat, ['Shared/Units']={StudsToMeters=function(n)return n*.28 end}, } function A.resolve(path)return map[path:gsub('^Modules/','')]end function A.status()return table.clone(diagnostics)end function A.blocked()return gun:ShouldBlockWeaponInput() and 'game input blocked' or nil end function A.poseBlocked() local f=localFighter() if not (f and f.Entity and f:IsAlive() and f:IsActive() and camera:GetCurrentSubject()==f)then return 'not active character'end if f:IsSliding() or f:IsEmoting()then return 'sliding or emoting'end end function A.nativeItem()return item()end function A.nativeFighter()return localFighter()end local function mapVoteSnapshot() local duel=duels and duels:GetDuel(player) local dueler=duel and not duel._destroyed and duel:GetDueler(player) if not dueler then return nil end local voting=duel.DuelInterface and duel.DuelInterface.Voting return {duel=duel,options=duel:Get('VoteOptions'),kind=duel:Get('VoteOptionsType'),mode=duel:Get('VoteSelectionMode'),lastVote=dueler:Get('LastVote'),open=voting and voting:IsOpen()==true} end function A.mapVoteSnapshot()return atGameIdentity(mapVoteSnapshot)end function A.voteMap(name) return atGameIdentity(function() local vote=mapVoteSnapshot() if not(vote and vote.open and vote.kind=='Maps'and type(vote.options)=='table')then return false,'not voting for maps' end if tostring(vote.mode):lower():find('ban',1,true)then return false,'map banning phase' end for _,option in pairs(vote.options)do if option.Name==name then if option.IsBanned then return false,'map banned' end if vote.lastVote==name then return true,'already voted' end RS.Remotes.Duels.Vote:FireServer(name) -- The exact request used by the native map button. return true,'requested' end end return false,'preferred map unavailable' end) end function A.character()local f=localFighter();return f and f.Entity and f.Entity.Model end refresh(true);atGameIdentity(bind);atGameIdentity(enforceAvatar) return A end end)() local installSkinPreview = (function() -- A local turntable using the exact model and wrap selected for each weapon. return function(page,adapter,Store,connect,cleanups,getValue,isMenuOpen) local Run=game:GetService('RunService') local UIS=game:GetService('UserInputService') local function make(class,props,parent) local object=Instance.new(class);for k,v in pairs(props)do object[k]=v end;object.Parent=parent;return object end local inner=page:FindFirstChild('Inner') for _,name in ipairs({'Left','Right'})do local col=inner:FindFirstChild(name);if col then col.Position=UDim2.new(col.Position.X.Scale,col.Position.X.Offset,0,318)end end local left=inner.Left local width=left.Size.X.Offset*2+11 local card=make('Frame',{Name='SkinPreview',Position=UDim2.fromOffset(20,18),Size=UDim2.fromOffset(width,282),BackgroundColor3=Color3.fromRGB(5,14,25),BorderSizePixel=0,ClipsDescendants=true},inner) make('UICorner',{CornerRadius=UDim.new(0,7)},card) make('UIStroke',{Color=Color3.fromRGB(18,43,64),Thickness=1},card) make('UIGradient',{Rotation=80,Color=ColorSequence.new(Color3.fromRGB(12,29,46),Color3.fromRGB(3,9,18))},card) local function label(value,y,size,color) return make('TextLabel',{Position=UDim2.fromOffset(18,y),Size=UDim2.new(1,-36,0,size+7),BackgroundTransparency=1,Text=value,Font=Enum.Font.GothamMedium,TextSize=size,TextColor3=color,TextXAlignment=Enum.TextXAlignment.Left,TextTruncate=Enum.TextTruncate.AtEnd,ZIndex=4},card) end label('LOCAL COLLECTION',14,10,Color3.fromRGB(81,153,205)) local title=label('Weapon preview',33,19,Color3.fromRGB(234,242,250)) local subtitle=label('',60,11,Color3.fromRGB(125,151,174)) -- Fine grid below the turntable provides depth without obscuring dark finishes. for i=0,10 do make('Frame',{Position=UDim2.new(i/10,0,0,216),Size=UDim2.fromOffset(1,65),BackgroundColor3=Color3.fromRGB(21,42,59),BackgroundTransparency=.58,BorderSizePixel=0,Rotation=(i-5)*-5},card)end for _,y in ipairs({220,234,254,279})do make('Frame',{Position=UDim2.fromOffset(0,y),Size=UDim2.new(1,0,0,1),BackgroundColor3=Color3.fromRGB(21,42,59),BackgroundTransparency=.55,BorderSizePixel=0},card)end local viewport=make('ViewportFrame',{Name='Turntable',Active=true,Position=UDim2.fromOffset(8,76),Size=UDim2.new(1,-16,0,174),BackgroundTransparency=1,Ambient=Color3.fromRGB(155,163,180),LightColor=Color3.fromRGB(255,242,221),LightDirection=Vector3.new(-.8,-1,-.7),ZIndex=3},card) local camera=make('Camera',{FieldOfView=35},viewport);viewport.CurrentCamera=camera local world=make('WorldModel',{},viewport) local hint=label('Drag to rotate / scroll to zoom',257,10,Color3.fromRGB(104,134,158)) hint.TextXAlignment=Enum.TextXAlignment.Center local status=label('',119,12,Color3.fromRGB(147,181,207));status.TextXAlignment=Enum.TextXAlignment.Center local model,signature,pending,stopped=nil,nil,false,false local yaw,pitch,zoom=-.45,.12,1 local radius=3;local drag=false;local lastMouse local generation=0 local diagnostics={builds=0,errors=0,parts=0} local function selection() local weapon=Store.contexts.skins return weapon,getValue('Skin Changer/Local/Model') or 'Original',getValue('Skin Changer/Local/Wrap') or 'Original',getValue('Skin Changer/Local/Inverted')==true end local function rebuild() local weapon,skin,wrap,inverted=selection() local key=tostring(weapon)..'|'..skin..'|'..wrap..'|'..tostring(inverted) if key==signature or pending then return end signature=key;pending=true;generation=generation+1;local ticket=generation title.Text=skin=='Original' and weapon or skin subtitle.Text=weapon..' / '..(wrap=='Original' and 'Original finish' or wrap)..(inverted and ' · Inverted' or '') status.Text='Loading model...';status.Visible=true task.spawn(function() local ok,result=pcall(adapter.preview,weapon,skin,wrap,inverted) pending=false if stopped or ticket~=generation then if ok then result:Destroy()end;return end if not ok then diagnostics.errors=diagnostics.errors+1;diagnostics.lastError=tostring(result);status.Text='Preview unavailable for this model';return end if model then model:Destroy()end;model=result;model.Parent=world local _,size=model:GetBoundingBox();radius=math.max(size.Magnitude*.5,.2) diagnostics.builds=diagnostics.builds+1;diagnostics.model=skin;diagnostics.weapon=weapon;diagnostics.wrap=wrap;diagnostics.parts=0 for _,part in ipairs(model:GetDescendants())do if part:IsA('BasePart')then diagnostics.parts=diagnostics.parts+1 end end status.Visible=false;yaw,pitch,zoom=-.45,.12,1 end) end connect(viewport.InputBegan,function(input) if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then drag=true;lastMouse=Vector2.new(input.Position.X,input.Position.Y)end end) connect(UIS.InputEnded,function(input)if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then drag=false end end) connect(viewport.InputChanged,function(input) if input.UserInputType==Enum.UserInputType.MouseWheel then zoom=math.clamp(zoom-input.Position.Z*.08,.65,1.8)end end) connect(UIS.InputChanged,function(input) if drag and (input.UserInputType==Enum.UserInputType.MouseMovement or input.UserInputType==Enum.UserInputType.Touch)then local point=Vector2.new(input.Position.X,input.Position.Y) if lastMouse then local delta=point-lastMouse;yaw=yaw-delta.X*.008;pitch=math.clamp(pitch+delta.Y*.006,-1.1,1.1)end lastMouse=point end end) connect(Run.RenderStepped,function(dt) if stopped or not page.Visible or not isMenuOpen()then drag=false;return end rebuild() if model then if not drag and getValue('Skin Changer/Preview/Auto Rotate')~=false then yaw=yaw+math.min(dt,.1)*.2 end local aspect=math.max(viewport.AbsoluteSize.X/math.max(viewport.AbsoluteSize.Y,1),.1) local half=math.rad(camera.FieldOfView*.5) local distance=radius/math.sin(math.atan(math.tan(half)*math.min(aspect,1)))*1.15*zoom local direction=Vector3.new(math.cos(yaw)*math.cos(pitch),math.sin(pitch),math.sin(yaw)*math.cos(pitch)) camera.CFrame=CFrame.lookAt(direction*distance,Vector3.zero) end end) table.insert(cleanups,function()stopped=true;generation=generation+1;if model then model:Destroy()end;card:Destroy()end) return {status=function()return table.clone(diagnostics)end} end end)() local installCustomModels = (function() -- Visual-only custom mesh rigs. Native character, hitboxes and animation tracks stay in place. local CustomRig=(function() local M={} local aliases={hips='LowerTorso',pelvis='LowerTorso',spine='LowerTorso',spine1='UpperTorso',spine2='UpperTorso',chest='UpperTorso',upperchest='UpperTorso',neck='Head',head='Head',torso='UpperTorso',root='HumanoidRootPart',rootpart='HumanoidRootPart'} local japanese={['腰']='LowerTorso',['下半身']='LowerTorso',['上半身']='UpperTorso',['上半身2']='UpperTorso',['首']='Head',['頭']='Head'} local body={'Head','UpperTorso','LowerTorso','LeftUpperArm','LeftLowerArm','LeftHand','RightUpperArm','RightLowerArm','RightHand','LeftUpperLeg','LeftLowerLeg','LeftFoot','RightUpperLeg','RightLowerLeg','RightFoot','HumanoidRootPart'} for _,name in ipairs(body)do aliases[name:lower()]=name end for _,side in ipairs({'Left','Right'})do local s=side:lower();local jp=side=='Left'and '左'or '右' for name,target in pairs({arm='UpperArm',upperarm='UpperArm',forearm='LowerArm',lowerarm='LowerArm',hand='Hand',upleg='UpperLeg',thigh='UpperLeg',upperleg='UpperLeg',leg='LowerLeg',calf='LowerLeg',lowerleg='LowerLeg',foot='Foot',toebase='Foot'})do aliases[s..name]=side..target end aliases[s..'shoulder']='UpperTorso' for name,target in pairs({['腕']='UpperArm',['ひじ']='LowerArm',['手首']='Hand',['足']='UpperLeg',['足D']='UpperLeg',['ひざ']='LowerLeg',['ひざD']='LowerLeg',['足首']='Foot',['足首D']='Foot'})do japanese[jp..name]=side..target;japanese[name..(side=='Left'and '.L'or '.R')]=side..target end japanese['肩'..(side=='Left'and '.L'or '.R')]='UpperTorso' end function M.canonical(name) if japanese[name]then return japanese[name]end local n=name:lower():gsub('[^%w]',''):gsub('^mixamorig',''):gsub('^bip001','') n=n:gsub('^jbipc',''):gsub('^jbipl','left'):gsub('^jbipr','right') return aliases[n] end function M.align(a,b) a=a.Unit;b=b.Unit local dot=math.clamp(a:Dot(b),-1,1) if dot>.999999 then return CFrame.identity end local cross=a:Cross(b) if cross.Magnitude<.00001 then cross=a:Cross(math.abs(a.Y)<.9 and Vector3.yAxis or Vector3.xAxis)end return CFrame.fromAxisAngle(cross.Unit,math.acos(dot)) end function M.source(model) local parts,rest={},{} for _,name in ipairs(body)do local p=model:FindFirstChild(name);if p and p:IsA('BasePart')then parts[name]=p end end local root=parts.HumanoidRootPart if not root then return nil end rest.HumanoidRootPart=CFrame.identity local links={} for _,joint in ipairs(model:GetDescendants())do if joint:IsA('Motor6D')or joint:IsA('AnimationConstraint')then local ok,p0,p1,c0,c1=pcall(function()return joint.Part0,joint.Part1,joint.C0,joint.C1 end) if ok and p0 and p1 then if joint.Name=='Waist'or joint.Name=='Neck'then c0=CFrame.new(c0.Position);c1=CFrame.new(c1.Position)end table.insert(links,{p0.Name,p1.Name,c0,c1}) end end end for _=1,18 do for _,j in ipairs(links)do if rest[j[1]]and not rest[j[2]]then rest[j[2]]=rest[j[1]]*j[3]*j[4]:Inverse()end end end for name,p in pairs(parts)do if not rest[name]then rest[name]=root.CFrame:ToObjectSpace(p.CFrame)end end return {model=model,root=root,parts=parts,rest=rest} end function M.sanitize(model) local collection=game:GetService('CollectionService') local remove={} for _,n in ipairs(model:GetDescendants())do for _,tag in ipairs(collection:GetTags(n))do collection:RemoveTag(n,tag)end if n:IsA('LuaSourceContainer')or n:IsA('Humanoid')or n:IsA('AnimationController')or n:IsA('Animator')or n:IsA('RemoteEvent')or n:IsA('RemoteFunction')or n:IsA('ProximityPrompt')or n:IsA('ClickDetector')or n:IsA('TouchTransmitter')or n:IsA('Sound')or n:IsA('LayerCollector')then table.insert(remove,n) elseif n:IsA('BasePart')then n.Anchored=true;n.CanCollide=false;n.CanTouch=false;n.CanQuery=false;n.Massless=true;n.LocalTransparencyModifier=0 if n.Name=='HumanoidRootPart'or n.Name=='RootPart'then n.Transparency=1 end end end for _,n in ipairs(remove)do n:Destroy()end end function M.build(template,height,scale) local model=template:Clone() local ok,result=pcall(function() M.sanitize(model) local _,size=model:GetBoundingBox() assert(size.Y>.01,'The model has no visible geometry') local factor=height/size.Y*scale assert(factor>0 and factor<100000,'Invalid model dimensions') model:ScaleTo(model:GetScale()*factor) local box,scaled=model:GetBoundingBox() local origin=CFrame.new(box.Position.X,box.Position.Y-scaled.Y*.5+scaled.Y*.53,box.Position.Z) local r={model=model,parts={},bones={},followers={},effects={},mapped=0,origin=origin,height=scaled.Y,joints=0} local byPart,links={},{} for _,n in ipairs(model:GetDescendants())do if n:IsA('AnimationConstraint')then local good,p0,p1,c0,c1=pcall(function()return n.Part0,n.Part1,n.C0,n.C1 end) if good and p0 and p1 then local motor=Instance.new('Motor6D');motor.Name=n.Name;motor.Part0=p0;motor.Part1=p1;motor.C0=c0;motor.C1=c1;motor.Parent=p0 end n:Destroy() end end for _,n in ipairs(model:GetDescendants())do if n:IsA('BasePart')then local p={part=n,bind=origin:ToObjectSpace(n.CFrame),name=M.canonical(n.Name)} byPart[n]=p;table.insert(r.parts,p) elseif n:IsA('JointInstance')or n:IsA('AnimationConstraint')then local good,p0,p1,c0,c1=pcall(function()return n.Part0,n.Part1,n.C0,n.C1 end) if good and p0 and p1 then links[p1]={parent=p0,c0=c0,c1=c1,joint=n};r.joints=r.joints+1 end elseif n:IsA('WeldConstraint')then if n.Part0 and n.Part1 then links[n.Part1]={parent=n.Part0,offset=n.Part0.CFrame:ToObjectSpace(n.Part1.CFrame),joint=n};r.joints=r.joints+1 end elseif n:IsA('ParticleEmitter')or n:IsA('Beam')or n:IsA('Trail')or n:IsA('Light')then table.insert(r.effects,{object=n,enabled=n.Enabled}) end end local function depth(p,seen) seen=seen or {};if seen[p]then return 0 end;seen[p]=true local link=links[p];return link and byPart[link.parent]and 1+depth(link.parent,seen)or 0 end for _,p in ipairs(r.parts)do p.link=links[p.part];p.depth=depth(p.part);if p.name and p.name~='HumanoidRootPart'then r.mapped=r.mapped+1 end end table.sort(r.parts,function(a,b)return a.depthprimary.score or group.score==primary.score and #group.bones>#primary.bones then primary=group end end local drivers={} if primary then for _,group in pairs(groups)do if group~=primary then local matches={} for _,b in ipairs(group.bones)do local driver=primary.names[b.bone.Name] if driver then b.driver=driver;table.insert(matches,b)end end if #matches>0 then for _,b in ipairs(matches)do drivers[b.bone]=b.driver;table.insert(r.followers,b)end -- One anchored assembly and one pose clock for body, clothing and separate hair rigs. local part=byPart[group.root] if part and not part.link then local offset=primary.root.CFrame:ToObjectSpace(group.root.CFrame) local weld=Instance.new('Weld');weld.Name='CustomRigCompanion';weld.Part0=primary.root;weld.Part1=group.root;weld.C0=offset;weld.C1=CFrame.identity;weld.Parent=primary.root part.link={parent=primary.root,c0=offset,c1=CFrame.identity,joint=weld} r.joints=r.joints+1 end end end end end for _,b in ipairs(r.bones)do b.driver=drivers[b.bone]end table.sort(r.followers,function(a,b)return a.depth=3 then p.boneDriven=true;break end cursor=cursor.link and byPart[cursor.link.parent] end end table.sort(r.bones,function(a,b)return a.depth=3,'No supported body rig found. Use R15, Mixamo, VRM or MMD bone names.') -- Shared skinned meshes find their skeleton through the imported rigid joints. -- Keep those connections and anchor each assembly root instead of every mesh. for _,p in ipairs(r.parts)do p.part.Anchored=not (p.link and p.link.joint and (p.link.joint:IsA('JointInstance')or p.link.joint:IsA('WeldConstraint'))) end for _,n in ipairs(model:GetDescendants())do if n:IsA('Constraint')and not n:IsA('WeldConstraint')then n:Destroy()end end return r end) if not ok then model:Destroy();error(result,0)end return result end function M.visible(r,show) for _,p in ipairs(r.parts)do p.part.LocalTransparencyModifier=show and 0 or 1 end for _,e in ipairs(r.effects)do e.object.Enabled=show and e.enabled or false end end function M.pose(r,source,anchor) local deltas={} local sourceFrame=source and source.root.CFrame if source then for name,p in pairs(source.parts)do if p.Parent then deltas[name]=sourceFrame:ToObjectSpace(p.CFrame).Rotation*source.rest[name].Rotation:Inverse()end end end for _,p in ipairs(r.parts)do local link=p.link -- Static skinned carriers inherit the anchored root through their existing joints. -- Rewriting their CFrames/near-identity Motor6D transforms causes separate skin rebuilds. if not link or not p.boneDriven and p.name and p.name~='HumanoidRootPart'then if p.rest~= (source and source.rest)then p.neutral=nil end if not p.neutral then local rest=source and source.rest[p.name]or CFrame.identity p.neutral=p.direction and M.align(p.direction,rest:VectorToWorldSpace(-Vector3.yAxis))*p.bind.Rotation or p.bind.Rotation p.rest=source and source.rest end local rotation=anchor.Rotation*(deltas[p.name]or CFrame.identity)*p.neutral if link and link.parent.Parent then if link.c0 then local pivot=link.parent.CFrame*link.c0 p.part.CFrame=CFrame.new(pivot.Position-rotation:VectorToWorldSpace(link.c1.Position))*rotation else p.part.CFrame=link.parent.CFrame*link.offset end else p.part.CFrame=anchor*p.bind end if p.name and not link then p.part.CFrame=CFrame.new(p.part.Position)*rotation end if link and link.joint and link.joint:IsA('Motor6D')then link.joint.Transform=link.c0:Inverse()*link.parent.CFrame:ToObjectSpace(p.part.CFrame)*link.c1 end end end for _,b in ipairs(r.bones)do if not b.driver then local bone=b.bone;local parent=bone.Parent local parentFrame=parent:IsA('Bone')and parent.TransformedWorldCFrame or parent.CFrame local base=parentFrame*bone.CFrame if b.direction and b.rest~= (source and source.rest)then b.neutral=nil end if not b.neutral then local rest=source and source.rest[b.name]or CFrame.identity b.neutral=b.direction and M.align(b.direction,rest:VectorToWorldSpace(-Vector3.yAxis))*b.bind.Rotation or b.bind.Rotation b.rest=source and source.rest end local rotation=anchor.Rotation*(deltas[b.name]or CFrame.identity)*b.neutral bone.Transform=base:ToObjectSpace(CFrame.new(base.Position)*rotation) end end for _,b in ipairs(r.followers)do local parent=b.bone.Parent local frame=parent:IsA('Bone')and parent.TransformedWorldCFrame or parent.CFrame b.bone.Transform=(frame*b.bone.CFrame):ToObjectSpace(b.driver.TransformedWorldCFrame) end end return M end)() return function(page,adapter,getValue,connect,cleanups,isMenuOpen,notify) local Run=game:GetService('RunService') local UIS=game:GetService('UserInputService') local player=game:GetService('Players').LocalPlayer if isfolder and makefolder and not isfolder('neverlose_ui/models')then pcall(makefolder,'neverlose_ui/models')end local function get(path)return getValue('Model Changer/'..path)end local stopped,pending,template,signature,requested=false,false,nil,nil,nil local generation,revision=0,0 local live,preview,source,liveKey,previewKey,boundCharacter local hidden=false local diagnostics={phase='disabled',errors=0,parts=0,bones=0,mapped=0,loads=0,localOnly=true} local folder=Instance.new('Folder');folder.Name='NeverloseCustomVisuals';folder.Parent=workspace table.insert(cleanups,adapter.setAvatarHiddenProvider(function()return hidden end)) table.insert(cleanups,adapter.setLocalVisualProvider(function()return hidden and live and live.model or nil end)) local function destroyRig(r)if r then r.model:Destroy()end end local function resetLive() hidden=false;destroyRig(live);live=nil;liveKey=nil adapter.refreshAvatarVisibility() end local function assetKey() local mode=get('Selection/Source') local value=mode=='Anime Example'and '6669297625'or mode=='Local File'and tostring(get('Selection/File')or '')or tostring(get('Selection/Asset ID')or '') return mode..':'..value,mode,value end local function loadAsset(mode,value) local uri if mode=='Local File'then assert(type(getcustomasset)=='function','Local model files are unavailable in this executor') assert(value:lower():match('%.rbxm$')or value:lower():match('%.rbxmx$'),'Choose a .rbxm or .rbxmx model file') assert(isfile(value),'Model file not found in executor workspace: '..value) uri=getcustomasset(value) else local id=value:match('^%s*(%d+)%s*$')or value:match('rbxassetid://(%d+)')or value:match('/asset/(%d+)')or value:match('[?&]id=(%d+)') assert(id and tonumber(id)>0,'Enter a model asset ID or Creator Store model link') uri='rbxassetid://'..id end local prior=getthreadidentity and getthreadidentity() if setthreadidentity then setthreadidentity(8)end local ok,objects=pcall(function()return game:GetObjects(uri)end) if setthreadidentity and prior then setthreadidentity(prior)end assert(ok,objects) local group=Instance.new('Model');group.Name='Custom Character' for _,object in ipairs(objects)do CustomRig.sanitize(object);object.Parent=group end local count=0;for _,p in ipairs(group:GetDescendants())do if p:IsA('BasePart')then count=count+1 end end if count==0 or count>400 then group:Destroy();error('Choose a character model with 1–400 parts',0)end return group end local function request(force) local key,mode,value=assetKey() if not force and key==requested then return end requested=key;generation=generation+1;local ticket=generation;pending=true diagnostics.phase='loading';diagnostics.lastError=nil task.spawn(function() local ok,result=pcall(function() local model=loadAsset(mode,value) local valid,rig=pcall(CustomRig.build,model,5.5,1) if not valid then model:Destroy();error(rig,0)end rig.model:Destroy();return model end) if stopped or ticket~=generation then if ok then result:Destroy()end;return end pending=false if not ok then diagnostics.errors=diagnostics.errors+1;diagnostics.lastError=tostring(result);diagnostics.phase='load failed' notify('Model Changer',tostring(result));return end if template then template:Destroy()end template=result;signature=key;revision=revision+1;diagnostics.loads=diagnostics.loads+1 diagnostics.name=mode=='Anime Example'and 'YYB Hatsune Miku'or mode=='Local File'and value:match('[^/\\]+$')or 'Custom asset '..value end) end local function bodyHeight(s) if not s then return 5.5 end if s.height then return s.height end local lo,hi=math.huge,-math.huge for name,p in pairs(s.parts)do if name~='HumanoidRootPart'then local y=s.rest[name].Position.Y;lo=math.min(lo,y-p.Size.Y*.5);hi=math.max(hi,y+p.Size.Y*.5) end end s.height=hi>lo and hi-lo or 5.5 return s.height end local make=function(class,props,parent)local o=Instance.new(class);for k,v in pairs(props)do o[k]=v end;o.Parent=parent;return o end local inner=page.Inner for _,name in ipairs({'Left','Right'})do local col=inner[name];col.Position=UDim2.new(col.Position.X.Scale,col.Position.X.Offset,0,318)end local width=inner.Left.Size.X.Offset*2+11 local card=make('Frame',{Name='CustomModelPreview',Position=UDim2.fromOffset(20,18),Size=UDim2.fromOffset(width,282),BackgroundColor3=Color3.fromRGB(5,14,25),BorderSizePixel=0,ClipsDescendants=true},inner) make('UICorner',{CornerRadius=UDim.new(0,7)},card) make('UIStroke',{Color=Color3.fromRGB(18,43,64)},card) local function label(text,y,size,color)return make('TextLabel',{Position=UDim2.fromOffset(18,y),Size=UDim2.new(1,-36,0,size+8),BackgroundTransparency=1,Text=text,Font=Enum.Font.GothamMedium,TextSize=size,TextColor3=color,TextXAlignment=Enum.TextXAlignment.Left,ZIndex=4},card)end label('CUSTOM CHARACTER / LOCAL VISUAL',12,10,Color3.fromRGB(81,153,205)) local title=label('Custom model preview',31,18,Color3.fromRGB(234,242,250)) local statusLabel=label('Choose a model asset or local rig file',58,11,Color3.fromRGB(136,163,185)) local view=make('ViewportFrame',{Active=true,Position=UDim2.fromOffset(8,78),Size=UDim2.new(1,-16,0,171),BackgroundTransparency=1,Ambient=Color3.fromRGB(175,175,188),LightColor=Color3.fromRGB(255,245,235),LightDirection=Vector3.new(-.6,-1,-.6)},card) local camera=make('Camera',{FieldOfView=35},view);view.CurrentCamera=camera local world=make('WorldModel',{},view) local hint=label('Drag to rotate / scroll to zoom',256,10,Color3.fromRGB(104,134,158));hint.TextXAlignment=Enum.TextXAlignment.Center local yaw,pitch,zoom,drag,lastMouse=-math.pi*.5,.08,1,false,nil connect(view.InputBegan,function(input)if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then drag=true;lastMouse=Vector2.new(input.Position.X,input.Position.Y)end end) connect(UIS.InputEnded,function(input)if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then drag=false end end) connect(view.InputChanged,function(input)if input.UserInputType==Enum.UserInputType.MouseWheel then zoom=math.clamp(zoom-input.Position.Z*.08,.6,2)end end) connect(UIS.InputChanged,function(input)if drag and (input.UserInputType==Enum.UserInputType.MouseMovement or input.UserInputType==Enum.UserInputType.Touch)then local point=Vector2.new(input.Position.X,input.Position.Y);local d=point-lastMouse;lastMouse=point;yaw=yaw-d.X*.008;pitch=math.clamp(pitch+d.Y*.006,-1,1) end end) local function update(dt) if stopped then return end local native=adapter.character() if native~=boundCharacter or source and not source.root.Parent or not source and native and native:FindFirstChild('HumanoidRootPart')then boundCharacter=native;source=native and CustomRig.source(native)or nil;liveKey=nil;previewKey=nil end local showPreview=page.Visible and isMenuOpen() local enabled=get('Selection/Enabled')==true if enabled or showPreview then request(false)end local scale=math.clamp(tonumber(get('Fitting/Scale'))or 100,25,250)/100 local height=bodyHeight(source) local key=tostring(revision)..':'..scale..':'..string.format('%.2f',height) local facing=CFrame.Angles(0,math.rad(tonumber(get('Fitting/Facing'))or 0),0) local offset=CFrame.new(0,(tonumber(get('Fitting/Height'))or 0)/100,0)*facing if enabled and template and source and source.model.Parent then if liveKey~=key then local new=CustomRig.build(template,height,scale);new.model.Name='NeverloseCustomCharacter';new.model.Parent=folder destroyRig(live);live=new;liveKey=key end local fp=adapter.firstPerson(player)==true CustomRig.pose(live,source,source.root.CFrame*offset) CustomRig.visible(live,not fp) hidden=true;adapter.refreshAvatarVisibility() diagnostics.parts=#live.parts;diagnostics.bones=#live.bones;diagnostics.mapped=live.mapped;diagnostics.sharedBones=#live.followers diagnostics.phase=fp and 'first person hidden'or pending and 'loading'or 'active' elseif live then resetLive()end if not enabled and not pending then diagnostics.phase='disabled'end if showPreview and template then if previewKey~=key then local new=CustomRig.build(template,height,scale);new.model.Parent=world;destroyRig(preview);preview=new;previewKey=key end CustomRig.pose(preview,source,offset) if not drag and get('Preview/Auto Rotate')~=false then yaw=yaw+math.min(dt,.1)*.25 end local radius=math.max(height*scale*.65,1) local aspect=math.max(view.AbsoluteSize.X/math.max(view.AbsoluteSize.Y,1),.1) local half=math.atan(math.tan(math.rad(camera.FieldOfView*.5))*math.min(aspect,1)) local direction=Vector3.new(math.cos(yaw)*math.cos(pitch),math.sin(pitch),math.sin(yaw)*math.cos(pitch)) local center=Vector3.new(0,-height*scale*.03,0) camera.CFrame=CFrame.lookAt(center+direction*radius/math.sin(half)*zoom,center) end title.Text=diagnostics.name or 'Custom model preview' statusLabel.Text=diagnostics.lastError and diagnostics.lastError:sub(1,115)or pending and 'Loading custom mesh rig…'or live and (#live.parts..' mesh parts · '..#live.bones..' body bones · '..diagnostics.phase)or 'Preview only · enable to replace your local appearance' end local binding='NeverloseCustomModel'..tostring(math.random(100000,999999)) Run:BindToRenderStep(binding,Enum.RenderPriority.Last.Value+3,function(dt) local ok,err=pcall(update,dt) if not ok then diagnostics.errors=diagnostics.errors+1;diagnostics.lastError=tostring(err);diagnostics.phase='model error';resetLive() if diagnostics.errors==1 then warn('[Model Changer] '..tostring(err))end end end) table.insert(cleanups,function() stopped=true;generation=generation+1;Run:UnbindFromRenderStep(binding);resetLive();destroyRig(preview) if template then template:Destroy()end;folder:Destroy();card:Destroy() end) return {status=function()return table.clone(diagnostics)end,reload=function()request(true)end} end end)() local installLiveESP = (function() -- Conservative screen-space occlusion regions. Never bridge visible cells. local OcclusionMask=(function() local M={} function M.rectangles(grid,cols,rows,limit) local cells={};for i,v in ipairs(grid) do cells[i]=v==true end local result={} for _=1,limit do local heights={};for x=1,cols do heights[x]=0 end local best,area=nil,0 for y=1,rows do for x=1,cols do heights[x]=cells[(y-1)*cols+x] and heights[x]+1 or 0 end local stack={} for x=1,cols+1 do local height=x<=cols and heights[x] or 0 local left=x while #stack>0 and stack[#stack].height>height do local item=table.remove(stack);left=item.left local size=item.height*(x-item.left) if size>area then area=size;best={item.left,y-item.height+1,x-1,y} end end if height>0 and (#stack==0 or stack[#stack].height