//
// Copyright(C) 2014-2015 Samuel Villarreal
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// DESCRIPTION:
//      Player Script Object Class
//

#include "scripts/common.txt"

/*
==============================================================
Global vars for Knife
==============================================================
*/

const array<int> g_KnifeRaptorHits          = { 3, 3, 3 };
const array<int> g_KnifeHumanHits           = { 15, 15, 15 };
const array<int> g_knifeDimetrondonHits     = { 1, 1, 1 };
const array<int> g_KnifeTriceratopsHits     = { 1, 1, 1 };
const array<int> g_KnifeSubterraneanHits    = { 1, 1, 1 };
const array<int> g_KnifeStalkerHits         = { 7, 7, 7 };
const array<int> g_KnifeAlienHits           = { 1, 1, 1 };
const array<int> g_KnifePurlinHits          = { 3, 3, 3 };
const array<int> g_KnifeRobotHits           = { -1, -1, -1 };
const array<int> g_KnifeSewerCrabHits       = { 1, 1, 1 };
const array<int> g_KnifePlantHits           = { 1, 1, 1 };

const int g_KnifeMortalWoundHits    = 30;
const int g_KnifeMortalDeathHits    = 999;
const int g_KnifeTrexHits           = 40;
const int g_KnifeCampaignerHits     = 20;
const int g_KnifeLonghunterHits     = 20;
const int g_KnifeHummerHits         = 50;
const int g_KnifeMantisHits         = 40;

// Smoke39
enum EHandedness {
	HAND_Left,
	HAND_Right
}
int MeleeWeaponHand;

bool bLevel8ReturnWarp = false; // entered dynamically spawned level 8 portal back to hub

/*
==============================================================
TurokPlayer
==============================================================
*/

class TurokPlayer : ScriptObjectPlayer
{
	kPuppet @self;
	kActor @m_pWarpBuzzActor;
	kVec3 m_vBloodVector;
	kVec3 m_vStabVector;
	kVec3 m_vShoveVector;
	float m_damageFloorTime;
	float m_initialFriction;
	float m_nBubbles;
	float m_bubblesSfxTimer;
	float m_shoveTime;
	// Smoke39
	float footstep;
	bool bWasOnGround, bLeftFoot;
	int DamFlashTick; // tick when last scope damage flash occured
	bool bWasInSaveSector;

	TurokPlayer(kPuppet @actor)
	{
		@self = actor;
		@m_pWarpBuzzActor = null;
		m_damageFloorTime = 0;
		m_initialFriction = 0;
		m_nBubbles = 0;
		m_bubblesSfxTimer = 0;
		m_shoveTime = 0;
		// Smoke39
		footstep = 0;
		bWasOnGround = true;
		DamFlashTick = -30;
		bWasInSaveSector = false;
		PowerCoreTick = -30*60;
	}

	// Smoke39
	void OnEndLevel()
	{
		@TraceStartActor = @TraceEndActor = null;
		TauntSystem::LevelEnd();
	}

	/*
	==============================================================
	InSpiritWorld
	==============================================================
	*/

	bool InSpiritWorld(void)
	{
		if(Game.GetCurrentMapID() < 26 || Game.GetCurrentMapID() > 41)
		{
			return false;
		}

		return true;
	}

	/*
	==============================================================
	DoSplashBubbles
	==============================================================
	*/

	void DoSplashBubbles(void)
	{
		float cnt;

		if(m_nBubbles <= 0)
		{
			return;
		}

		m_nBubbles -= GAME_FRAME_TIME;

		if(m_nBubbles < 0)
		{
			m_nBubbles = 0;
		}

		if(m_nBubbles < m_bubblesSfxTimer)
		{
			self.PlaySound("sounds/shaders/underwater_swim_1.ksnd");
			m_bubblesSfxTimer = 0;
		}

		cnt = m_nBubbles / 6;
		if(cnt < 1)
		{
			cnt = 1;
		}

		for(int i = 0; i < int(cnt); ++i)
		{
			self.SpawnFx("fx/water_bubble.kfx", Math::vecZero);
		}
	}

	/*
	==============================================================
	DoWarpSounds
	==============================================================
	*/

	void DoWarpSounds(void)
	{
		if(m_pWarpBuzzActor is null)
		{
			return;
		}

		float time = float(PlayLoop.Ticks());

		m_pWarpBuzzActor.Origin() = self.Origin();

		m_pWarpBuzzActor.Origin().x += (GAME_SCALE*15) * Math::Sin(Math::Deg2Rad(time * 6.0f)) + self.Yaw();
		m_pWarpBuzzActor.Origin().y += (GAME_SCALE*15) * Math::Cos(Math::Deg2Rad(time * 7.0f)) + self.Yaw();

		m_pWarpBuzzActor.PlaySound("sounds/shaders/generic_185.ksnd");
	}

	/*
	==============================================================
	IntroCinematicEvent
	==============================================================
	*/

	void IntroCinematicEvent(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		if(Game.GetCurrentMapID() != 43)
		{
			return;
		}

		Game.CallDelayedMapScript(3, instigator, 0);
	}

	/*
	==============================================================
	OnTick
	==============================================================
	*/

