local w=require(script.Parent:WaitForChild("\066\097\115\101\067\104\097\114\097\099\116\101\114\067\111\110\116\114\111\108\108\101\114"))local n=setmetatable({},w)n.__index=n function n.new(N)local X=setmetatable(w.new(),n)X.CONTROL_ACTION_PRIORITY=N X.navigationRequestedConn=nil X.heartbeatConn=nil X.currentDestination=nil X.currentPath=nil X.currentPoints=nil X.currentPointIdx=0 X.expectedTimeToNextPoint=0 X.timeReachedLastPoint=tick()X.moving=false X.isJumpBound=false X.moveLatch=false X.userCFrameEnabledConn=nil return X end function n.SetLaserPointerMode(n,w)pcall(function()StarterGui:SetCore("\086\082\076\097\115\101\114\080\111\105\110\116\101\114\077\111\100\101",w)end)end function n.GetLocalHumanoid(w)local n=LocalPlayer.Character if not n then return end for w,n in pairs(n:GetChildren())do if n:IsA("\072\117\109\097\110\111\105\100")then return n end end return nil end function n.HasBothHandControllers(w)return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand)and VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)end function n.HasAnyHandControllers(w)return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand)or VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)end function n.IsMobileVR(w)return UserInputService.TouchEnabled end function n.HasGamepad(w)return UserInputService.GamepadEnabled end function n.ShouldUseNavigationLaser(w)if w:IsMobileVR()then return true else if w:HasBothHandControllers()then return false end if not w:HasAnyHandControllers()then return not w:HasGamepad()end return true end end function n.StartFollowingPath(n,w)currentPath=w currentPoints=currentPath:GetPointCoordinates()currentPointIdx=1 moving=true timeReachedLastPoint=tick()local N=n:GetLocalHumanoid()if N and(N.Torso and#currentPoints>=1)then local w=(currentPoints[1]-N.Torso.Position).magnitude expectedTimeToNextPoint=w/N.WalkSpeed end movementUpdateEvent:Fire("\116\097\114\103\101\116\080\111\105\110\116",n.currentDestination)end function n.GoToPoint(n,w)currentPath=true currentPoints={w}currentPointIdx=1 moving=true local N=n:GetLocalHumanoid()local X=(N.Torso.Position-w).magnitude local t=X/N.WalkSpeed timeReachedLastPoint=tick()expectedTimeToNextPoint=t movementUpdateEvent:Fire("\116\097\114\103\101\116\080\111\105\110\116",w)end function n.StopFollowingPath(w)currentPath=nil currentPoints=nil currentPointIdx=0 moving=false w.moveVector=ZERO_VECTOR3 end function n.TryComputePath(N,w,n)local X=0 local t=nil while not t and X<5 do t=PathfindingService:ComputeSmoothPathAsync(w,n,MAX_PATHING_DISTANCE)X=X+1 if t.Status==Enum.PathStatus.ClosestNoPath or t.Status==Enum.PathStatus.ClosestOutOfRange then t=nil break end if t and t.Status==Enum.PathStatus.FailStartNotEmpty then w=w+(n-w).unit t=nil end if t and t.Status==Enum.PathStatus.FailFinishNotEmpty then n=n+Vector3.new(0,1,0)t=nil end end return t end function n.OnNavigationRequest(N,w,n)local X=w.p local t=N.currentDestination if not IsFiniteVector3(X)then return end N.currentDestination=X local H=N:GetLocalHumanoid()if not H or not H.Torso then return end local q=H.Torso.Position local R=(N.currentDestination-q).magnitude if R<NO_PATH_THRESHOLD then N:GoToPoint(N.currentDestination)return end if not t or(N.currentDestination-t).magnitude>RECALCULATE_PATH_THRESHOLD then local w=N:TryComputePath(q,N.currentDestination)if w then N:StartFollowingPath(w)if PathDisplay then PathDisplay.setCurrentPoints(N.currentPoints)PathDisplay.renderPath()end else N:StopFollowingPath()if PathDisplay then PathDisplay.clearRenderedPath()end end else if moving then N.currentPoints[#currentPoints]=N.currentDestination else N:GoToPoint(N.currentDestination)end end end function n.OnJumpAction(X,w,n,N)if n==Enum.UserInputState.Begin then X.isJumping=true end return Enum.ContextActionResult.Sink end function n.BindJumpAction(n,w)if w then if not n.isJumpBound then n.isJumpBound=true ContextActionService:BindActionAtPriority("\086\082\074\117\109\112\065\099\116\105\111\110",function()return n:OnJumpAction()end,false,n.CONTROL_ACTION_PRIORITY,Enum.KeyCode.ButtonA)end else if n.isJumpBound then n.isJumpBound=false ContextActionService:UnbindAction("\086\082\074\117\109\112\065\099\116\105\111\110")end end end function n.ControlCharacterGamepad(X,w,n,N)if N.KeyCode~=Enum.KeyCode.Thumbstick1 then return end if n==Enum.UserInputState.Cancel then X.moveVector=ZERO_VECTOR3 return end if n~=Enum.UserInputState.End then X:StopFollowingPath()if PathDisplay then PathDisplay.clearRenderedPath()end if X:ShouldUseNavigationLaser()then X:BindJumpAction(true)X:SetLaserPointerMode("\072\105\100\100\101\110")end if N.Position.magnitude>THUMBSTICK_DEADZONE then X.moveVector=Vector3.new(N.Position.X,0,-N.Position.Y)if X.moveVector.magnitude>0 then X.moveVector=X.moveVector.unit*math.min(1,N.Position.magnitude)end X.moveLatch=true end else X.moveVector=ZERO_VECTOR3 if X:ShouldUseNavigationLaser()then X:BindJumpAction(false)X:SetLaserPointerMode("\078\097\118\105\103\097\116\105\111\110")end if X.moveLatch then X.moveLatch=false movementUpdateEvent:Fire("\111\102\102\116\114\097\099\107")end end return Enum.ContextActionResult.Sink end function n.OnHeartbeat(n,w)local N=n.moveVector local X=n:GetLocalHumanoid()if not X or not X.Torso then return end if n.moving and n.currentPoints then local t=X.Torso.Position local H=currentPoints[1]local q=(H-t)*XZ_VECTOR3 local R=q.magnitude local d=q/R if R<POINT_REACHED_THRESHOLD then local w=0 local N=currentPoints[1]for n,t in pairs(currentPoints)do if n~=1 then local n=(t-N).magnitude N=t w=w+n/X.WalkSpeed end end table.remove(currentPoints,1)currentPointIdx=currentPointIdx+1 if#currentPoints==0 then n:StopFollowingPath()if PathDisplay then PathDisplay.clearRenderedPath()end return else if PathDisplay then PathDisplay.setCurrentPoints(currentPoints)PathDisplay.renderPath()end local w=currentPoints[1]local n=(w-t).magnitude expectedTimeToNextPoint=n/X.WalkSpeed timeReachedLastPoint=tick()end else local H={game.Players.LocalPlayer.Character;workspace.CurrentCamera}local q=Ray.new(t-Vector3.new(0,1,0),d*3)local R,p,B=workspace:FindPartOnRayWithIgnoreList(q,H)if R then local w=Vector3.new(0,100,0)local n=Ray.new((p+d*.5)+w,-w)local N,q,R=workspace:FindPartOnRayWithIgnoreList(n,H)local B=q.Y-t.Y if B<6 and B>-2 then X.Jump=true end end local T=tick()-timeReachedLastPoint if T>expectedTimeToNextPoint+OFFTRACK_TIME_THRESHOLD then n:StopFollowingPath()if PathDisplay then PathDisplay.clearRenderedPath()end movementUpdateEvent:Fire("\111\102\102\116\114\097\099\107")end N=n.moveVector:Lerp(d,w*10)end end if IsFiniteVector3(N)then n.moveVector=N end end function n.OnUserCFrameEnabled(w)if w:ShouldUseNavigationLaser()then w:BindJumpAction(false)w:SetLaserPointerMode("\078\097\118\105\103\097\116\105\111\110")else w:BindJumpAction(true)w:SetLaserPointerMode("\072\105\100\100\101\110")end end function n.Enable(n,w)n.moveVector=ZERO_VECTOR3 n.isJumping=false if w then n.navigationRequestedConn=VRService.NavigationRequested:Connect(function(w,N)n:OnNavigationRequest(w,N)end)n.heartbeatConn=RunService.Heartbeat:Connect(function(w)n:OnHeartbeat(w)end)ContextActionService:BindAction("\077\111\118\101\084\104\117\109\098\115\116\105\099\107",function(w,N,X)return n:ControlCharacterGamepad(w,N,X)end,false,n.CONTROL_ACTION_PRIORITY,Enum.KeyCode.Thumbstick1)ContextActionService:BindActivate(Enum.UserInputType.Gamepad1,Enum.KeyCode.ButtonR2)n.userCFrameEnabledConn=VRService.UserCFrameEnabled:Connect(function()n:OnUserCFrameEnabled()end)n:OnUserCFrameEnabled()VRService:SetTouchpadMode(Enum.VRTouchpad.Left,Enum.VRTouchpadMode.VirtualThumbstick)VRService:SetTouchpadMode(Enum.VRTouchpad.Right,Enum.VRTouchpadMode.ABXY)n.enabled=true else n:StopFollowingPath()ContextActionService:UnbindAction("\077\111\118\101\084\104\117\109\098\115\116\105\099\107")ContextActionService:UnbindActivate(Enum.UserInputType.Gamepad1,Enum.KeyCode.ButtonR2)n:BindJumpAction(false)n:SetLaserPointerMode("\068\105\115\097\098\108\101\100")if n.navigationRequestedConn then n.navigationRequestedConn:Disconnect()n.navigationRequestedConn=nil end if n.heartbeatConn then n.heartbeatConn:Disconnect()n.heartbeatConn=nil end if n.userCFrameEnabledConn then n.userCFrameEnabledConn:Disconnect()n.userCFrameEnabledConn=nil end n.enabled=false end end return n
--
local BaseCharacterController = require(script.Parent:WaitForChild("BaseCharacterController"))
local VRNavigation = setmetatable({}, BaseCharacterController)
VRNavigation.__index = VRNavigation

function VRNavigation.new(CONTROL_ACTION_PRIORITY)
	local self = setmetatable(BaseCharacterController.new(), VRNavigation)

	self.CONTROL_ACTION_PRIORITY = CONTROL_ACTION_PRIORITY

	self.navigationRequestedConn = nil
	self.heartbeatConn = nil

	self.currentDestination = nil
	self.currentPath = nil
	self.currentPoints = nil
	self.currentPointIdx = 0

	self.expectedTimeToNextPoint = 0
	self.timeReachedLastPoint = tick()
	self.moving = false

	self.isJumpBound = false
	self.moveLatch = false

	self.userCFrameEnabledConn = nil

	return self
end

function VRNavigation:SetLaserPointerMode(mode)
	pcall(function()
		StarterGui:SetCore("VRLaserPointerMode", mode)
	end)
end

function VRNavigation:GetLocalHumanoid()
	local character = LocalPlayer.Character
	if not character then
		return
	end

	for _, child in pairs(character:GetChildren()) do
		if child:IsA("Humanoid") then
			return child
		end
	end
	return nil
end

function VRNavigation:HasBothHandControllers()
	return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand) and VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)
