//
// 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:
//      Weapon Actions
//

#include "scripts/animations.txt"

// Smoke39 - moved weapons into their own files in a new folder
#include "scripts/Weapons/Knife.cs"
#include "scripts/Weapons/Bow.cs"
#include "scripts/Weapons/Pistol.cs"
#include "scripts/Weapons/Rifle.cs"
#include "scripts/Weapons/Minigun.cs"
#include "scripts/Weapons/Shotgun.cs"
#include "scripts/Weapons/AutoShotgun.cs"
#include "scripts/Weapons/PulseRifle.cs"
#include "scripts/Weapons/AlienRifle.cs"
#include "scripts/Weapons/Accelerator.cs"
#include "scripts/Weapons/GrenadeLauncher.cs"
#include "scripts/Weapons/RocketLauncher.cs"
#include "scripts/Weapons/FusionCannon.cs"
#include "scripts/Weapons/Chrono.cs"

enum eInputActions
{
	IA_SCOPE = IA_CUSTOM1,
	IA_MELEE = IA_CUSTOM2
}
enum eButtons
{
	BC_SCOPE = 1 << IA_SCOPE,
	BC_MELEE = 1 << IA_MELEE
}

int  OldWeapon;
uint OldConButtons;

class TurokWeapon : ScriptObjectWeapon
{
    kWeapon @self;
    // Smoke39
    float KnifeTweenDownTime;
    float KnifeTweenUpTime;
    kVec3 KnifeDownOffset;
    float KnifeDownPitch;
	float ScopeMag = 3.0f;
	// weapon variant stuff
	array<kStr> WeaponModels, WeaponAnims;
	array<kVec3> WeaponScales;
	// this is the only one that explicates the default (vecZero, added automatically in OnSpawn())
	// because it's the most likely to be used outside of boilerplate here
	// everything else should be indexed with "WeaponModel-1"
	array<kVec3> WeaponOffsets;
	int WeaponModel;
	bool bPlayedReadySound;

    TurokWeapon(kWeapon @actor)
    {
        @self = actor;
        // Smoke39
        // this lets us distinguish between swapping from another weapon, and loading a save with the weapon up
        OldWeapon = -1;
        bPlayedReadySound = false;
        WeaponModel = 0;
        SetOffhandProperties();
    }

    ~TurokWeapon()
    {
    }

    // Smoke39
    void SetOffhandProperties()
    {
		KnifeTweenDownTime = 0.1;
		KnifeTweenUpTime   = 0.1;
		KnifeDownOffset.Set( 30, -30, -30 );
		KnifeDownPitch = Math::Deg2Rad(25);
    }

    void OnSpawn(void)
    {
        // Smoke39 - do this here instead of ctor to give subclasses a chance to set arrays in ctor first
        WeaponOffsets.insertAt( 0, Math::vecZero );
		kVec3 offset;
		self.Definition().GetVector( "offset", offset );
		for ( uint o = 1;  o < WeaponOffsets.length();  o++ )
			WeaponOffsets[o] -= offset;
    }

    void OnTick(void)
    {
		// Smoke39
		UpdateWeaponSounds();
		if ( !self.Owner().Locked() && Game.ConButtons() & CBC_CHANGEAMMO != 0 && OldConButtons & CBC_CHANGEAMMO == 0 )
		{
			// game doesn't switch ammo during cutscenes, so do it manually when scoped
			if ( Camera.Active() && CanToggleAmmo() )
				self.Owner().UseAltAmmo() = !self.Owner().UseAltAmmo();
			HandleModeToggle();
		}
		KnifeTick();
		ScopeTick();
		CheckWeaponType();
		CheckScale();
		if ( PowerCoreActive() )
			self.RunFxEvent( "PowerCore" );
		if ( IsPlaying(anim_weaponSwapIn) )
		{
			if ( !bPlayedReadySound )
			{
				bPlayedReadySound = true;
				PlayReadySound();
			}
		}
		else
			bPlayedReadySound = false;

		if ( !Player.Locked() ) // no free recharge during cutscenes
		{
			RechargeFlareGun();
			RechargeMinigunShield();
		}

		OldWeapon = self.Owner().CurrentWeapon();
		OldConButtons = Game.ConButtons();
    }

    // Smoke39
    void RechargeFlareGun()
	{
		::RechargeFlareGun();
	}
	void RechargeMinigunShield()
	{
		::RechargeMinigunShield();
	}

	// Smoke39
	void OnBeginFire(void)
	{
		if ( KnifeState <= KNIFE_ACTIVATED )
			BeginFire();
	}
	void BeginFire()
	{
	}