	void OnTick(void)
	{
		// Smoke39

		// open Turok+ menu in save sectors
		bool bInSaveSector = World.GetAreaFlags( self.AreaID() ) & AAF_SAVEGAME != 0;
		if ( bInSaveSector != bWasInSaveSector )
		{
			if ( bInSaveSector )
				Spawn( "TurokPlusMenu", self.Origin() );
			bWasInSaveSector = bInSaveSector;
		}

		HUD::Tick();
		TauntSystem::Tick();
		if ( GetAreaFlags(self) & AAF_SECRET != 0 )
		{
			// note that secret bits and count aren't updated until after OnTick()
			int bits = Game.GetMapSecretBits( Game.GetCurrentMapID() );
			int16 secret = World.GetAreaArg( self.AreaID(), 5 );
			if ( bits & (1 << secret) == 0 )
			{
				HUD::Level::FoundSecret( Game.GetHubSecretsFound( GetCurrentHubID() ) + 1 );
				TauntSystem::SecretFound();
			}
		}

		if ( PowerCoreRemaining() == 60 )
			self.PlaySound( "sounds/shaders/RW/PowerCore_Expire.ksnd" );

		if ( self.PlayerFlags() & PF_FALLINGDEATHPIT != 0 )
			FallingToDeath();
		UpdateFootsteps();

		// end Smoke39 stuff

		const int area = self.AreaID();
		float damageDelay =  float(World.GetAreaArg(area, 5)) / 1024.0f;

		if(self.AnimState().PlayingID() == anim_campaingerRage)
		{
			return;
		}

		if(InSpiritWorld())
		{
			DoWarpSounds();
		}

		if(self.GetWaterLevel() == WLT_UNDER)
		{
			DoSplashBubbles();
		}

		if((World.GetAreaFlags(area) & AAF_DAMAGE) != 0 && self.OnGround())
		{
			m_damageFloorTime += GAME_DELTA_TIME;

			if(m_damageFloorTime >= damageDelay)
			{
				m_damageFloorTime = 0;
				self.InflictGenericDamage(self.CastToActor(), World.GetAreaArg(area, 4));
			}
		}
		else
		{
			m_damageFloorTime = damageDelay;
		}

		if((World.GetAreaFlags(area) & AAF_LAVA) != 0 && self.OnGround())
		{
			self.Friction() = m_initialFriction * 0.5f;
		}
		else
		{
			// Smoke39 - slow while scoped
			if ( PlayerScoped() && !bExternalWeaponPack )
				self.Friction() = m_initialFriction * 0.5f;
			else
				self.Friction() = m_initialFriction;
		}

		if(m_shoveTime > 0)
		{
			kVec3 vDir = m_vShoveVector - self.Origin();
			float anYaw = vDir.ToYaw();

			self.Yaw() = self.Yaw().Interpolate(anYaw, 0.2f);
			m_shoveTime -= GAME_DELTA_TIME;
		}
	}

	// Smoke39
	void UpdateFootsteps()
	{
		if ( !Opt::bPlayerFootsteps )
			return;

		// keep footsteps from droning on during cutscenes
		if ( Player.Locked() )
			return;

		bool bOnGround = self.OnGround() && self.PlayerFlags() & (PF_FLY | PF_NOCLIP) == 0
			&& World.GetAreaFlags( self.AreaID() ) & (AAF_CLIMB | AAF_LADDER | AAF_WATER | AAF_CLIFF) == 0;

		// landed
		if ( !bWasOnGround && bOnGround )
		{
			footstep = 1.0f;
			bLeftFoot = false;
		}
		// running
		else if ( bOnGround && self.PlayerFlags() & PF_CRAWLING == 0 )
		{
			float maxSpeed = 6.4f, backSpeed = 4.864f, freq = 3;
			// we could let the slower movement speed give us lower percentages for slower footsteps
			// but then running diagonally would have faster footsteps when capping to 1.0 (since each axis is only getting up to 0.5), which we don't want
			// so we change the scale to match lava speed, and instead reduce freq
			if ( World.GetAreaFlags( self.AreaID() ) & AAF_LAVA != 0 )
			{
				maxSpeed /= 2;
				backSpeed /= 2;
				freq = 2;
			}
			// setting backSpeed to maxSpeed would cause footsteps to match actual speed, but this sounds too slow in practice
			// leaving backSpeed at actual max back speed would make running backward sound as fast as forward, but that doesn't reflect the speed reduction
			// so we average them to slow the step speed a bit, but not too much
			backSpeed = (maxSpeed + backSpeed) / 2;

//			kVec3 X = self.GetTransformedVector( kVec3( 1 / self.Scale().x, 0, 0 ) ) - self.Origin();
//			kVec3 Y = self.GetTransformedVector( kVec3( 0, -1 / self.Scale().y, 0 ) ) - self.Origin();
			kQuat horizontalRot = kQuat( -self.Yaw(), 0,0,1 );
			kVec3 X = kVec3(1,0,0) * horizontalRot;
			kVec3 Y = kVec3(0,1,0) * horizontalRot;
			float speedX = Math::Fabs( self.Movement().Dot( X ) / maxSpeed );
			float speedY = self.Movement().Dot( Y );
			if ( speedY >= 0 )
				speedY /= maxSpeed;
			else
				speedY /= backSpeed;

			footstep += Math::Min( Math::Sqrt( speedX*speedX + speedY*speedY ), 1.0f )
				* freq * GAME_DELTA_TIME;
		}

		if ( footstep >= 1 )
		{
			bLeftFoot = !bLeftFoot;
			PlayFootstepSound();
			footstep -= 1;
		}

		bWasOnGround = bOnGround;
	}