end

function VRNavigation:HasAnyHandControllers()
	return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand) or VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)
end

function VRNavigation:IsMobileVR()
	return UserInputService.TouchEnabled
end

function VRNavigation:HasGamepad()
	return UserInputService.GamepadEnabled
end

function VRNavigation:ShouldUseNavigationLaser()
	--Places where we use the navigation laser:
	-- mobile VR with any number of hands tracked
	-- desktop VR with only one hand tracked
	-- desktop VR with no hands and no gamepad (i.e. with Oculus remote?)
	--using an Xbox controller with a desktop VR headset means no laser since the user has a thumbstick.
	--in the future, we should query thumbstick presence with a features API
	if self:IsMobileVR() then
		return true
	else
		if self:HasBothHandControllers() then
			return false
		end
		if not self:HasAnyHandControllers() then
			return not self:HasGamepad()
		end
		return true
	end
end



function VRNavigation:StartFollowingPath(newPath)
	currentPath = newPath
	currentPoints = currentPath:GetPointCoordinates()
	currentPointIdx = 1
	moving = true

	timeReachedLastPoint = tick()

	local humanoid = self:GetLocalHumanoid()
	if humanoid and humanoid.Torso and #currentPoints >= 1 then
		local dist = (currentPoints[1] - humanoid.Torso.Position).magnitude
		expectedTimeToNextPoint = dist / humanoid.WalkSpeed
	end

	movementUpdateEvent:Fire("targetPoint", self.currentDestination)