	// Smoke39
    void OnFire(void)
    {
		if ( KnifeState <= KNIFE_ACTIVATED )
			Firing();
    }
    void Firing()
    {
    }

	// Smoke39
    void OnEndFire(void)
    {
		if ( KnifeState <= KNIFE_ACTIVATED )
			EndFire();
    }
    void EndFire()
    {
    }

    // switched weapons
    void OnLower(void)
    {
		if ( IsZoomed() )
			ZoomOut();
    }

    void OnRaise(void)
    {
    }

    // climbing
    void OnHoldster(void)
    {
		if ( IsZoomed() )
			ZoomOut();
    }

	////////////////////////////////////////////////////////////////////////////
	// Smoke39 - weapon variant stuff

	int IntendedModel()
	{
		return 0;
	}

	void PlayReadySound()
	{
	}

	void CheckWeaponType()
	{
		if ( KnifeState > KNIFE_ACTIVATED )
			return;
		if ( WeaponModel != IntendedModel() && !PlayingAttack() )
		{
			int animID = PlayingID();
			ResetModel();
			self.AnimState().Set( animID, 4.0f, 0 );
		}
	}

	void CheckScale()
	{
		// weapons often default to 0,0,0 scale, to prevent flashing wrong model for a frame on swap-in
		// offhand actions also do this, to prevent an edge case that could flash the knife on swap-in
		// CheckWeaponType(), and ResetModel() via KnifeTick(), should undo this most of the time
		// but this additional check is needed for at least one edge case
		// (loading save with a 0,0,0 scale weapon already held)
		if ( KnifeState != KNIFE_SWIPE && Equal( self.Scale(), Math::vecZero ) )
		{
			// make visible
			ResetScale();
			// restart anim, so we don't miss the first frame
			self.AnimState().Set( PlayingID(), 4.0f, 0 );
		}
	}

	////////////////////////////////////////////////////////////////////////////
	// Smoke39 - convenience functions

	kPuppet@ OwnerP() { return self.Owner().Actor(); }
	kActor@  OwnerA() { return self.Owner().Actor().CastToActor(); }

	//-------------------------------------------------------------------------

	bool HasAmmo()
	{
		return self.Owner().HasAmmo( self.Owner().CurrentWeapon() );
	}
	bool HasMainAmmo()
	{
		return self.Owner().HasAmmo( self.Owner().CurrentWeapon(), false );
	}
	bool HasAltAmmo()
	{
		return self.Owner().HasAltAmmo();
	}
	bool UsingAltAmmo()
	{
		return self.Owner().UseAltAmmo();
	}
	bool HasOtherAmmo()
	{
		if ( self.Owner().UseAltAmmo() )
			return HasMainAmmo();
		return HasAltAmmo();
	}

	int GetAmmo()
	{
		return self.Owner().GetAmmo( self.Owner().CurrentWeapon() );
	}
	int GetAltAmmo()
	{
		return self.Owner().GetAltAmmo( self.Owner().CurrentWeapon() );
	}
	int GetLoadedAmmo()
	{
		return UsingAltAmmo() ? GetAltAmmo() : GetAmmo();
	}

	bool CanToggleAmmo()
	{
		return HasOtherAmmo() && GetCvarB( "g_changeammotoggle", true );
	}

	void UseAmmo( int amt )
	{
		bool bAlt = self.Owner().UseAltAmmo();
		self.Owner().ConsumeAmmo( amt );
		// if we ran out of current ammo type and switched, give opportunity to play sound
		if ( self.Owner().UseAltAmmo() != bAlt && HasAmmo() )
			AutoAmmoChange();
	}

	void AutoAmmoChange()
	{
	}

	//-------------------------------------------------------------------------

	kVec3 EyePos()
	{
		kPuppet @src = self.Owner().Actor();
		kVec3 v = src.Origin();
		v.z += src.ViewHeight() + src.LandingViewOffset();
		return v;
	}

