function stopAllAnimations()local B=currentAnim if emoteNames[B]~=nil and emoteNames[B]==false then B="\105\100\108\101"end if currentlyPlayingEmote then B="\105\100\108\101"currentlyPlayingEmote=false end currentAnim=""currentAnimInstance=nil if currentAnimKeyframeHandler~=nil then currentAnimKeyframeHandler:disconnect()end if currentAnimTrack~=nil then currentAnimTrack:Stop()currentAnimTrack:Destroy()currentAnimTrack=nil end for B,n in pairs(locomotionMap)do if n.track then n.track:Stop()n.track:Destroy()n.track=nil end end return B end function getHeightScale()if Humanoid then if not Humanoid.AutomaticScalingEnabled then return 1 end local B=Humanoid.HipHeight/HumanoidHipHeight if AnimationSpeedDampeningObject==nil then AnimationSpeedDampeningObject=script:FindFirstChild("\083\099\097\108\101\068\097\109\112\101\110\105\110\103\080\101\114\099\101\110\116")end if AnimationSpeedDampeningObject~=nil then B=1+((Humanoid.HipHeight-HumanoidHipHeight)*AnimationSpeedDampeningObject.Value)/HumanoidHipHeight end return B end return 1 end local function B(B,n)return-math.atan2(B.x*n.y-B.y*n.x,B.x*n.x+B.y*n.y)end local n=2.0 local function x(x,c,g,X,Q,z)local y=.5*(Q+z)local w={x=(X-Q)/y;y=n*B(c,x)}local f={x=(z-Q)/y;y=n*B(c,g)}local m=smallButNotZero+(f.x*f.x+f.y*f.y)local v=w.x*f.x+w.y*f.y local F=math.clamp(1.0-v/m,.0,1.0)return F end local function c(B,n)local c={}local g=.0 for X,Q in pairs(locomotionMap)do if B.x*Q.lv.x<.0 or B.y*Q.lv.y<0 then c[X]=.0 continue end c[X]=math.huge for g,z in pairs(locomotionMap)do if B.x*z.lv.x<.0 or B.y*z.lv.y<0 then continue end c[X]=math.min(c[X],x(B,Q.lv,z.lv,n,Q.speed,z.speed))end g+=c[X]end local X=.0 local Q=0 local z=0 for B,n in pairs(locomotionMap)do if c[B]/g>.1 then X+=c[B]Q+=c[B]*n.lv.x z+=c[B]*n.lv.y else c[B]=.0 end end local y local w=Q*Q+z*z if w>smallButNotZero then y=math.sqrt((n*n)/w)else y=0 end y=y/getHeightScale()local f=0 for B,n in pairs(locomotionMap)do if n.track.IsPlaying then f=n.track.TimePosition break end end for B,n in pairs(locomotionMap)do if c[B]>.0 then if not n.track.IsPlaying then n.track:Play(runBlendtime)n.track.TimePosition=f end local x=math.max(smallButNotZero,c[B]/X)n.track:AdjustWeight(x,runBlendtime)n.track:AdjustSpeed(y)else n.track:Stop(runBlendtime)end end end local function g()local B=Humanoid.WalkToPoint local n=Humanoid.WalkToPart if Humanoid.MoveDirection~=Vector3.zero then return Humanoid.MoveDirection elseif n or B~=Vector3.zero then local x if n then x=n.CFrame:PointToWorldSpace(B)else x=B end local c=Vector3.zero if Humanoid.RootPart then c=x-Humanoid.RootPart.CFrame.Position c=Vector3.new(c.x,.0,c.z)local B=c.Magnitude if B>.01 then c/=B end end return c else return Humanoid.MoveDirection end end local function X(B)local n if locomotionMap==strafingLocomotionMap then local n=g()if not Humanoid.RootPart then return end local x=Humanoid.RootPart.CFrame if math.abs(x.UpVector.Y)<smallButNotZero or pose~="\082\117\110\110\105\110\103"or humanoidSpeed<.001 then for B,n in pairs(locomotionMap)do if n.track then n.track:AdjustWeight(smallButNotZero,runBlendtime)end end return end local X=x.LookVector local Q=Vector3.new(X.X,.0,X.Z)Q=Q/Q.Magnitude local z=n:Dot(Q)if z<=.0 and z>-0.05 then z=smallButNotZero end local y=Q.X*n.Z-Q.Z*n.X local w=Vector2.new(y,z)local f=Vector2.new(w.x-cachedLocalDirection.x,w.y-cachedLocalDirection.y)if f:Dot(f)>.001 or math.abs(humanoidSpeed-cachedRunningSpeed)>.01 or B-lastBlendTime>1 then cachedLocalDirection=w cachedRunningSpeed=humanoidSpeed lastBlendTime=B c(cachedLocalDirection,cachedRunningSpeed)end else if math.abs(humanoidSpeed-cachedRunningSpeed)>.01 or B-lastBlendTime>1 then cachedRunningSpeed=humanoidSpeed lastBlendTime=B c(Vector2.yAxis,cachedRunningSpeed)end end end function setAnimationSpeed(B)if currentAnim~="\119\097\108\107"then if B~=currentAnimSpeed then currentAnimSpeed=B currentAnimTrack:AdjustSpeed(currentAnimSpeed)end end end function keyFrameReachedFunc(B)if B=="\069\110\100"then local B=currentAnim if emoteNames[B]~=nil and emoteNames[B]==false then B="\105\100\108\101"end if currentlyPlayingEmote then if currentAnimTrack.Looped then return end B="\105\100\108\101"currentlyPlayingEmote=false end local n=currentAnimSpeed playAnimation(B,.15,Humanoid)setAnimationSpeed(n)end end function rollAnimation(B)local n=math.random(1,animTable[B].totalWeight)local x=n local c=1 while n>animTable[B][c].weight do n=n-animTable[B][c].weight c=c+1 end return c end local Q,z,y,w local function f()for B,n in pairs(strafingLocomotionMap)do if n.track then n.track:Stop()n.track:Destroy()n.track=nil end end for B,n in pairs(fallbackLocomotionMap)do if n.track then n.track:Stop()n.track:Destroy()n.track=nil end end cachedRunningSpeed=0 end local function m(B)z=0 Q=0 w=0 y=0 end local function v(B)if B then if B.x>Q then Q=B.x end if B.y>y then y=B.y end if B.x<z then z=B.x end if B.y<w then w=B.y end end end local function F(B)if Q==0 or z==0 or y==0 or w==0 then if locomotionMap==strafingLocomotionMap then warn("\083\116\114\097\102\101 \098\108\101\110\100\105\110\103 \100\105\115\097\098\108\101\100\046  \078\111\116 \097\108\108 \113\117\097\100\114\097\110\116\115 \111\102 \109\111\116\105\111\110 \114\101\112\114\101\115\101\110\116\101\100\046")end locomotionMap=fallbackLocomotionMap else locomotionMap=strafingLocomotionMap end end local function Z(B,n,x,c)m()for B,n in pairs(locomotionMap)do n.track=c:LoadAnimation(animTable[B][1].anim)n.track.Priority=Enum.AnimationPriority.Core v(n.lv)end F()end local function p(B,n,x,c)if B~=currentAnimInstance then if currentAnimTrack~=nil then currentAnimTrack:Stop(x)currentAnimTrack:Destroy()end if currentAnimKeyframeHandler~=nil then currentAnimKeyframeHandler:disconnect()end currentAnimSpeed=1.0 currentAnim=n currentAnimInstance=B if n=="\119\097\108\107"then Z(B,n,x,c)else f()currentAnimTrack=c:LoadAnimation(B)currentAnimTrack.Priority=Enum.AnimationPriority.Core currentAnimTrack:Play(x)currentAnimKeyframeHandler=currentAnimTrack.KeyframeReached:connect(keyFrameReachedFunc)end end end function playAnimation(B,n,x)local c=rollAnimation(B)local g=animTable[B][c].anim p(g,B,n,x)currentlyPlayingEmote=false end function playEmote(B,n,x)p(B,B.Name,n,x)currentlyPlayingEmote=true end