	void PlayFootstepSound()
	{
		// no non-goop step sounds below walking speed
		switch ( World.GetAreaFloorImpact( self.AreaID() ) )
		{
			case IT_DEFAULT:
			case IT_METAL:
			case IT_STONE:
				if ( bWasOnGround && ( self.Movement() * kVec3(1,1,0) ).UnitSq() <= 16 )
					return;
		}

		kStr str = "sounds/shaders/TPlus/Player/Step_";
		switch ( World.GetAreaFloorImpact( self.AreaID() ) )
		{
			case IT_DEFAULT: str += "Earth_" + (Math::RandMax(3) + 1); break;
			case IT_METAL:
			case IT_STONE:   str += "Stone_" + (Math::RandMax(3) + 1); break;
			case IT_LAVA:    str += "Lava"; break;
			case IT_SLIME:
			if ( bLeftFoot ) str += "Tar"; else return; break;
			default: return;
		}
		self.PlaySound( str + ".ksnd" );
	}

	/*
	==============================================================
	OnBeginLevel
	==============================================================
	*/

	void OnBeginLevel(void)
	{
		// Smoke39 - level 8 - spawn a portal back to the hub
		if ( Game.GetCurrentMapID() == 21 )
			Spawn( "SpawnWarpPortal", -9413-20, 3295-30, 51, Math::pi + 0.7f );

		if ( InSpiritWorld() )
			@m_pWarpBuzzActor = ActorFactory.Spawn( "DummyActor", 0, 0, 0, 0, self.SectorIndex() );
	}

	// Smoke39
	void OnPostBeginLevel()
	{
		// weapons are created between OnBeginLevel() and OnPostBeginLevel()
		// so initialize ammo and weapon pack stuff here
		Magazine.Init();
		if ( GrenadeDrops == HGD_Init )
		{
			if ( bExternalWeaponPack )
			{
				kStr str;
				if ( Player.GetWeaponActor(0).Definition().GetString( "TPlus.GrenadeDrops", str ) )
				{
					str = str.ToLower();
					     if ( str == "on"  ) GrenadeDrops = HGD_On;
					else if ( str == "off" ) GrenadeDrops = HGD_Off;
					else                     GrenadeDrops = str.Atoi();
				}
				else
					GrenadeDrops = HGD_Off;
			}
			else
				GrenadeDrops = TW_WEAPON_GRENADE;
		}

		// force enable enemy respawn, so more granular T+ setting can take over
		Game.OverrideRespawningEnemies( 2 );

		// Game.LoadModFile() crashes the game if used any earlier
		// HUD stuff also needs to come this late, which is initialized when applying settings after loading
		Opt::LoadSettings();

		// move from warp point to actual return point
		// OnBeginLevel() seems to be before the actual warp point's position is applied
		if ( !bLevel8ReturnWarp ) return;
		self.SetPosition( self.Origin() + kVec3( 0, 5.5f * 30, 3.25f ) * GAME_SCALE );
		self.Origin().z = self.GetFloorHeight();
		bLevel8ReturnWarp = false;
	}

	/*
	==============================================================
	OnSpawn
	==============================================================
	*/

	void OnSpawn(void)
	{
		// Smoke39
		InitTraceActors( self.CastToActor() );
		TPlus_Title_Init();
		StuckArrowTick = -60;

		m_initialFriction = self.Friction();
	}

	/*
	==============================================================
	OnEnterWater
	==============================================================
	*/

	void OnEnterWater(void)
	{
		// what speed is the player entering the water?
		if(self.Velocity().z < 0)
		{
			m_nBubbles = -self.Velocity().z * 2;

			if(m_nBubbles < 0)
			{
				m_nBubbles = 0;
				m_bubblesSfxTimer = m_nBubbles / 2;
			}
		}
	}

	/*
	==============================================================
	OnArmorDamage
	==============================================================
	*/

	void OnArmorDamage(kActor @instigator, kDictMem @damageDef, const int damage)
	{
		// Smoke39 - scope view damage flash
		DamageFlash( true );

		// note: threshold is actually 5 but actual armor is divided by 3
		if(Player.Armor() > 15 && Player.Armor() - damage <= 15)
			Game.PrintLine( "$str_180", 0 );
	}

	/*
	==============================================================
	DoViewShake
	==============================================================
	*/

	void DoViewShake(float velocity, float angle, float duration)
	{
		kActor @actor = ActorFactory.Spawn("QuakeSource", 0, 0 ,0 ,0, self.SectorIndex());
		TurokQuakeSource @quake;

		if(actor is null)
		{
			return;
		}

		@quake = cast<TurokQuakeSource@>(actor.ScriptObject().obj);

		if(quake is null)
		{
			return;
		}

		quake.SetupShake(self.Origin(), velocity, angle, duration);
	}

	/*
	==============================================================
	DoShoveWithCamera
	==============================================================
	*/