end

function VRNavigation:GoToPoint(point)
	currentPath = true
	currentPoints = { point }
	currentPointIdx = 1
	moving = true

	local humanoid = self:GetLocalHumanoid()
	local distance = (humanoid.Torso.Position - point).magnitude
	local estimatedTimeRemaining = distance / humanoid.WalkSpeed

	timeReachedLastPoint = tick()
	expectedTimeToNextPoint = estimatedTimeRemaining

	movementUpdateEvent:Fire("targetPoint", point)
end

function VRNavigation:StopFollowingPath()
	currentPath = nil
	currentPoints = nil
	currentPointIdx = 0
	moving = false
	self.moveVector = ZERO_VECTOR3
end

function VRNavigation:TryComputePath(startPos, destination)
	local numAttempts = 0
	local newPath = nil

	while not newPath and numAttempts < 5 do
		newPath = PathfindingService:ComputeSmoothPathAsync(startPos, destination, MAX_PATHING_DISTANCE)
		numAttempts = numAttempts + 1

		if newPath.Status == Enum.PathStatus.ClosestNoPath or newPath.Status == Enum.PathStatus.ClosestOutOfRange then
			newPath = nil
			break
		end

		if newPath and newPath.Status == Enum.PathStatus.FailStartNotEmpty then
			startPos = startPos + (destination - startPos).unit
			newPath = nil
		end

		if newPath and newPath.Status == Enum.PathStatus.FailFinishNotEmpty then
			destination = destination + Vector3.new(0, 1, 0)
			newPath = nil
		end
	end

	return newPath