function stopAllAnimations()
	local oldAnim = currentAnim

	-- return to idle if finishing an emote
	if (emoteNames[oldAnim] ~= nil and emoteNames[oldAnim] == false) then
		oldAnim = "idle"
	end

	if currentlyPlayingEmote then
		oldAnim = "idle"
		currentlyPlayingEmote = false
	end

	currentAnim = ""
	currentAnimInstance = nil
	if (currentAnimKeyframeHandler ~= nil) then
		currentAnimKeyframeHandler:disconnect()
	end

	if (currentAnimTrack ~= nil) then
		currentAnimTrack:Stop()
		currentAnimTrack:Destroy()
		currentAnimTrack = nil
	end

	for _,v in pairs(locomotionMap) do
		if v.track then
			v.track:Stop()
			v.track:Destroy()
			v.track = nil
		end
	end

	return oldAnim
end

function getHeightScale()
	if Humanoid then
		if not Humanoid.AutomaticScalingEnabled then
			return 1
		end

		local scale = Humanoid.HipHeight / HumanoidHipHeight
		if AnimationSpeedDampeningObject == nil then
			AnimationSpeedDampeningObject = script:FindFirstChild("ScaleDampeningPercent")
		end
		if AnimationSpeedDampeningObject ~= nil then
			scale = 1 + (Humanoid.HipHeight - HumanoidHipHeight) * AnimationSpeedDampeningObject.Value / HumanoidHipHeight
		end
		return scale
	end
	return 1