	kVec3 FOVOffset( const array<kVec3>&in offsets )
	{
		float FOV = GetCvarF( "r_fov", 74 );
		if ( FOV <= 74 )
			return Math::Lerp( offsets[0], offsets[1], (FOV -  47.5f) / ( 74.0f -  47.5f) );
		else if ( FOV <= 90 )
			return Math::Lerp( offsets[1], offsets[2], (FOV -  74.0f) / ( 90.0f -  74.0f) );
		else if ( FOV <= 110 )
			return Math::Lerp( offsets[2], offsets[3], (FOV -  90.0f) / (110.0f -  90.0f) );
		else
			return Math::Lerp( offsets[3], offsets[4], (FOV - 110.0f) / (120.0f - 110.0f) );
	}
	float FOVOffset( const array<float>&in offsets )
	{
		float FOV = GetCvarF( "r_fov", 74 );
		if ( FOV <= 74 )
			return Math::Lerp( offsets[0], offsets[1], (FOV -  47.5f) / ( 74.0f -  47.5f) );
		else if ( FOV <= 90 )
			return Math::Lerp( offsets[1], offsets[2], (FOV -  74.0f) / ( 90.0f -  74.0f) );
		else if ( FOV <= 110 )
			return Math::Lerp( offsets[2], offsets[3], (FOV -  90.0f) / (110.0f -  90.0f) );
		else
			return Math::Lerp( offsets[3], offsets[4], (FOV - 110.0f) / (120.0f - 110.0f) );
	}

	kVec3 ProjSpawnLoc( kVec3 offset )
	{
		return EyePos() + ( offset * self.Owner().Actor().Rotation() );
	}
	kVec3 ProjSpawnLoc( float x, float y, float z )
	{
		return ProjSpawnLoc( kVec3(x,y,z) );
	}

	void SpawnProj( const kStr&in type, const kVec3&in offset, float transRand,
	                const array<kStr>@ tracer = null )
	{
		SpawnProj( type, offset, kVec3(0,1,0).Randomize(transRand).ToQuat(), tracer );
	}

	void SpawnProj( const kStr&in type, float x, float y, float z, float transRand,
	                const array<kStr>@ tracer = null )
	{
		SpawnProj( type, kVec3(x,y,z), transRand, tracer );
	}

	void SpawnProj( const kStr&in type, const kVec3&in offset, const kQuat&in offsetRot,
	                const array<kStr>@ tracer = null )
	{
		kPuppet @src = self.Owner().Actor();
		kVec3 loc = ProjSpawnLoc( offset );
		kQuat rot = offsetRot;
		rot *= src.Rotation();
		Game.SpawnFx( type, src, loc, rot );
		if ( tracer is null )
			return;
		uint max = tracer.length() - 1;
		for ( uint i = 0;  i < max;  i++ )
		{
			float f = i;
			// safety buffer in case of rounding errors
			if ( i == 0 )
				f += 0.01f;
			if ( Game.GetGameSpeed() >= Math::Lerp( 1.0f, 0.2f, f / float(max) ) )
			{
				Game.SpawnFx( tracer[i], src, loc, rot );
				return;
			}
		}
		// rather than checking if game speed >= 0.2 in the loop, stop early
		// and spawn the slowest version if none of the faster ones qualify
		Game.SpawnFx( tracer[max], src, loc, rot );
	}

	void SpawnProj( const kStr&in type, float x, float y, float z, const kQuat&in offsetRot,
	                const array<kStr>@ tracer = null )
	{
		SpawnProj( type, kVec3(x,y,z), offsetRot, tracer );
	}

	//-------------------------------------------------------------------------

	int PlayingID()
	{
		return self.AnimState().PlayingID();
	}
	bool IsPlaying( int animID )
	{
		return self.AnimState().IsPlaying( animID );
	}

	float PlayTime()
	{
		return self.AnimState().PlayTime();
	}
	float TrackTime()
	{
		return self.AnimState().TrackTime();
	}

	bool PlayingAttack()
	{
		switch ( PlayingID() )
		{
			case anim_weaponAttack1:  case anim_weaponAttack2:  case anim_weaponAttack3:
			case anim_weaponFire:  case anim_weaponFireCharged:  case anim_weaponFireLoop:
			case anim_weaponAttackUnderwater:  case anim_weaponFireBowNoAmmo:
				return true;
		}
		return false;
	}

	////////////////////////////////////////////////////////////////////////////
	// Smoke39 - mode toggle

	void HandleModeToggle()
	{
	}

	////////////////////////////////////////////////////////////////////////////
	// Smoke39 - SCOPE

	bool HasScope()
	{
		return false;
	}

	bool IsZoomed()
	{
		return PlayerScoped();
	}

	// conditions common to both allowing zooming in, and zooming out if not met
	// additional conditions specific to one or the other are in ScopeTick()
	bool CanZoom()
	{
		return HasScope() && OwnerP().OnGround() && GetAreaFlags( OwnerP() ) & AAF_CLIMB == 0
			&& (KnifeState <= KNIFE_ACTIVATED || (KnifeState >= KNIFE_WEPUP && KnifeDownPct < 0.5))
			&& !IsPlaying( anim_weaponSwapOut );
	}