end

function VRNavigation:OnNavigationRequest(destinationCFrame, inputUserCFrame )
	local destinationPosition = destinationCFrame.p
	local lastDestination = self.currentDestination

	if not IsFiniteVector3(destinationPosition) then
		return
	end

	self.currentDestination = destinationPosition

	local humanoid = self:GetLocalHumanoid()
	if not humanoid or not humanoid.Torso then
		return
	end

	local currentPosition = humanoid.Torso.Position
	local distanceToDestination = (self.currentDestination - currentPosition).magnitude

	if distanceToDestination < NO_PATH_THRESHOLD then
		self:GoToPoint(self.currentDestination)
		return
	end

	if not lastDestination or (self.currentDestination - lastDestination).magnitude > RECALCULATE_PATH_THRESHOLD then
		local newPath = self:TryComputePath(currentPosition, self.currentDestination)
		if newPath then
			self:StartFollowingPath(newPath)
			if PathDisplay then
				PathDisplay.setCurrentPoints(self.currentPoints)
				PathDisplay.renderPath()
			end
		else
			self:StopFollowingPath()
			if PathDisplay then
				PathDisplay.clearRenderedPath()
			end
		end
	else
		if moving then
			self.currentPoints[#currentPoints] = self.currentDestination
		else
			self:GoToPoint(self.currentDestination)
		end
	end
end

function VRNavigation:OnJumpAction(actionName, inputState, inputObj)
	if inputState == Enum.UserInputState.Begin then
		self.isJumping = true
	end
	return Enum.ContextActionResult.Sink
end
function VRNavigation:BindJumpAction(active)
	if active then
		if not self.isJumpBound then
			self.isJumpBound = true
			ContextActionService:BindActionAtPriority("VRJumpAction", (function() return self:OnJumpAction() end), false,
				self.CONTROL_ACTION_PRIORITY, Enum.KeyCode.ButtonA)
		end
	else
		if self.isJumpBound then
			self.isJumpBound = false
			ContextActionService:UnbindAction("VRJumpAction")
		end
	end
end

function VRNavigation:ControlCharacterGamepad(actionName, inputState, inputObject)
	if inputObject.KeyCode ~= Enum.KeyCode.Thumbstick1 then return end

	if inputState == Enum.UserInputState.Cancel then
		self.moveVector =  ZERO_VECTOR3
		return
	end

	if inputState ~= Enum.UserInputState.End then
		self:StopFollowingPath()
		if PathDisplay then
			PathDisplay.clearRenderedPath()
		end

		if self:ShouldUseNavigationLaser() then
			self:BindJumpAction(true)
			self:SetLaserPointerMode("Hidden")
		end

		if inputObject.Position.magnitude > THUMBSTICK_DEADZONE then
			self.moveVector = Vector3.new(inputObject.Position.X, 0, -inputObject.Position.Y)
			if self.moveVector.magnitude > 0 then
				self.moveVector = self.moveVector.unit * math.min(1, inputObject.Position.magnitude)
			end

			self.moveLatch = true
		end
	else
		self.moveVector =  ZERO_VECTOR3

		if self:ShouldUseNavigationLaser() then
			self:BindJumpAction(false)
			self:SetLaserPointerMode("Navigation")
		end

		if self.moveLatch then
			self.moveLatch = false
			movementUpdateEvent:Fire("offtrack")
		end
	end
	return Enum.ContextActionResult.Sink
end

function VRNavigation:OnHeartbeat(dt)
	local newMoveVector = self.moveVector
	local humanoid = self:GetLocalHumanoid()
	if not humanoid or not humanoid.Torso then
		return
	end

	if self.moving and self.currentPoints then
		local currentPosition = humanoid.Torso.Position
		local goalPosition = currentPoints[1]
		local vectorToGoal = (goalPosition - currentPosition) * XZ_VECTOR3
		local moveDist = vectorToGoal.magnitude
		local moveDir = vectorToGoal / moveDist

		if moveDist < POINT_REACHED_THRESHOLD then
			local estimatedTimeRemaining = 0
			local prevPoint = currentPoints[1]
			for i, point in pairs(currentPoints) do
				if i ~= 1 then
					local dist = (point - prevPoint).magnitude
					prevPoint = point
					estimatedTimeRemaining = estimatedTimeRemaining + (dist / humanoid.WalkSpeed)
				end
			end

			table.remove(currentPoints, 1)
			currentPointIdx = currentPointIdx + 1

			if #currentPoints == 0 then
				self:StopFollowingPath()
				if PathDisplay then
					PathDisplay.clearRenderedPath()
				end
				return
			else
				if PathDisplay then
					PathDisplay.setCurrentPoints(currentPoints)
					PathDisplay.renderPath()
				end

				local newGoal = currentPoints[1]
				local distanceToGoal = (newGoal - currentPosition).magnitude
				expectedTimeToNextPoint = distanceToGoal / humanoid.WalkSpeed
				timeReachedLastPoint = tick()
			end
		else
			local ignoreTable = {
				game.Players.LocalPlayer.Character,
				workspace.CurrentCamera
			}
			local obstructRay = Ray.new(currentPosition - Vector3.new(0, 1, 0), moveDir * 3)
			local obstructPart, obstructPoint, obstructNormal = workspace:FindPartOnRayWithIgnoreList(obstructRay, ignoreTable)

			if obstructPart then
				local heightOffset = Vector3.new(0, 100, 0)
				local jumpCheckRay = Ray.new(obstructPoint + moveDir * 0.5 + heightOffset, -heightOffset)
				local jumpCheckPart, jumpCheckPoint, jumpCheckNormal = workspace:FindPartOnRayWithIgnoreList(jumpCheckRay, ignoreTable)

				local heightDifference = jumpCheckPoint.Y - currentPosition.Y
				if heightDifference < 6 and heightDifference > -2 then
					humanoid.Jump = true
				end
			end

			local timeSinceLastPoint = tick() - timeReachedLastPoint
			if timeSinceLastPoint > expectedTimeToNextPoint + OFFTRACK_TIME_THRESHOLD then
				self:StopFollowingPath()
				if PathDisplay then
					PathDisplay.clearRenderedPath()
				end

				movementUpdateEvent:Fire("offtrack")
			end

			newMoveVector = self.moveVector:Lerp(moveDir, dt * 10)
		end
	end

	if IsFiniteVector3(newMoveVector) then
		self.moveVector = newMoveVector
	end
end


function VRNavigation:OnUserCFrameEnabled()
	if self:ShouldUseNavigationLaser() then
		self:BindJumpAction(false)
		self:SetLaserPointerMode("Navigation")
	else
		self:BindJumpAction(true)
		self:SetLaserPointerMode("Hidden")
	end
end

function VRNavigation:Enable(enable)

	self.moveVector = ZERO_VECTOR3
	self.isJumping = false

	if enable then
		self.navigationRequestedConn = VRService.NavigationRequested:Connect(function(destinationCFrame, inputUserCFrame) self:OnNavigationRequest(destinationCFrame, inputUserCFrame) end)
		self.heartbeatConn = RunService.Heartbeat:Connect(function(dt) self:OnHeartbeat(dt) end)

		ContextActionService:BindAction("MoveThumbstick", (function(actionName, inputState, inputObject) return self:ControlCharacterGamepad(actionName, inputState, inputObject) end),
			false, self.CONTROL_ACTION_PRIORITY, Enum.KeyCode.Thumbstick1)
		ContextActionService:BindActivate(Enum.UserInputType.Gamepad1, Enum.KeyCode.ButtonR2)

		self.userCFrameEnabledConn = VRService.UserCFrameEnabled:Connect(function() self:OnUserCFrameEnabled() end)
		self:OnUserCFrameEnabled()

		VRService:SetTouchpadMode(Enum.VRTouchpad.Left, Enum.VRTouchpadMode.VirtualThumbstick)
		VRService:SetTouchpadMode(Enum.VRTouchpad.Right, Enum.VRTouchpadMode.ABXY)

		self.enabled = true
	else
		-- Disable
		self:StopFollowingPath()

		ContextActionService:UnbindAction("MoveThumbstick")
		ContextActionService:UnbindActivate(Enum.UserInputType.Gamepad1, Enum.KeyCode.ButtonR2)

		self:BindJumpAction(false)
		self:SetLaserPointerMode("Disabled")

		if self.navigationRequestedConn then
			self.navigationRequestedConn:Disconnect()
			self.navigationRequestedConn = nil
		end
		if self.heartbeatConn then
			self.heartbeatConn:Disconnect()
			self.heartbeatConn = nil
		end
		if self.userCFrameEnabledConn then
			self.userCFrameEnabledConn:Disconnect()
			self.userCFrameEnabledConn = nil
		end
		self.enabled = false
	end
end

return VRNavigation
