local drop_speed = FRACUNIT * 600 / 100
local bump_range = FRACUNIT * 600
local spin_range = FRACUNIT * 240
local bump_thrust = FRACUNIT * 12
local spin_thrust = FRACUNIT * 32

local function OpenTricks_MakeQuakeMarker(attacker, defender, range, color)
  local amobj = attacker.mo
  local dmobj = defender.mo
  
  local angle = R_PointToAngle2(amobj.x, amobj.y, dmobj.x, dmobj.y)
  local dx = FixedMul(cos(angle), range)
  local dy = FixedMul(sin(angle), range)

  local smoke = P_SpawnMobj(amobj.x + dx, amobj.y + dy, amobj.z, MT_OTRICKSMOKE)
  
  smoke.target = amobj
  smoke.destscale = amobj.scale
  smoke.scale = amobj.scale
  smoke.color = color

  return smoke
end

local function Quake_Attack(atk)
  for def in players.iterate do
    if def.spectator or not def.mo or not def.mo.valid or not def.mo.health or def.mo == atk.mo -- don't attack self, specs, etc.
	  continue
	end 
	
	if not P_CheckSight(atk.mo, def.mo) or not P_IsObjectOnGround(def.mo) -- don't attack through walls, don't attack airborne
	  continue
	end
	
	OpenTricks_MakeQuakeMarker(atk, def, bump_range, SKINCOLOR_VOMIT)
	OpenTricks_MakeQuakeMarker(atk, def, spin_range, SKINCOLOR_MOONSLAM)
    
    local dist = FixedHypot(FixedHypot(atk.mo.x - def.mo.x, atk.mo.y - def.mo.y), atk.mo.z - def.mo.z)
	print(dist>>FRACBITS)
  
    if dist <= spin_range
	  K_SpinPlayer(def, nil, 0, atk.mo)
      P_SetObjectMomZ(def.mo, spin_thrust, false)
    elseif dist <= bump_range
      P_SetObjectMomZ(def.mo, bump_thrust, false)
    end
  end
end

local function Quake_Initialize(player)
  local mobj = player.mo
  player.OpenTricks.Quake = {["fall_time"] = 0, ["last_fall_time"] = 0, ["mini"] = 0}
end

local function Quake_Thinker(player)
  local mobj = player.mo
  
  player.OpenTricks.Quake.last_fall_time = player.OpenTricks.Quake.fall_time
  
  OpenTricks_AutoMiniBoost(player, player.OpenTricks.Quake)
  
  if P_IsObjectOnGround(mobj)
    player.OpenTricks.Quake.fall_time = 0
  elseif player.OpenTricks.combo -- if was in the air and had any combo...
    player.OpenTricks.Quake.fall_time = $ + 1
  end
end

local function Quake_Success(player)
  local mobj = player.mo
  if (mobj.flags2 & MF2_OBJECTFLIP)
    mobj.momz = $ + drop_speed
  else
    mobj.momz = $ - drop_speed
  end
end

local function Quake_Landing(player)
  if player.OpenTricks.combo > 0
    Quake_Attack(player)
  end
  local mobj = player.mo
  S_StartSound(mobj, sfx_s23c)
  player.OpenTricks.Quake.mini = $ + ((30 + player.OpenTricks.Quake.last_fall_time) * (player.OpenTricks.combo ^ 2))
end

OPENTRICKS_ADD_FOURICONS("quake", "attack nearby foes", "TRXTGN22", "TRXTGN24", "TRXTGN24", "TRXTGN26", true, Quake_Initialize, Quake_Thinker, Quake_Success, Quake_Landing)