	void ZoomIn()
	{
		Camera.StartCinematic( CMF_NO_LETTERBOX | CMF_SHOW_HIDDEN_OBJECTS | CMF_NO_INITIAL_FADEOUT );
		// at least one of these allows camera position to be updated in OnTick() after key acquisition cutscene
		Camera.ClearLookAtActor();
		Camera.ClearFinalView();
		Camera.ClearViewTracks();
	}
	void ZoomOut()
	{
		CancelScope();
	}

	void ScopeTick()
	{
		if ( self.Owner().ButtonHeldTime(IA_SCOPE) == 1 )
		{
			if ( !self.Owner().Locked() )
			{
				if ( Camera.Active() )
					ZoomOut();
				else if ( CanZoom() && (!IsPlaying(anim_weaponSwapIn) || TrackTime() > 0.5f) )
					ZoomIn();
			}
		}

		if ( IsZoomed() )
		{
			if ( !CanZoom() )
			{
				ZoomOut();
				return;
			}

			Camera.fov = GetCvarF("r_fov",74) / ScopeMag;

			Camera.origin    = EyePos();
			Camera.pitch     = self.Owner().Actor().Pitch();
			Camera.yaw       = self.Owner().Actor().Yaw();
			Camera.roll      = self.Owner().Actor().Roll();
			self.Owner().LookSensScale() = 1 / ScopeMag;

			ScopeView();
		}
		// reset sensitivity if cutscene interrupted scope
		else if ( Camera.Active() )
			self.Owner().LookSensScale() = 1;
	}

	// spawn/update/render reticle, scope border, etc.
	void ScopeView()
	{
	}

	////////////////////////////////////////////////////////////////////////////
	// Smoke39 - QUICK KNIFE

	int KnifeTick()
	{
		if ( self.Owner().ButtonHeldTime(IA_MELEE) == 1 && CanUseOffhand() )
			SetOffhand( OFFHAND_KNIFE );

		// player changed weapons
		if ( self.Owner().CurrentWeapon() != OldWeapon )
		{
			// only do this if switching from another weapon, not when loading a save
			if ( OldWeapon != -1 )
			{
				// edge case when switching to another weapon during KNIFE_WEPUP
				if ( !IsPlaying(anim_weaponSwapIn) )
					OnLower();
				else
				{
					// in case we were put down while knifing
					// this is from before the above edge case was fixed, and could maybe be moved up there now
					// (reset when swapping out, rather than when swapping back in)
					ResetModel();
					// changing model resets anim, so we need to restart select anim
					self.AnimState().Set( anim_weaponSwapIn, 4, 0 );
					if ( KnifeState > KNIFE_ACTIVATED )
						KnifeState = KNIFE_IDLE;
				}
			}
		}

		bKnifeCanQueue = false;

		// climbing
		if ( GetAreaFlags( Player.Actor() ) & AAF_CLIMB != 0 )
		{
			if ( KnifeState == KNIFE_SWIPE )
				ResetModel();
			if ( Player.Actor().OnGround() && PlayingID() != anim_weaponSwapOut )
				self.AnimState().Set( anim_weaponSwapOut, 4, 0 );
			ResetOffset();
			return KnifeState = KNIFE_IDLE;
		}

		// knife state
		switch ( KnifeState )
		{
			case KNIFE_ACTIVATED:
				// only react to offhand button if fire button is not held
				// but if offhand action was accepted, but we're still waiting for fire anim to complete,
				//   check bKnifeFireQueued so fire button doesn't clear KnifeState
				if ( Player.Buttons() & BC_ATTACK == 0 || bKnifeFireQueued )
					OnKnifeActivated();
				else
					KnifeState = KNIFE_IDLE;
				break;
			case KNIFE_WEPDOWN:  OnKnifeWepDown();  break;
			case KNIFE_SWIPE:    OnKnifeSwipe();    break;
			case KNIFE_WEPUP:    OnKnifeWepUp();    break;
		}

		return KnifeState;
	}

	//-------------------------------------------------------------------------
	// KNIFE STATES

	// knife button pressed
	void OnKnifeActivated()
	{
		switch ( PlayingID() )
		{
			// idle
			case anim_weaponIdle: case anim_weaponIdleUnderwater:
			case anim_weaponWalk: case anim_weaponRun:
			case anim_weaponSwapIn: case anim_weaponSwapOut:
				if ( !bKnifeQueued )
					TweenToKnife();
				KnifeDownPct = 0;
				++KnifeState;
				break;
			// attacking
			default:
				if ( self.AnimState().Stopped() || KnifeCanInterruptFiring() )
				{
					TweenToKnife();
					KnifeDownPct = 0;
					++KnifeState;
				}
				else if ( !bKnifeFireQueued )
				{
					if ( !KnifeCanQueueWhileFiring() )
						KnifeState = KNIFE_IDLE;
					else
					{
						bKnifeFireQueued = true;
						KnifeQueueSpeedup();
					}
				}
				break;
		}
	}