	void DoShoveWithCamera(kActor @instigator)
	{
		if(instigator is null)
		{
			return;
		}

		kVec3 org;
		kVec3 pos;

		org.x = instigator.Origin().x;
		org.y = instigator.Origin().y;
		org.z = instigator.Origin().z + instigator.Height() * 0.5f;

		kVec3 dir = self.Origin() - org;

		if(dir.x*dir.x+dir.y*dir.y <= 0.0f)
		{
			dir.x = Math::RandCFloat();
			dir.y = Math::RandCFloat();
		}

		dir.Normalize();

		dir *= (1.75f*GAME_SCALE);
		dir.z = (0.875f*GAME_SCALE);

		self.Velocity() += dir;

		self.Origin().z += GAME_SCALE;
		self.PlayerFlags() |= PF_NOAIRFRICTION;

		m_shoveTime = 0.5f;
		m_vShoveVector = org;
	}

	/*
	==============================================================
	DoDamageTactile
	==============================================================
	*/

	void DoDamageTactile(const kStr &in strDamageVib)
	{
		// only do generic damage vibrations when an effect is not already playing
		if(!Game.IsTactilePlaying(kexVibrationPlayer::CHANNEL_DAMAGE))
		{
			Game.PlayTactile(strDamageVib, kexVibrationPlayer::CHANNEL_DAMAGE, kexVibrationPlayer::POSITION_NEUTRAL);
		}
	}

	/*
	==============================================================
	OnDamage
	==============================================================
	*/

	void OnDamage(kActor @instigator, kDictMem @damageDef, const int damage)
	{
		// check for quake effect
		if ( damageDef !is null )
		{
			HandleArrowDamageSignal( damageDef );
			HandleDazeDamageSignal( damageDef );

			if ( GetBool( damageDef, "bQuake" ) )
			{
				float velocity = GetFloat( damageDef, "quakeVelocity",  0.5625f * GAME_SCALE );
				float angle    = GetFloat( damageDef, "quakeAngle",    -0.03f );
				float duration = GetFloat( damageDef, "quakeDuration",  2.75f );

				// Smoke39 - check for localized quake source
				float range;
				if ( damageDef.GetFloat("RangeLimit",range) && range > 0 )
					RangedQuake( velocity, angle, duration, ParticleOrigin(), range );
				else
					DoViewShake( velocity, angle, duration );
			}

			if ( GetBool( damageDef, "bShove" ) )
				DoShoveWithCamera( instigator );
		}

		if ( damage <= 0 )
			return;

		// killing blow
		if ( self.Health() > 0 && self.Health() - damage <= 0 )
			return;

		// Smoke39 - moved after killing blow check to prevent low health message if the same hit kills us
		if ( self.Health() > 15 && self.Health() - damage <= 15 )
		{
			Game.PrintLine("$str_181", 0);
			// Smoke39
			TauntSystem::LowHealth();
		}

		// Smoke39
		DamageFlash();

		// Smoke39 - use new function to only play pain sound if one isn't already playing
		if(self.GetWaterLevel() == WLT_UNDER &&
			(World.GetAreaFlags(self.AreaID()) & AAF_ANTIGRAVITY) == 0)
		{
			switch(Math::RandMax(2))
			{
			case 0:
//				self.PlaySound("sounds/shaders/generic_14_turok_water_injury_1.ksnd");
				PlayPainSound("sounds/shaders/generic_14_turok_water_injury_1.ksnd");
				DoDamageTactile("tactile/wtflnc1p.bnvib");
				break;
			case 1:
//				self.PlaySound("sounds/shaders/generic_15_turok_water_injury_2.ksnd");
				PlayPainSound("sounds/shaders/generic_15_turok_water_injury_2.ksnd");
				DoDamageTactile("tactile/wtflnc2p.bnvib");
				break;
			}
		}
		else
		{
			switch((Math::RandMax(5)) & 3)
			{
			case 0:
//				self.PlaySound("sounds/shaders/generic_10_turok_injury_1.ksnd");
				PlayPainSound("sounds/shaders/generic_10_turok_injury_1.ksnd");
				DoDamageTactile("tactile/tflnch1p.bnvib");
				break;
			case 1:
//				self.PlaySound("sounds/shaders/generic_11_turok_injury_2.ksnd");
				PlayPainSound("sounds/shaders/generic_11_turok_injury_2.ksnd");
				DoDamageTactile("tactile/tflnch2p.bnvib");
				break;
			case 2:
//				self.PlaySound("sounds/shaders/generic_12_turok_injury_3.ksnd");
				PlayPainSound("sounds/shaders/generic_12_turok_injury_3.ksnd");
				DoDamageTactile("tactile/tflnch3p.bnvib");
				break;
			case 3:
//				self.PlaySound("sounds/shaders/generic_13_turok_injury_4.ksnd");
				PlayPainSound("sounds/shaders/generic_13_turok_injury_4.ksnd");
				DoDamageTactile("tactile/tflnch4p.bnvib");
				break;
			}
		}
	}