end


local function signedAngle(a, b)
	return -math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y)
end

local angleWeight = 2.0
local function get2DWeight(px, p1, p2, sx, s1, s2)
	local avgLength = 0.5 * (s1 + s2)

	local p_1 = {x = (sx - s1)/avgLength, y = (angleWeight * signedAngle(p1, px))}
	local p12 = {x = (s2 - s1)/avgLength, y = (angleWeight * signedAngle(p1, p2))}	
	local denom = smallButNotZero + (p12.x*p12.x + p12.y*p12.y)
	local numer = p_1.x * p12.x + p_1.y * p12.y
	local r = math.clamp(1.0 - numer/denom, 0.0, 1.0)
	return r
end

local function blend2D(targetVelo, targetSpeed)
	local h = {}
	local sum = 0.0
	for n,v1 in pairs(locomotionMap) do
		if targetVelo.x * v1.lv.x < 0.0 or targetVelo.y * v1.lv.y < 0 then
			-- Require same quadrant as target
			h[n] = 0.0
			continue
		end
		h[n] = math.huge
		for j,v2 in pairs(locomotionMap) do
			if targetVelo.x * v2.lv.x < 0.0 or targetVelo.y * v2.lv.y < 0 then
				-- Require same quadrant as target
				continue
			end
			h[n] = math.min(h[n], get2DWeight(targetVelo, v1.lv, v2.lv, targetSpeed, v1.speed, v2.speed))
		end
		sum += h[n]
	end

	--truncates below 10% contribution
	local sum2 = 0.0
	local weightedVeloX = 0
	local weightedVeloY = 0
	for n,v in pairs(locomotionMap) do

		if (h[n] / sum > 0.1) then
			sum2 += h[n]
			weightedVeloX += h[n] * v.lv.x
			weightedVeloY += h[n] * v.lv.y
		else
			h[n] = 0.0
		end
	end
	local animSpeed
	local weightedSpeedSquared = weightedVeloX * weightedVeloX + weightedVeloY * weightedVeloY
	if weightedSpeedSquared > smallButNotZero then
		animSpeed = math.sqrt(targetSpeed * targetSpeed / weightedSpeedSquared)
	else
		animSpeed = 0
	end

	animSpeed = animSpeed / getHeightScale()
	local groupTimePosition = 0
	for n,v in pairs(locomotionMap) do
		if v.track.IsPlaying then
			groupTimePosition = v.track.TimePosition
			break
		end
	end
	for n,v in pairs(locomotionMap) do
		-- if not loco
		if h[n] > 0.0 then
			if not v.track.IsPlaying then 
				v.track:Play(runBlendtime)
				v.track.TimePosition = groupTimePosition
			end

			local weight = math.max(smallButNotZero, h[n] / sum2)
			v.track:AdjustWeight(weight, runBlendtime)
			v.track:AdjustSpeed(animSpeed)
		else
			v.track:Stop(runBlendtime)
		end
	end