	// lowering weapon
	void OnKnifeWepDown()
	{
		if ( KnifeDownPct < 1 )
			LowerWeapon( 1 );
		else
		{
//			SetKnifeModel(); // moved to SwipeKnife()
//			OffsetKnife(); // moved to SwipeKnife()
			SwipeKnife();
		}
	}

	// swiping
	void OnKnifeSwipe()
	{
		if ( KnifeAnimPlaying() )
		{
			OffsetKnife();
			// hide the knife, in case we switch weapons, so when we switch back we won't still see the knife for a frame before resetting the model
			switch ( OffhandAction )
			{
				case OFFHAND_KNIFE:
					if ( self.AnimState().CurrentFrame() == self.AnimState().NumFrames()-1 )
						self.Scale() = Math::vecZero;
//					if ( self.AnimState().CurrentFrame() >= 10 )
					if ( TrackTime() >= 0.8f )
						bKnifeCanQueue = true;
					break;
				case OFFHAND_GRENADE:
					self.ModelVariation() = Opt::HandGrenade;
					if ( self.AnimState().CurrentFrame() == 10 )
						self.Scale() = Math::vecZero;
					// hide after it goes offscreen
					if ( self.AnimState().CurrentFrame() >= 6 )
					{
						bKnifeCanQueue = true;
						self.Scale() = Math::vecZero;
					}
					if ( !bOffhandGrenadeThrown && TrackTime() >= 0.5f )
					{
						ConsumeGrenade();
						self.PlaySound( "sounds/shaders/generic_122_throw_grenade_swoosh.ksnd" );
						self.FireProjectile( Opt::HandGrenade == HG_Exp ?
							"fx/TPlus/Grenade_Thrown.kfx" : "fx/T2/Sunfire/Pod_Offhand.kfx",
							Math::Sign( self.Scale().x ) * 18.432f, 25.696f, -15.0f );
						bOffhandGrenadeThrown = true;
						self.RenderModel().SetVisibility( 1, false ); // grenade
						self.RenderModel().SetVisibility( 2, false ); // sunfire
					}
					break;
			}
		}
		else if ( bKnifeQueued )
		{
			OffhandAction = QueuedOffhandAction;
//			OffsetKnife(); // moved to SwipeKnife()
			SwipeKnife();
		}
		else
		{
			ResetModel();
			LowerWeapon( 1, true );
			TweenFromKnife();
			bKnifeCanQueue = true;
			++KnifeState;
		}
	}

	// raising weapon
	void OnKnifeWepUp()
	{
		// in case we queued on the exact frame KNIFE_SWIPE ended
		if ( bKnifeQueued )
			KnifeState = KNIFE_WEPDOWN;
		// raising
		else if ( KnifeDownPct > 0 )
			LowerWeapon( -1 );
		// up
		else
		{
			ResetOffset();
			if ( bKnifeQueued )
				KnifeState = KNIFE_ACTIVATED;
			else
			{
				KnifeState = KNIFE_IDLE;
				KnifeWepUpFinished();
			}
		}
	}

	//-------------------------------------------------------------------------
	// OTHER KNIFE STUFF

	void SwipeKnife()
	{
		SetKnifeModel();
		OffsetKnife();

		switch ( OffhandAction )
		{
			case OFFHAND_KNIFE:
				// anim_weaponAttack1 - left
				// anim_weaponAttack2 - right
				// anim_weaponAttack3 - down
				if ( MeleeWeaponModel == MT_WARBLADE )
				{
					// war blade has a dedicated off-hand attack anim, which deploys and retracts the blade
					self.AnimState().Set( anim_weaponAttack3, 3, ANF_NOINTERRUPT );
					self.PlaySound( "sounds/shaders/T2/WarBlade/Ready_Offhand.ksnd" );
					self.PlaySound( "sounds/shaders/T2/WarBlade/Swoosh_" + (1 + Math::RandMax(2)) + ".ksnd" );
				}
				else
				{
					self.AnimState().Set( anim_weaponAttackUnderwater, 3, ANF_NOINTERRUPT );
					// talon anim is a little shorter, so play a bit slower to match knife
					if ( MeleeWeaponModel == MT_TALON )
						self.AnimState().ChangeSpeed( 3.0f * 14.5f / self.AnimState().NumFrames() );
					self.PlaySound( "sounds/shaders/knife_swish_" + (1 + Math::RandMax(3)) + ".ksnd" );
				}
				break;

			case OFFHAND_GRENADE:
				self.RenderModel().SetVisibility( 1, true ); // grenade
				self.RenderModel().SetVisibility( 2, true ); // sunfire
				self.AnimState().Set( anim_weaponAttack3, 5.5f, ANF_NOINTERRUPT );
				if ( Opt::HandGrenade == HG_Exp )
					self.PlaySound( "sounds/shaders/TPlus/Grenade_Thrown_Prime.ksnd" );
				bOffhandGrenadeThrown = false;
				break;
		}

		KnifeState = KNIFE_SWIPE;
		bKnifeQueued = false;
		bKnifeFireQueued = false;
		SetKnifeScale();
	}

