-- Called when the user's rotation type is changed.
-- This is a strong indication the user is in first person
-- and needs to have its first person movement smoothened out.


function FpsCamera:OnRotationTypeChanged()
	local camera = workspace.CurrentCamera
	local subject = camera and camera.CameraSubject
	
	if subject and subject:IsA("Humanoid") then
		local rotationType = UserGameSettings.RotationType
	
		if rotationType == Enum.RotationType.CameraRelative then
			subject.AutoRotate = false
			
			RunService:BindToRenderStep("FpsCamera", 1000, function (delta)
				if subject.AutoRotate or not subject:IsDescendantOf(game) or (subject.SeatPart and subject.SeatPart:IsA("VehicleSeat")) then
					RunService:UnbindFromRenderStep("FpsCamera")
					return
				end

				if camera.CameraType.Name == "Scriptable" then
					return
				end
				
				local rootPart = subject.RootPart
				local isGrounded = rootPart and rootPart:IsGrounded()
				
				if rootPart and not isGrounded then
					local state = subject:GetState()
					local canRotate = true

					if self.InvalidRotationStates[state.Name] then
						canRotate = false
					end

					if subject.Sit and subject.SeatPart then
						local root = rootPart:GetRootPart()

						if root ~= rootPart then
							canRotate = false
						end
					end

					if canRotate then
						local pos = rootPart.Position
						local step = math.min(0.2, (delta * 40) / 3)

						local look = camera.CFrame.LookVector
						look = (look * XZ_VECTOR3).Unit
						
						local cf = CFrame.new(pos, pos + look)
						rootPart.CFrame = rootPart.CFrame:Lerp(cf, step)
					end
				end

				if self:IsInFirstPerson() then
					local cf = camera.CFrame
					local headPos, headLook = self:GetSubjectPosition(subject)

					if headPos then
						local offset = (headPos - cf.Position)
						cf += offset

						camera.CFrame = cf
						camera.Focus += offset
					end

					local shadowAngle = self:GetShadowAngle()
					local inView = cf.LookVector:Dot(shadowAngle)

					if inView < 0 then
						for real, mirror in pairs(self.HeadMirrors) do
							mirror.CFrame = real.CFrame + (shadowAngle * 9)
						end
					end

					self.MirrorBin.Parent = (inView < 0 and camera or nil)
				else
					self.MirrorBin.Parent = nil
				end
			end)
		else
			subject.AutoRotate = true
			self.MirrorBin.Parent = nil
		end
	end
end