	// Smoke39
	void PlayPainSound( const kStr&in snd )
	{
		if ( self.SoundPlayTime("sounds/shaders/generic_14_turok_water_injury_1.ksnd") >= 0 ) return;
		if ( self.SoundPlayTime("sounds/shaders/generic_15_turok_water_injury_2.ksnd") >= 0 ) return;
		if ( self.SoundPlayTime("sounds/shaders/generic_10_turok_injury_1.ksnd") >= 0 ) return;
		if ( self.SoundPlayTime("sounds/shaders/generic_11_turok_injury_2.ksnd") >= 0 ) return;
		if ( self.SoundPlayTime("sounds/shaders/generic_12_turok_injury_3.ksnd") >= 0 ) return;
		if ( self.SoundPlayTime("sounds/shaders/generic_13_turok_injury_4.ksnd") >= 0 ) return;
		self.PlaySound( snd );
	}

	void HandleArrowDamageSignal( kDictMem@ damageDef )
	{
		// eventually, different StickArrow values will indicate different arrow styles
		// if this method is implemented for more arrow types in place of smart projectiles
		if ( GetInt( damageDef, "StickArrow" ) != 1 ) return;
		// make sure this isn't a corpse sticker trying to spawn on a live enemy
		// or a wall being hit at the same time as an actor from the game's wonky collision
		if ( self.GameTicks() - StuckArrowTick < 2 ) return;
		kVec3 origin = ParticleOrigin();
//		kActor@ arrow = Spawn( "StuckArrow", origin, 0, -1 );
//		kActor@ arrow = Spawn( "StuckArrow", origin, 0, self.SectorIndex() );
		kActor@ arrow = Spawn( "StuckArrow", self.Origin(), 0, self.SectorIndex() );
		if ( arrow is null ) return;
		arrow.SetPosition( origin );
		kVec3 v = self.Origin();
		v.z += self.ViewHeight();
		v = origin - v;
		arrow.Velocity() = v.Normalize() * 7680;
		arrow.Pitch() = -v.ToPitch();
		arrow.Yaw()   =  v.ToYaw();
		StuckArrow@ SO = cast<StuckArrow@>( ActorScript(arrow) );
		if ( SO is null ) return;
		SO.CollisionCommon( null, origin, Math::vecZero, 0 );
		if ( GetBool( damageDef, "bFall" ) )
			SO.UnStick();
	}

	void HandleDazeDamageSignal( kDictMem@ damageDef )
	{
		float daze = GetFloat( damageDef, "Daze" );
		if ( daze <= 0 ) return;
		kVec3 origin = ParticleOrigin();
		float radius = Math::Sqr( GetFloat( damageDef, "radius" ) * GAME_SCALE );
		kActorIterator it;
		kActor@ a;
		while ( (@a = it.Get()) !is null )
		{
			TurokEnemy@ e = cast< TurokEnemy@ >( ActorScript( a ) );
			if ( e is null ) continue;
			if ( !e.CanBeDazed() ) continue;
			float dist = SqrDistToCylinder( a.Origin() - origin, a.Radius(), a.Height() );
			if ( dist >= radius ) continue;
			Trace( a.GetTransformedVector( e.DazeOffset() ) , origin, CF_IGNOREBLOCKERS | CF_NOCLIPSTATICS );
			if ( (CModel.InterceptVector() - origin).UnitSq() > 25 ) continue;
			e.DazeTime = Math::Max( daze * (1 - dist / radius), e.DazeTime );
			e.StunYaw = a.Yaw();
		}
	}

	// Smoke39
	kVec3 ParticleOrigin()
	{
		// known delta per tick of special trigger particle
		kVec3 delta( 0, 1000000000.0f * GAME_DELTA_TIME * Game.GetGameSpeed(), 0 );
		// work backward from hit location to find origin
		return CModel.InterceptVector() - delta * CModel.Fraction();
	}

	// Smoke39 - flash the screen when scoped, since normal damage flash doesn't happen during cutscenes
	void DamageFlash( bool bArmor=false )
	{
		if ( !PlayerScoped() )
			return;

		int t = self.GameTicks() - DamFlashTick;
		if ( t < 3 )
			return;

		kStr flash = "fx/TPlus/Scope/DamageFlash";
		if ( bArmor )
			flash += "_Armor";
		if ( t < 14 )
			flash += "_Light";
		if ( Game.GetGameSpeed() <= 0.6f )
			flash += "_Slomo";
		flash += ".kfx";

		self.SpawnFx( flash, Math::vecZero );

		DamFlashTick = self.GameTicks();
	}

	// Smoke39
	void RangedQuake( float vel, float angle, float time, kVec3&in origin, float range )
	{
		kVec3 center = self.Origin();
		center.z += self.Height() / 2;
		float power = 1 - ( origin - center ).Unit() / range;
		if ( power > 0 )
		{
			power = Math::Pow( power, 1.5f );
			DoViewShake( vel * power, angle * power, time );
		}
	}

	/*
	==============================================================
	OnDeath
	==============================================================
	*/

	// Smoke39 - stuff to do for both normal and falling death
	void DeathCommon()
	{
		TauntSystem::CancelTaunt();
	}

	// Smoke39
	void FallingToDeath()
	{
		DeathCommon();
	}