end

local function getWalkDirection()
	local walkToPoint = Humanoid.WalkToPoint
	local walkToPart = Humanoid.WalkToPart
	if Humanoid.MoveDirection ~= Vector3.zero then
		return Humanoid.MoveDirection
	elseif walkToPart or walkToPoint ~= Vector3.zero then
		local destination
		if walkToPart then
			destination = walkToPart.CFrame:PointToWorldSpace(walkToPoint)
		else
			destination = walkToPoint
		end
		local moveVector = Vector3.zero
		if Humanoid.RootPart then
			moveVector = destination - Humanoid.RootPart.CFrame.Position
			moveVector = Vector3.new(moveVector.x, 0.0, moveVector.z)
			local mag = moveVector.Magnitude
			if mag > 0.01 then
				moveVector /= mag
			end
		end
		return moveVector
	else
		return Humanoid.MoveDirection
	end
end

local function updateVelocity(currentTime)
	
	local tempDir
	
	if locomotionMap == strafingLocomotionMap then
		
		local moveDirection = getWalkDirection()

		if not Humanoid.RootPart then
			return
		end

		local cframe = Humanoid.RootPart.CFrame
		if math.abs(cframe.UpVector.Y) < smallButNotZero or pose ~= "Running" or humanoidSpeed < 0.001 then
			-- We are horizontal!  Do something  (turn off locomotion)
			for n,v in pairs(locomotionMap) do
				if v.track then
					v.track:AdjustWeight(smallButNotZero, runBlendtime)
				end
			end
			return
		end
		local lookat = cframe.LookVector
		local direction = Vector3.new(lookat.X, 0.0, lookat.Z)
		direction = direction / direction.Magnitude --sensible upVector means this is non-zero.
		local ly = moveDirection:Dot(direction)
		if ly <= 0.0 and ly > -0.05 then
			ly = smallButNotZero -- break quadrant ties in favor of forward-friendly strafes
		end
		local lx = direction.X*moveDirection.Z - direction.Z*moveDirection.X
		local tempDir = Vector2.new(lx, ly) -- root space moveDirection
		local delta = Vector2.new(tempDir.x-cachedLocalDirection.x, tempDir.y-cachedLocalDirection.y)
		-- Time check serves the purpose of the old keyframeReached sync check, as it syncs anim timePosition
		if delta:Dot(delta) > 0.001 or math.abs(humanoidSpeed - cachedRunningSpeed) > 0.01 or currentTime - lastBlendTime > 1 then
			cachedLocalDirection = tempDir
			cachedRunningSpeed = humanoidSpeed
			lastBlendTime = currentTime
			blend2D(cachedLocalDirection, cachedRunningSpeed)
		end 
	else
		if math.abs(humanoidSpeed - cachedRunningSpeed) > 0.01 or currentTime - lastBlendTime > 1 then
			cachedRunningSpeed = humanoidSpeed
			lastBlendTime = currentTime
			blend2D(Vector2.yAxis, cachedRunningSpeed)
		end
	end
end

function setAnimationSpeed(speed)
	if currentAnim ~= "walk" then
		if speed ~= currentAnimSpeed then
			currentAnimSpeed = speed
			currentAnimTrack:AdjustSpeed(currentAnimSpeed)
		end
	end
end