	void ConsumeGrenade()
	{
		// "giving" negative ammo works even when infinite ammo is on, so bail out if it is
		if ( Game.IsCheatActive( GC_INFINITE_AMMO ) ) return;
		self.Owner().GiveAmmo( TW_WEAPON_GRENADE, -1, false );
		Game.PrintLine( ""+ self.Owner().GetAmmo( TW_WEAPON_GRENADE ) +" grenades remaining", 0 );
	}

	bool KnifeAnimPlaying()
	{
		switch ( PlayingID() )
		{
			case anim_weaponAttack1:
			case anim_weaponAttack2:
			case anim_weaponAttack3:
			case anim_weaponAttackUnderwater:
				return true;
		}
		return false;
	}

	void LowerWeapon( float dir, bool bClearInterp = false )
	{
		float tweenTime = dir > 0 ? KnifeTweenDownTime : KnifeTweenUpTime;
		KnifeDownPct = Math::Clampf(
			KnifeDownPct + dir * (0.25f + 0.5f * KnifeDownPct) / (tweenTime / 2) * GAME_DELTA_TIME,
			0.0f, 1.0f );
		float f = Math::Sqr( KnifeDownPct );
		self.RenderModel().Offset() = WeaponOffsets[ WeaponModel ] + KnifeDownOffset * f;
		if ( bClearInterp )
			self.RenderModel().PrevOffset() = self.RenderModel().Offset();
		self.RenderModel().SetRotationOffset( 0, f * KnifeDownPitch, 1,0,0, bClearInterp );
	}

	int Offhandedness()
	{
		return HAND_Left;
	}

	void SetKnifeModel()
	{
		// some weapons like to mess with this, so reset it
		self.ModelVariation() = 0;
		int type = MeleeWeaponType();
		kStr model, anim;
		switch ( OffhandAction )
		{
			case OFFHAND_KNIFE:
				model = MeleeWeaponModels[ type ];
				anim = MeleeWeaponAnims[ type ];
				MeleeWeaponModel = type;
				break;
			case OFFHAND_GRENADE:
				model = "models/TPlus/dyn_HandGrenade";
				anim = "anims/dyn_knife_anim.bin";
				break;
		}
		MeleeWeaponHand = Offhandedness();
		if ( MeleeWeaponHand == HAND_Left )
			model += "_Reverse";
		self.RenderModel().SetModel( model + ".bin", anim );
	}
	void SetKnifeScale()
	{
		if ( OffhandAction == OFFHAND_GRENADE )
			self.Scale() = kVec3( 1, 1, 1 );
		else
			self.Scale() = MeleeWeaponScales[ MeleeWeaponModel ];

		if ( Offhandedness() == HAND_Left )
			self.Scale().x = -self.Scale().x;
	}
	void OffsetKnife()
	{
		kVec3 offset, mOffset;
		self.Definition().GetVector( "offset", offset );
		if ( OffhandAction == OFFHAND_GRENADE )
			mOffset = kVec3(170.667,153.6,-9.216);
		else
			mOffset = MeleeWeaponOffsets[MeleeWeaponModel];
		if ( Offhandedness() == HAND_Left )
			mOffset.x = -mOffset.x;
		self.RenderModel().Offset() = mOffset - offset;
		self.RenderModel().PrevOffset() = self.RenderModel().Offset();
	}

	int KnifeTween()
	{
/*		if ( self.AnimState().CheckAnimID(anim_weaponFireCharged) )
			return anim_weaponFireCharged;
		if ( self.AnimState().CheckAnimID(anim_weaponFire) )
			return anim_weaponFire;
		if ( self.AnimState().CheckAnimID(anim_weaponFireLoop) )
			return anim_weaponFireLoop;
		Sys.Warning( "no fire anim" );
		return -1;
*/
		return anim_weaponIdle;
	}
	void TweenToKnife()
	{
		// some weapons set no interrupt flag for their fire anim, so we need to make sure it's cleared here
		self.AnimState().flags &= ~ANF_NOINTERRUPT;
		self.AnimState().Blend( KnifeTween(), 9999, 4, ANF_NOINTERRUPT );
	}
	void TweenFromKnife()
	{
		self.AnimState().Set( KnifeTween(), 9999, ANF_NOINTERRUPT );
	}
	void KnifeWepUpFinished()
	{
		self.AnimState().Stop();
//		self.AnimState().Blend( anim_weaponIdle, 4.0, 4.0, ANF_LOOP );
	}