	void OnDeath(kActor @killer, kDictMem @damageDef)
	{
		// Smoke39
		DeathCommon();

		self.PlaySound("sounds/shaders/generic_18_turok_normal_death.ksnd");

		//
		// we're going to be doing our own custom death cinematic for these specific maps
		//

		int currentMap = Game.GetCurrentMapID();

		switch(currentMap)
		{
        case 0: // campaigner boss map?
            self.PlayerFlags() |= PF_PREVENTDEATHCAM;
            Game.CallMapScript(2, self.CastToActor());
            break;
        case 3: // trex boss map?
            self.PlayerFlags() |= PF_PREVENTDEATHCAM;
            Game.CallMapScript(2, self.CastToActor());
            break;
        case 49: // mantis boss map?
            self.PlayerFlags() |= PF_PREVENTDEATHCAM;
            Game.CallMapScript(5, self.CastToActor());
            break;
		default:
			// Smoke39
			if ( PlayerScoped() )
				CancelScope();
			break;
		}
	}

	/*
	==============================================================
	OnPickup
	==============================================================
	*/

	void OnPickup(kActor @pickup)
	{
        for(uint i = 0; i < hookPlayerPickup.length(); ++i)
            hookPlayerPickup[i](pickup);

		// Smoke39
		TauntSystem::Pickup( pickup );

		// Smoke39
		if ( pickup.InstanceOf("kexKeyPickup") )
		{
			SetGameVarF( "MeleePoints", GetGameVarF( "MeleePoints" ) + MeleePointsPerKey );
			int level = Game.GetMapNumberFromName( GetString( pickup, "pickup.key.mapDef" ) );
			HUD::Level::GotKey( level, pickup.TID() );
			if ( !Opt::bKeyCutscenes )
			{
				Game.Print( Game.GetLocalizedText( "$str_006" ) + level
				          + Game.GetLocalizedText( "$str_007" ) );
				if ( GetBool( pickup, "pickup.key.bExitWarp" )
				  && GetInt(  pickup, "pickup.key.exitWarpFromMap" ) == Game.GetCurrentMapID() )
						PlayLoop.StartWarp( self.CastToActor(), GetInt( pickup, "pickup.key.exitWarpTID"   ),
						                                        GetInt( pickup, "pickup.key.exitWarpToMap" ) );
			}
		}

		int giveBits = 0;
		int chronoBits;

		switch(pickup.Type())
		{
		case AT_PICKUP_CHRONOPIECE1:  giveBits = 0;  break;
		case AT_PICKUP_CHRONOPIECE2:  giveBits = 1;  break;
		case AT_PICKUP_CHRONOPIECE3:  giveBits = 2;  break;
		case AT_PICKUP_CHRONOPIECE4:  giveBits = 3;  break;
		case AT_PICKUP_CHRONOPIECE5:  giveBits = 4;  break;
		case AT_PICKUP_CHRONOPIECE6:  giveBits = 5;  break;
		case AT_PICKUP_CHRONOPIECE7:  giveBits = 6;  break;
		case AT_PICKUP_CHRONOPIECE8:  giveBits = 7;  break;
		case AT_PICKUP_KEY1:
		case AT_PICKUP_KEY2:
		case AT_PICKUP_KEY3:
		case AT_PICKUP_KEY5:
		case AT_PICKUP_KEY6:
			self.RenderModel().SetTexture(21, pickup.SpawnParams(5));
			return;
		case AT_PICKUP_KEY4:
			self.RenderModel().SetTexture(21, pickup.SpawnParams(5));
			if(Game.GetCurrentMapID() == 48)
			{
				GameVariables.SetValue("bGotLonghunterKey", "1");
			}
			// fall through
		case AT_PICKUP_FINALKEY2:
			if(Game.GetCurrentMapID() == 49)
			{
				GameVariables.SetValue("bGotMantisKey", "1");
			}
			// fall through
		default:
			return;
		}

		GameVariables.GetInt("chronoPieceFlags", chronoBits);
		chronoBits |= (1 << giveBits);

		if(chronoBits == 0xFF)
		{
			// give chronosceptor weapon
			Player.GiveWeapon(TW_WEAPON_CHRONO, 3);
			// Smoke39 - nuke pickup message
			Game.PrintLine( Opt::ChronoType == CH_Chrono ? "$str_156" : "nuke", 0 );
		}

		GameVariables.SetValue("chronoPieceFlags", "" + chronoBits);
		// Smoke39 - update level stats display
		HUD::Level::GotChronoPiece( giveBits );
	}

	/*
	==============================================================
	KnifeAttack
	==============================================================
	*/

	// Smoke39 - more permissive backstab detection when enemy is incapacitated
	// (full range, and check player position rather than facing)
	bool CheckStunnedBackstab( kActor@ other, float dist, float radius )
	{
		TurokEnemy@ script = cast<TurokEnemy@>( ActorScript(other) );
		if ( script is null || !script.IsIncapacitated() ) return false;
		if ( dist > radius + other.Radius() ) return false;
		if ( script.bSedated ) return true; // unconscious enemies always take backstab damage
		return Math::Fabs( Math::Rad2Deg( other.GetTurnYaw(self.Origin()) ) ) > 135;
	}