function keyFrameReachedFunc(frameName)
	if (frameName == "End") then
		local repeatAnim = currentAnim
		-- return to idle if finishing an emote
		if (emoteNames[repeatAnim] ~= nil and emoteNames[repeatAnim] == false) then
			repeatAnim = "idle"
		end

		if currentlyPlayingEmote then
			if currentAnimTrack.Looped then
				-- Allow the emote to loop
				return
			end

			repeatAnim = "idle"
			currentlyPlayingEmote = false
		end

		local animSpeed = currentAnimSpeed
		playAnimation(repeatAnim, 0.15, Humanoid)
		setAnimationSpeed(animSpeed)
	end
end

function rollAnimation(animName)
	local roll = math.random(1, animTable[animName].totalWeight)
	local origRoll = roll
	local idx = 1
	while (roll > animTable[animName][idx].weight) do
		roll = roll - animTable[animName][idx].weight
		idx = idx + 1
	end
	return idx
end

local maxVeloX, minVeloX, maxVeloY, minVeloY

local function destroyRunAnimations()
	for _,v in pairs(strafingLocomotionMap) do
		if v.track then
			v.track:Stop()
			v.track:Destroy()
			v.track = nil
		end
	end
	for _,v in pairs(fallbackLocomotionMap) do
		if v.track then
			v.track:Stop()
			v.track:Destroy()
			v.track = nil
		end
	end
	cachedRunningSpeed = 0
end

local function resetVelocityBounds(velo)
	minVeloX = 0
	maxVeloX = 0
	minVeloY = 0
	maxVeloY = 0
end

local function updateVelocityBounds(velo)
	if velo then 
		if velo.x > maxVeloX then maxVeloX = velo.x end
		if velo.y > maxVeloY then maxVeloY = velo.y end
		if velo.x < minVeloX then minVeloX = velo.x end
		if velo.y < minVeloY then minVeloY = velo.y end
	end
end

local function checkVelocityBounds(velo)
	if maxVeloX == 0 or minVeloX == 0 or maxVeloY == 0 or minVeloY == 0 then
		if locomotionMap == strafingLocomotionMap then
			warn("Strafe blending disabled.  Not all quadrants of motion represented.")
		end
		locomotionMap = fallbackLocomotionMap
	else
		locomotionMap = strafingLocomotionMap
	end
end

local function setupWalkAnimation(anim, animName, transitionTime, humanoid)
	resetVelocityBounds()
	-- check to see if we need to blend a walk/run animation
	for n,v in pairs(locomotionMap) do
		v.track = humanoid:LoadAnimation(animTable[n][1].anim)
		v.track.Priority = Enum.AnimationPriority.Core
		updateVelocityBounds(v.lv)
	end
	checkVelocityBounds()
end

local function switchToAnim(anim, animName, transitionTime, humanoid)
	-- switch animation		
	if (anim ~= currentAnimInstance) then

		if (currentAnimTrack ~= nil) then
			currentAnimTrack:Stop(transitionTime)
			currentAnimTrack:Destroy()
		end
		if (currentAnimKeyframeHandler ~= nil) then
			currentAnimKeyframeHandler:disconnect()
		end


		currentAnimSpeed = 1.0

		currentAnim = animName
		currentAnimInstance = anim	-- nil in the case of locomotion

		if animName == "walk" then
			setupWalkAnimation(anim, animName, transitionTime, humanoid)
		else
			destroyRunAnimations()
			-- load it to the humanoid; get AnimationTrack
			currentAnimTrack = humanoid:LoadAnimation(anim)
			currentAnimTrack.Priority = Enum.AnimationPriority.Core

			currentAnimTrack:Play(transitionTime)	
			
			-- set up keyframe name triggers
			currentAnimKeyframeHandler = currentAnimTrack.KeyframeReached:connect(keyFrameReachedFunc)
		end
	end
end

function playAnimation(animName, transitionTime, humanoid)
	local idx = rollAnimation(animName)
	local anim = animTable[animName][idx].anim

	switchToAnim(anim, animName, transitionTime, humanoid)
	currentlyPlayingEmote = false
end

function playEmote(emoteAnim, transitionTime, humanoid)
	switchToAnim(emoteAnim, emoteAnim.Name, transitionTime, humanoid)
	currentlyPlayingEmote = true
end