	void ResetModel()
	{
		// some offhand weapons like to mess with this, so reset it
		self.ModelVariation() = 0;
		WeaponModel = IntendedModel();
		if ( WeaponModel == 0 )
		{
			kStr model, anim;
			self.Definition().GetString( "model", model );
			self.Definition().GetString( "anim", anim );
			self.RenderModel().SetModel( model, anim );
			self.Scale().Set( 1, 1, 1 );
		}
		else
		{
			self.RenderModel().SetModel( WeaponModels[ WeaponModel - 1 ], WeaponAnims[ WeaponModel - 1 ] );
			self.Scale() = WeaponScales[ WeaponModel - 1 ];
		}
		self.RenderModel().Offset() = WeaponOffsets[ WeaponModel ];
		self.RenderModel().PrevOffset() = self.RenderModel().Offset();
		SetOffhandProperties();
	}

	void ResetOffset()
	{
		self.RenderModel().Offset() = WeaponOffsets[ WeaponModel ];
		self.RenderModel().SetRotationOffset( 0, 0, 0,0,0 );
	}

	void ResetScale()
	{
		self.Scale() = WeaponModel == 0 ? kVec3(1,1,1) : WeaponScales[ WeaponModel - 1 ];
	}

	// copied from TurokKnife
	// horizontal slash animation calls this at the time it wants to deal damage
    void KnifeAttack1(kActor @instigator, const float w, const float x, const float y, const float z)
    {
        kPuppet @src = self.Owner().Actor();

        TurokPlayer @p = cast<TurokPlayer@>(src.ScriptObject().obj);
        p.m_vBloodVector = kVec3(0, (w * GAME_SCALE), 0);
        p.m_vBloodVector.z += (GAME_SCALE * 3);

        p.m_vStabVector = (kVec3(0, (w * GAME_SCALE), 0) * src.Rotation());
        p.m_vStabVector += src.Origin();
        p.m_vStabVector.z += (GAME_SCALE * 3);

        src.InteractActorsAtPosition(p.m_vStabVector, "KnifeAttack", 0, w);

        // revert warblade to normal speed after swiping
        if ( MeleeWeaponModel == MT_WARBLADE )
			self.AnimState().ChangeSpeed( 4.2f );
    }

	// copied from TurokKnife so we don't get console warnings when throwing grenades
	void KnifeAttack3( kActor @instigator, const float w, const float x, const float y, const float z )
	{
	}

	bool KnifeCanQueueWhileFiring()
	{
		return false;
	}
	bool KnifeCanInterruptFiring()
	{
		return false;
	}
	void KnifeQueueSpeedup()
	{
		self.AnimState().ChangeSpeed( 2 );
	}
}

//==============================================================================
//
//    WEAPON SOUNDS
//
//==============================================================================

enum eWeaponSoundSlot { WSS_General, WSS_Extra, WSS_COUNT }
array<kActor@> WeaponSounds( WSS_COUNT );

void PlayWeaponSound( kStr&in sound, uint slot = WSS_General )
{
	if ( Exists(WeaponSounds[slot]) ) WeaponSounds[slot].PlaySound( sound );
}

void StopWeaponSound( uint slot = WSS_General )
{
	if ( Exists(WeaponSounds[slot]) ) WeaponSounds[slot].StopSound();
}

void InitWeaponSounds()
{
	for ( uint i = 0;  i < WeaponSounds.length();  i++ )
	{
		@WeaponSounds[i] = Spawn( -1, Player.Actor().Origin(), 0, Player.Actor().SectorIndex() );
		if ( WeaponSounds[i] !is null ) WeaponSounds[i].Height() = WeaponSounds[i].Radius() = 0;
	}
}
void ClearWeaponSounds()
{
	for ( uint i = 0;  i < WeaponSounds.length();  i++ )
		@WeaponSounds[i] = null;
}
void UpdateWeaponSounds()
{
	for ( uint i = 0;  i < WeaponSounds.length();  i++ )
	{
		if ( WeaponSounds[i] is null ) continue;
		if ( WeaponSounds[i].IsStale() ) @WeaponSounds[i] = null;
		else WeaponSounds[i].SetPosition( Player.Actor().Origin() );
	}
}