	void KnifeAttack( kActor @actor, const float arg1, const float arg2, const float arg3, const float arg4 )
	{
		float radius;
		float dist;
		int damage = 0;
		int angle1, angle2;
		int angDiff;
		int nKnife = int(arg1);
		int health;
		TurokEnemy @enemyObj;

		if(actor is null)
		{
			return;
		}

		if(actor.IsStale() || (actor.ScriptObject() is null))
		{
			// actor must be alive and has a script object
			return;
		}

		if(actor.ScriptObject().obj is null)
		{
			// ref handle to script object must exist
			return;
		}

		if((actor.Flags() & AF_HOLDTRIGGERANIM) != 0 ||
			actor.TriggerInvincibility() ||
			(actor.Flags() & AF_DEAD) != 0 ||
			(actor.Flags() & AF_SOLID) == 0)
		{
			return;
		}

		// Smoke39 - LOS check
		if ( !self.CanSee( actor, CF_IGNOREBLOCKERS /*| CF_NOCLIPSTATICS | CF_NOCLIPACTORS*/ ) )
			return;

		// did actor get hit?
		radius = (arg2 * GAME_SCALE);

		dist = Math::Sqrt(actor.DistanceToPoint(m_vStabVector));

		angle1 = int(Math::Rad2Deg(actor.Yaw())) % 360;
		angle2 = int(Math::Rad2Deg( self.Yaw())) % 360;

		if(angle1 < 0) angle1 += 360;
		if(angle2 < 0) angle2 += 360;

		angDiff = (angle1 - angle2);

		// check for backstabs
		bool bBackstabbed = false; // Smoke39
		if ( CheckStunnedBackstab( actor, dist, radius ) // Smoke39
			|| dist <= ((radius * 0.5f) + actor.Radius()) && Math::Abs(angDiff) <= 40 )
		{
			// Smoke39
			bBackstabbed = true;
			if ( MeleeWeaponModel == MT_WARBLADE )
				damage = WarBladeDamage_Back( actor, nKnife );
			else
				damage = BackstabDamage( actor );
		}
		// do regular direct damage
		else if(dist <= (radius + actor.Radius()))
		{
			// Smoke39
			if ( MeleeWeaponModel == MT_WARBLADE )
				damage = WarBladeDamage_Front( actor, nKnife );
			else
				damage = KnifeDamage( actor, nKnife );
		}

		if(damage <= 0)
		{
			return;
		}

		health = actor.Health();
		actor.InflictGenericDamage(self.CastToActor(), "S_Plyr_Knife", damage);

		// very important that we know that all actors that we attack contains a pointer
		// to the TurokEnemy script object class
		if(!(actor.ScriptObject() is null) && !(actor.ScriptObject().obj is null))
		{
			@enemyObj = cast<TurokEnemy@>(actor.ScriptObject().obj);

			if(health > 0 && actor.Health() <= 0 && !(enemyObj is null))
			{
				enemyObj.m_bMortallyWounded = true;
				// Smoke39
				// tell humanoids if they were killed by backstab
				TurokGrunt@ grunt = cast<TurokGrunt@>( ActorScript(actor) );
				if ( grunt !is null ) grunt.bBackstabbed = bBackstabbed;
				// increment melee points
				float meleePoints = GetGameVarF( "MeleePoints" ) + PointsPerMeleeKill[ MeleeWeaponModel ];
				SetGameVarF( "MeleePoints", meleePoints );
				if ( meleePoints >= PointsForWarBlade && !CheckSmoke39Flag(SMOKE39_WARBLADE) )
				{
					SetSmoke39Flag( SMOKE39_WARBLADE, true );
					if ( Opt::MeleeSetting == MT_TALON )
					{
						Game.Print( "War Blade" );
						self.PlaySound( "sounds/shaders/generic_4_non_weapon_pickup.ksnd" );
						Game.SetPickupFlash();
					}
				}
			}
		}

		Game.PlayTactile("tactile/stabmp1p.bnvib", kexVibrationPlayer::CHANNEL_WEAPON, kexVibrationPlayer::POSITION_NEUTRAL);
		KnifeParticles(actor, nKnife, damage);
	}

	// Smoke39 - moved out of KnifeAttack()
	int KnifeDamage( kActor@ A, int nKnife )
	{
		kVec3 defDam;
		if ( A.Definition().GetVector( "knife.damage", defDam ) )
			return int( defDam[ nKnife ] );

		switch ( A.Type() )
		{
			case AT_RAPTOR:      return g_KnifeRaptorHits[ nKnife ];
			case AT_DINOSAUR1:   return g_knifeDimetrondonHits[ nKnife ];
			case AT_RIDER:       return g_KnifeTriceratopsHits[ nKnife ];
			case AT_SANDWORM:    return g_KnifeSubterraneanHits[ nKnife ];
			case AT_STALKER:     return g_KnifeStalkerHits[ nKnife ];
			case AT_ALIEN:       return g_KnifeAlienHits[ nKnife ];
			case AT_PURLIN:      return g_KnifePurlinHits[ nKnife ];
			case AT_MECH:        return g_KnifeRobotHits[ nKnife ];
			case AT_SEWERCRAB:   return g_KnifeSewerCrabHits[ nKnife ];
			case AT_KILLERPLANT: return g_KnifePlantHits[ nKnife ];

			case AT_GRUNT:
			case AT_INSECT:
			case AT_DRAGONFLY:
			case AT_ANIMAL:
			case AT_BOAR:      return g_KnifeHumanHits[ nKnife ];

			case AT_AIBOSS_TREX:       return g_KnifeTrexHits;
			case AT_AIBOSS_CAMPAINGER: return g_KnifeCampaignerHits;
			case AT_AIBOSS_HUNTER:     return g_KnifeLonghunterHits;
			case AT_AIBOSS_HUMMER:     return g_KnifeHummerHits;
			case AT_AIBOSS_MANTIS:     return g_KnifeMantisHits;
		}

		return 0;
	}

