-- // Chaos Control - Created by HellHawkX
-- // This script handles HMS' crazily overpowered ability
-- // Revamped and restructured by Wolfy

local function ChaosControl(player)
	local nextsec = R_PointInSubsector(player.mo.x + player.mo.momx, player.mo.y + player.mo.momy).sector
	if (player.mo.skin == "hms123311") then
		for rover in nextsec.ffloors() do
			if (rover.bottomheight < player.mo.z + P_GetPlayerHeight(player)) and (rover.topheight > player.mo.z) then
				if (rover.flags & (FF_TRANSLUCENT|FF_SOLID) == (FF_TRANSLUCENT|FF_SOLID)) then
					rover.flags = $1 & ~FF_SOLID
				end
			end
		end
		if (not nextsec or (nextsec.ceilingheight - nextsec.floorheight <= player.mo.height)) then
			P_BounceMove(player.mo)
			player.mo.angle = R_PointToAngle2(0, 0, player.mo.momx, player.mo.momy)
		end
		if not (player.cmd.buttons & BT_JUMP) then
			if (player.mo.z <= player.mo.floorz) then
				player.mo.state = S_PLAY_STND
			end
			player.mo.flags = $1 & ~MF_NOCLIP
			player.chaoscontrol = false
		else
			if not (player.exiting) then
				P_InstaThrust(player.mo, player.mo.angle, 80*FRACUNIT)
				P_SetObjectMomZ(player.mo, -FRACUNIT, false)
				player.mo.flags = $1|MF_NOCLIP
			end
		end
	end
end

addHook("AbilitySpecial", function(player)
	if (player.mo.skin == "hms123311") then
		S_StartSound(player.mo, sfx_zoom)
		S_StartSound(player.mo, player.mo.info.attacksound)
		P_NukeEnemies(player.mo, player.mo, 1536*FRACUNIT)
		P_SpawnThokMobj(player)
		player.chaoscontrol = true
	end
end)

addHook("MobjThinker", function(mobj)
	local player = mobj.player
	if (player.mo and player.mo.skin == "hms123311")
	and not (maptol & TOL_NIGHTS)
	and (player.playerstate == PST_LIVE)
	and not (player.mo.tracer and player.mo.tracer.type == MT_TUBEWAYPOINT)
	and not (P_IsObjectOnGround(player.mo))
	and (player.powers[pw_carry] != CR_NIGHTSMODE)
	and not (player.powers[pw_carry] & (CR_GENERIC|CR_PLAYER|CR_ROPEHANG))
	and (player.pflags & PF_THOKKED)
	and not (P_InQuicksand(player.mo))
	and (player.chaoscontrol) then
		ChaosControl(player)
	else
		player.chaoscontrol = false
	end
end, MT_PLAYER)