//==============================================================================
//
//    OFFHAND
//
//==============================================================================

array<kStr> MeleeWeaponModels =
{
	"models/dyn_knife",
	"models/T2/Weapon_Talons",
	"models/T2/Weapon_War_Blade"
};
array<kStr> MeleeWeaponAnims =
{
	"anims/dyn_knife_anim.bin",
	"anims/T2/Weapon_Talons_Anim.bin",
	"anims/T2/Weapon_War_Blade_Anim.bin"
};
array<kVec3> MeleeWeaponOffsets =
{
	kVec3( 170.667f, 153.6f, -9.216f ), // T1
	kVec3( 124, 200, -145 ),            // T2 talon
	kVec3( 124, 200, -145 )             // T2 warblade
};
array<kVec3> MeleeWeaponScales =
{
	kVec3( 1, 1, 1 ),
	kVec3( 0.1f, 0.1f, 0.1f ),
	kVec3( 0.1f, 0.1f, 0.1f )
};

enum eKnifeState {
	KNIFE_IDLE,
	KNIFE_ACTIVATED,
	KNIFE_WEPDOWN,
	KNIFE_SWIPE,
	KNIFE_WEPUP
}

enum eOffhandAction {
	OFFHAND_KNIFE,
	OFFHAND_GRENADE
}

int KnifeState = KNIFE_IDLE;
int OffhandAction, QueuedOffhandAction;
float KnifeDownPct = 0;
bool bKnifeQueued = false;     // pressed knife key during end of swipe anim
bool bKnifeFireQueued = false; // pressed knife key while firing weapon
bool bKnifeCanQueue = false;
bool bOffhandGrenadeThrown;

bool CanUseOffhand()
{
	return !Player.Locked() &&
		(World.GetAreaFlags(Player.Actor().AreaID()) & AAF_CLIMB == 0 || !Player.Actor().OnGround());
}

void SetOffhand( eOffhandAction action )
{
	if ( KnifeState == KNIFE_IDLE )
	{
		KnifeState = KNIFE_ACTIVATED;
		OffhandAction = action;
	}
	else if ( KnifeState == KNIFE_WEPUP )
	{
		KnifeState = KNIFE_WEPDOWN;
		OffhandAction = action;
	}
	else if ( bKnifeCanQueue )
	{
		bKnifeQueued = true;
		QueuedOffhandAction = action;
	}
}

// offhand grenade key function
void QuickGrenade()
{
	if ( CanUseOffhand() && !Player.Actor().InWater() )
	{
		if ( Player.HasAmmo( TW_WEAPON_GRENADE ) )
			SetOffhand( OFFHAND_GRENADE );
		else
			Game.PrintLine( "out of grenades", 0, 60 );
	}
}
void quickgrenade()
{
	QuickGrenade();
}

//==============================================================================
//
//    DEBUG
//
//==============================================================================

kStr AnimStr( int anim )
{
	switch ( anim )
	{
		case anim_weaponIdle:              return "anim_weaponIdle";
		case anim_weaponWalk:              return "anim_weaponWalk";
		case anim_weaponRun:               return "anim_weaponRun";
		case anim_weaponAttack1:           return "anim_weaponAttack1";
		case anim_weaponAttack2:           return "anim_weaponAttack2";
		case anim_weaponAttack3:           return "anim_weaponAttack3";
		case anim_weaponFire:              return "anim_weaponFire";
		case anim_weaponFireCharged:       return "anim_weaponFireCharged";
		case anim_weaponSwapIn:            return "anim_weaponSwapIn";
		case anim_weaponSwapOut:           return "anim_weaponSwapOut";
		case anim_weaponFireLoop:          return "anim_weaponFireLoop";
		case anim_weaponAttackUnderwater:  return "anim_weaponAttackUnderwater";
		case anim_weaponIdleUnderwater:    return "anim_weaponIdleUnderwater";
		case anim_weaponFireBowNoAmmo:     return "anim_weaponFireBowNoAmmo";
	}
	return "other";
}

kStr KnifeStateStr( int state )
{
	switch ( state )
	{
		case KNIFE_IDLE:       return "KNIFE_IDLE";
		case KNIFE_ACTIVATED:  return "KNIFE_ACTIVATED";
		case KNIFE_WEPDOWN:    return "KNIFE_WEPDOWN";
		case KNIFE_SWIPE:      return "KNIFE_SWIPE";
		case KNIFE_WEPUP:      return "KNIFE_WEPUP";
	}
	return "invalid knife state";
}