	// Smoke39 - moved out of KnifeAttack()
	int BackstabDamage( kActor@ A )
	{
		int defDam;
		if ( A.Definition().GetInt( "knife.backdamage", defDam ) )
			return defDam;

		switch ( A.Type() )
		{
			case AT_GRUNT:
			case AT_ANIMAL:
			case AT_BOAR:
			case AT_AIBOSS_HUMMER: return g_KnifeMortalDeathHits;

			case AT_RAPTOR:
			case AT_DINOSAUR1:
			case AT_RIDER:
			case AT_SANDWORM:
			case AT_STALKER:
			case AT_ALIEN:
			case AT_PURLIN:
			case AT_MECH:      return g_KnifeMortalWoundHits;

			case AT_AIBOSS_TREX:       return g_KnifeTrexHits;
			case AT_AIBOSS_CAMPAINGER: return g_KnifeCampaignerHits;
			case AT_AIBOSS_HUNTER:     return g_KnifeLonghunterHits;
			case AT_AIBOSS_MANTIS:     return g_KnifeMantisHits;
		}

		return 0;
	}

	// Smoke39
	int WarBladeDamage_Front( kActor@ A, int nKnife )
	{
		int dam = KnifeDamage( A, nKnife );
		if ( dam == 0 ) return 0;
		return Math::iCeil( Math::Max( dam * 53 / 41.0f, (dam + g_KnifeMortalWoundHits) / 2.0f ) );
	}
	int WarBladeDamage_Back( kActor@ A, int nKnife )
	{
		// used to be higher for longhunter, keeping just in case any custom actors get set up similarly
		int WBFront = WarBladeDamage_Front( A, nKnife );
		// higher for everything else
		int KBack = Math::iCeil( BackstabDamage( A ) * 53 / 41.0f );
		return Math::Max( WBFront, KBack );
	}

	/*
	==============================================================
	KnifeParticles
	==============================================================
	*/

	void KnifeParticles(kActor @actor, const int nKnife, const int damage)
	{
		kStr redBlood, greenBlood;
		kStr particle;

		// Smoke39 - new effects for T2 talon, and off-hand
		switch(nKnife)
		{
		case 0:
			if ( MeleeWeaponHand == HAND_Right )
			{
				switch ( MeleeWeaponModel )
				{
					case MT_WARBLADE:
					case MT_KNIFE:    redBlood   = "fx/knifeleft_blood.kfx";
					                  greenBlood = "fx/knifeleft_gblood.kfx";         break;
					case MT_TALON:    redBlood   = "fx/T2/Talon/Blood_Red_Left.kfx";
					                  greenBlood = "fx/T2/Talon/Blood_Green_Left.kfx";
				}
			}
			else // left hand
			{
				switch ( MeleeWeaponModel )
				{
					case MT_WARBLADE:
					case MT_KNIFE:    redBlood   = "fx/TPlus/Knife_Offhand_Blood.kfx";
					                  greenBlood = "fx/TPlus/Knife_Offhand_GBlood.kfx";   break;
					case MT_TALON:    redBlood   = "fx/T2/Talon/Blood_Red_Offhand.kfx";
					                  greenBlood = "fx/T2/Talon/Blood_Green_Offhand.kfx";
				}
			}
			break;

		case 1:
			redBlood   = "fx/kniferight_blood.kfx";
			greenBlood = "fx/kniferight_gblood.kfx";
			break;

		case 2:
			switch ( MeleeWeaponModel )
			{
				case MT_KNIFE:    redBlood   = "fx/knifeforward_blood.kfx";
				                  greenBlood = "fx/knifeforward_gblood.kfx";      break;
				case MT_TALON:    redBlood   = "fx/T2/Talon/Blood_Red_Down.kfx";
				                  greenBlood = "fx/T2/Talon/Blood_Green_Down.kfx";
			}
		}

		// Smoke39 - base effects on impact type, rather than actor type
		// proper effects for force field, rather than flesh effects
		// change metallic impact spark from stone to metallic
		// also using this instead of "knife.blood" actor def property 3.0 added
		switch ( actor.ImpactType() )
		{
			case IT_METAL:
				actor.PlaySound( "sounds/shaders/tomahawk_impact_metal.ksnd" );
				particle = "fx/generic_251.kfx";
				break;

			case IT_FORCEFIELD:
				actor.PlaySound( "sounds/shaders/generic_219.ksnd" );
				particle = "fx/generic_187.kfx";
				break;

			case IT_FLESH_HUMAN:
				actor.PlaySound( "sounds/shaders/tomahawk_impact_flesh.ksnd" );
				particle = redBlood;
				break;

			case IT_FLESH_CREATURE:
				actor.PlaySound( "sounds/shaders/tomahawk_impact_flesh.ksnd" );
				particle = greenBlood;
				break;

			default:
				actor.PlaySound( "sounds/shaders/tomahawk_impact_flesh.ksnd" );
				return;
		}

		actor.SpawnProjectile(particle, m_vBloodVector, self.Origin(), Math::Deg2Rad(360));
	}
};
