// kd: New Chillgrasp code. Addresses a bunch of shortcomings, notably working
// with portals, though silent teleporters will not be regarded at all.

class Gc_IsGrasping : Inventory {	// kd: Currently chillgrasping somebody
	default {
		Inventory.MaxAmount 1;
	}
}

class Gc_IsGrasped : Inventory {	// kd: Currently being chillgrasped
	default {
		Inventory.MaxAmount 1;
	}
}

class Gc_ChillPuff : Actor {
	default {
		+ALLOWTHRUFLAGS
		+THRUACTORS
		+NOTONAUTOMAP
		+NOBLOCKMAP
		RenderStyle "None";
	}
}

class Gc_ChillScanPuff : Actor {
	default {
		+NOTONAUTOMAP
		+BLOODLESSIMPACT
		+NOBLOCKMAP
		RenderStyle "None";
	}
}

class Gc_GraspThinker : Thinker {
	private Actor    user;
	private Actor    target;
	private Actor    hold_spot;
	private bool     holding;
	private bool     old_holding;
	private uint     hold_tics;
	private float    offset_ang;
	private bool     override_hp_view;
	
	override void PostBeginPlay () {
		hold_spot = Actor.Spawn("Mapspot");
		super.PostBeginPlay();
	}
	
	override void Tick () {
		if(holding) {
			if(!target) {
				holding = false;
			}
			
			else {
				ForceFlags();
				UpdateHoldPos(200.0f, offset_ang);
				UpdateTargetMovement(0.2f);
				CancelIfOutOfReach(350.0f);
				HandleHpView();
				
				if( !(target is 'PlayerPawn') ) {
					target.angle = user.angle;
				}
				
				hold_tics++;
				
				if(6 < hold_tics) {
					hold_tics = 0;
					ApplyDamage("ChillgraspDamage");
				}
			}
		}
		
		bool stopped_holding = old_holding && !holding;
		
		if(stopped_holding && target) {
			TossTarget(40.0, 5.0);
			ClearTargetHeld();
			target = NULL;
		}
		
		old_holding = holding;
		super.Tick();
	}
	
	private void HandleHpView () {
		if(override_hp_view) {
			let handler = Gc_HealthView(Gc_HealthView.Find("Gc_HealthView"));
			
			if(handler) {
				handler.OverrideTarget(target);
			}
		}
	}
	
	void Init (Actor p_user) {
		ChangeStatNum(STAT_SCRIPTS); // kd: Later than actors, just what we need
		user = p_user;
	}
	
	Actor ScanForTargets (float range) {
		FTranslatedLineTarget   linetarget;
		Actor                   puff_dummy;
		int                     unused;
		
		[puff_dummy, unused] = user.LineAttack(
			user.angle, range, user.pitch, 0, '', "Gc_ChillScanPuff",
			LAF_NOIMPACTDECAL | LAF_NORANDOMPUFFZ,
			linetarget);
		
		return linetarget.linetarget;
	}
	
	void BeginHold (Actor p_target, float off_ang = 25) {
		if(p_target && !target && p_target.bshootable) {
			offset_ang = off_ang;
			hold_tics  = 0;
			target     = p_target;
			holding    = true;
			user.GiveInventory("Gc_IsGrasping", 1);
			target.GiveInventory("Gc_IsGrasped", 1);
			
			override_hp_view = CvarEx.GetBoolDef(
				"gc_hpview_prefergrasped",
				user.player,
				false);
		}
	}
	
	static bool IsGrasping (Actor who) {
		// console.printf("\c[ice]IsGrasping called");
		if(who) {
			// if(0 < who.CountInv("Gc_IsGrasping")) console.printf("\c[ice]You have grasping token");
			return 0 < who.CountInv("Gc_IsGrasping");
		}
		
		return false;
	}
	
	static bool IsGrasped (Actor who) {
		// console.printf("\c[sapphire]IsGrasped called");
		if(who) {
			// if(0 < who.CountInv("Gc_IsGrasped")) console.printf("\c[sapphire]target has token");
			return 0 < who.CountInv("Gc_IsGrasped");
		}
		
		return false;
	}
	
	bool TargetIsHeldAndAlive () {
		if(target) {
			return holding && 0 < target.health;
		}
		
		return false;
	}
	
	void EndHold () {
		holding = false;
		user.TakeInventory("Gc_IsGrasping", int.max);
		
		if(target) {
			user.TakeInventory("Gc_IsGrasped", int.max);
		}
	}
	
	private void ApplyDamage (class <Actor> expl_class) {
		let spawn_pos = target.vec3offset(0, 0, target.height * 0.5);
		
		Actor spawned = Actor.Spawn(expl_class, spawn_pos);
		
		if(spawned) {
			spawned.target = user.bmissile ? user.target : user;
		}
	}
	
	bool IsHolding () {
		return holding;
	}
	
	// kd: The rest will be handled off in Tick. You don't call these update
	// functions.
	
	private void ForceFlags () {
		target.bslidesonwalls = true;
		target.bnoblockmonst  = true;
	}
	
	// kd: Scans for obstacles, so as to not carry the actor outside by
	// accident. Otherwise, will extend hold position to somewhere in front
	// of you.
	
	private void UpdateHoldPos (float hold_len, float off_ang) {
		FTranslatedLineTarget linetarget;
		
		Actor   puff_dummy;
		int     unused;
		float   ang        = user.angle + off_ang;
		float   vang       = user.pitch;
		
		[puff_dummy, unused] = user.LineAttack(
			ang, hold_len, vang, 0, '', "Gc_ChillPuff",
			LAF_NOIMPACTDECAL | LAF_NORANDOMPUFFZ,
			linetarget);
		
		bool hit_something = puff_dummy != NULL;
		Vector3 hold_pos;
		
		if(hit_something) {
			hold_pos = puff_dummy.pos;
		}
		
		else {
			float r_cosvang = cos(vang) * hold_len;
			
			hold_pos = (
				r_cosvang * cos(ang)
			,	r_cosvang * sin(ang)
			,  -hold_len  * sin(vang) + 41.0);
			
			hold_pos = user.Vec3Offset(hold_pos.x, hold_pos.y, hold_pos.z);
		}
		
		hold_spot.SetOrigin(hold_pos, true);
	}
	
	private void CancelIfOutOfReach (float reach) {
		vector3 offset = target.Vec3To(hold_spot);
		// vector3 offset = levellocals.vec3diff(target.pos, hold_spot.pos);
		
		// kd: There was a function for this. I'm too lazy to look it up, hu.
		if(reach * reach < offset dot offset) {
			holding = false;
		}
	}
	
	Actor Grasped () const {
		return target;
	}
	
	// kd: The grabbed actor will cease falling and gradually move towards
	// the dummy hold spot.
	
	private void UpdateTargetMovement (float rate) {
		rate = clamp(rate, 0.0f, 1.0f);
		target.vel = rate * target.Vec3To(hold_spot);
		// target.vel = rate * levellocals.vec3diff(target.pos, hold_spot.pos);
	}
	
	private void ClearTargetHeld () {
		target.TakeInventory("Gc_IsGrasped", 1);
	}
	
	private void TossTarget (float max_vel, float forw_vel) {
		float r_cosvang = forw_vel * cos(user.pitch);
		vector3 forw = (
			r_cosvang * cos(user.angle)
		,	r_cosvang * sin(user.angle)
		,  -forw_vel * sin(user.pitch) );
		
		target.vel += user.vel + forw;
		target.vel  = target.vel.Unit() * min(max_vel, target.vel.Length());
	}
}



// Previously, on DragonCouch Z!~

class ChillgraspTrigger : Inventory { Default { Inventory.MaxAmount 1; } }

class ChillgraspDamage : Actor
{
	Default
	{
		Obituary "%k sent sergeant shivers down %o's spine."; //Lol.
		Damage (5);
		DamageType "Ice";
		RenderStyle 'Add';
		Projectile;
		Alpha 0.8;
		Scale 0.1;
		+FORCERADIUSDMG
		+BLOODLESSIMPACT
		+CAUSEPAIN
		+FORCEPAIN
	}
	
	int ExpandDong;
	int Buttsauce;
	int Wowlewd;
	int Noshit;
	
	States
	{
	Spawn:
		TNT1 A 0 {
			if(GetCvar("GC_ToasterMode")) { Noshit = 96; }
			else { Noshit = 0; }
		}
	Death:
		TNT1 A 0
		{
			if(CountInv("PowerDeadmaker",AAPTR_TARGET)) {
				bICESHATTER = 1;
				A_RadiusThrust(-3000, 256, RTF_NOIMPACTDAMAGE, 64);
				A_RadiusThrust(-300,  256, RTF_THRUSTZ|RTF_NOIMPACTDAMAGE, 64); //Vertical thrust is a bit of a stronk. [/Yhollspeak]
				For(Wowlewd = 0; Wowlewd < 8; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspWaveLarge",frandom(-20.0,20.0),
						frandom(-20.0,20.0),frandom(-20.0,20.0),frandom(8.0,6.0),
						frandom(0.8,-0.8),frandom(1.8,-1.8),frandom(0.0,360.0),
						SXF_CLIENTSIDE,40 + Noshit);
				}
				For(Wowlewd = 0; Wowlewd < 6; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspSnow",frandom(-135.0,135.0),
						frandom(-135.0,135.0),frandom(-65.0,65.0),0,0,0,
						frandom(0.0,360.0),SXF_CLIENTSIDE,40 + Noshit);
				}
				For(Wowlewd = 0; Wowlewd < 3; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspMist",frandom(-20.0,20.0),
					frandom(-20.0,20.0),frandom(-20.0,20.0),0,0,0,
					frandom(0.0,360.0),SXF_CLIENTSIDE,0 + Noshit);
				}
				A_SpawnItemEx("ChillgraspAurora1", 0, 0, 0, 0, 0, 0, 0, SXF_CLIENTSIDE);
			}
			else {
				For(Wowlewd = 0; Wowlewd < 4; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspWave",frandom(-5.0,5.0),
						frandom(-5.0,5.0),frandom(-5.0,5.0),frandom(6.0,5.0),
						frandom(0.8,-0.8),frandom(1.8,-1.8),frandom(0.0,360.0),
						SXF_CLIENTSIDE,40 + Noshit);
				}
				For(Wowlewd = 0; Wowlewd < 3; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspSnow",frandom(-25.0,25.0),
						frandom(-25.0,25.0),frandom(-5.0,25.0),0,0,0,
						frandom(0.0,360.0),SXF_CLIENTSIDE,40 + Noshit);
				}
				For(Wowlewd = 0; Wowlewd < 2; Wowlewd++)
				{
					A_SpawnItemEx("ChillgraspMist",frandom(-5.0,5.0),
					frandom(-5.0,5.0),frandom(-5.0,5.0),0,0,0,
					frandom(0.0,360.0),SXF_CLIENTSIDE,0 + Noshit);
				}
				A_SpawnItemEx("ChillyPulse", 0, 0, 0, 0, 0, 0, 0, SXF_CLIENTSIDE);
			}
		}
	Looplet:
		ICIC L 1 Bright {
			ExpandDong = ExpandDong + 10 + CountInv("PowerDeadmaker",AAPTR_TARGET) * 64;
			Buttsauce = Buttsauce + 1;
			A_Explode(16 - Buttsauce, 64 + ExpandDong,0,0);
			If(CountInv("PowerDeadmaker",AAPTR_TARGET) && CountInv("DergfistSupremeSelected",AAPTR_TARGET))
			{
				A_RadiusGive("ChillgraspTrigger", 128 + ExpandDong, RGF_MONSTERS|RGF_CORPSES, 1);
			}
			Else If(CountInv("PowerTomeEffect",AAPTR_TARGET))
			{
				A_RadiusGive("ChillgraspTrigger", 64 + ExpandDong, RGF_MONSTERS|RGF_CORPSES, 1);
			}
			Else
			{
				A_RadiusGive("ChillgraspTrigger", 16, RGF_MONSTERS|RGF_CORPSES, 1);
			}
			A_FadeOut(0.12);
			A_SetScale(scale.x + 0.1);
		}
		Loop;
	}
}

class ChillgraspBlast : Actor
{
	Default
	{
		DamageType "Ice";
		Obituary "%o was served with an explosive ice statue.";
		Projectile;
		+NOINTERACTION
		+BLOODLESSIMPACT
		+FORCERADIUSDMG
		+NOTONAUTOMAP
	}
	
	int ExpandDong;
	int Buttsauce;
	int Counter;
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay {
			Counter = 10;
			A_PlaySound("Chillgrasp/Blast",4,0.8);
			A_SpawnItemEx("ChillgraspSpawnerMist", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspSpawnerShockwave", 0, 0, 15, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspAurora1", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspAurora2", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspAurora3", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspSpawnerSnow", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspCloud", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
			A_SpawnItemEx("ChillgraspPulse", 0, 0, 20, 0, 0, 0, 0, SXF_CLIENTSIDE, 0);
		}
    //TNT1 A 0 A_Blast(BF_DONTWARN|BF_AFFECTBOSSES, 255, 192, 55, "BlastEffect", None)
	Looplet:
		TNT1 A 1 {
			Counter--;
			ExpandDong = ExpandDong + 16;
			Buttsauce = Buttsauce + 4;
			A_Explode(60 - Buttsauce, 96 + ExpandDong, 0,0);
			if(CountInv("PowerTomeEffect",AAPTR_TARGET))
			{
				A_RadiusGive("ChillgraspTrigger", 96 + ExpandDong, RGF_MONSTERS|RGF_CORPSES, 1);
			}
			Return A_JumpIf(Counter <= 0, "Null");
		}
		Loop;
	}
}

//EFFECTS

class ChillgraspBase : Actor
{
	Default
	{
		Renderstyle 'Add';
		Alpha 0.99;
		+NOINTERACTION
		+NOTONAUTOMAP
		+FORCEXYBILLBOARD
	}
	
	int tm; //toaster mode counter.
}

class ChillgraspSnow : Actor
{
	Default
	{
		Radius 2;
		Height 2;
		Renderstyle 'Add';
		Scale 0.01;
		Gravity 0.035;
		Projectile;
		+BOUNCEONWALLS
		+BOUNCEONCEILINGS
		+BOUNCEONACTORS
		+ALLOWBOUNCEONACTORS
		+NOTONAUTOMAP
		+FORCEXYBILLBOARD
		-NOGRAVITY
	}
	
	int t;
	
	States
	{
	Spawn:
		SNWP A 0 NoDelay { t = random(175,210); }
	Looplet:
		SNWP A 1 {
			A_ChangeVelocity(frandom(-0.2, 0.2), frandom(-0.2, 0.2), frandom(-0.035,-0.015), CVF_RELATIVE);
			t--;
			return A_JumpIf(t <= 0, "Death");
		}
		Loop;
	Death:
		SNWP A random(35,70);
		SNWP A 1 A_FadeOut(0.01);
		Wait;
	}
}

class ChillgraspCloud : ChillgraspBase
{
	Default
	{
		Scale 0.75;
	}
	
	States
	{
	Spawn:
		CLDH A 1 NoDelay A_FadeOut(0.02);
		Loop;
	}
}

class ChillgraspMist : ChillgraspBase
{
	Default
	{
		Alpha 0.45;
		Scale 0.65;
	}
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay A_Jump(256,"Spawn1","Spawn2","Spawn3","Spawn4");
	Spawn1:
		NSMK A 1 A_Jump(256,"Main");
	Spawn2:
		NSMK B 1 A_Jump(256,"Main");
	Spawn3:
		NSMK C 1 A_Jump(256,"Main");
  Spawn4:
		NSMK D 1 A_Jump(256,"Main");
	Main:
		"####" "#" 1 {
			A_ChangeVelocity (frandom(-0.05, 0.05), frandom(-0.05, 0.05), frandom(-0.05, 0.05), CVF_RELATIVE);
			A_SetScale(scale.x + 0.01 + frandom(0.02, -0.01));
			A_FadeOut(0.003);
		}
		Loop;
	}
}

class ChillgraspWave : ChillgraspBase
{
	Default
	{
		Alpha 0.45;
		Scale 1.0;
		DamageType 'Ice';
		+FORCERADIUSDMG
		+BLOODLESSIMPACT
	}
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay A_Jump(256,"Spawn1","Spawn2","Spawn3","Spawn4");
	Spawn1:
		NSMK A 1 A_Jump(256,"Main");
	Spawn2:
		NSMK B 1 A_Jump(256,"Main");
	Spawn3:
		NSMK C 1 A_Jump(256,"Main");
	Spawn4:
		NSMK D 1 A_Jump(256,"Main");
	Main:
		"####" "#" 1 {
			A_ChangeVelocity(frandom(-0.1, 0.1), frandom(-0.1, 0.1), frandom(-0.1, 0.1), CVF_RELATIVE);
			A_SetScale(scale.x + 0.01 + frandom(0.02, -0.01));
			//A_Explode(1,128);
			A_FadeOut(0.01);
		}
		Loop;
	}
}

class ChillgraspWaveLarge : ChillgraspWave
{
	Default
	{
		Scale 2.0;
	}
}

class ChillgraspAurora1 : ChillgraspBase
{
	Default
	{
		Scale 0.5;
	}
	
	States
	{
	Spawn:
		ICIC L 1 Bright NoDelay {
			A_SetScale(scale.x + 0.05);
			A_FadeOut(0.08);
		}
		Loop;
	}
}

class ChillgraspAurora2 : ChillgraspBase
{
	Default
	{
		Scale 0.75;
		Alpha 0.9;
	}
	
	States
	{
	Spawn:
		ICIC L 1 Bright NoDelay {
			A_SetScale(scale.x + 0.06);
			A_FadeOut(0.08);
		}
		Loop;
	}
}

class ChillgraspAurora3 : ChillgraspBase
{
	Default
	{
		Scale 0.9;
		Alpha 0.7;
	}
	
	States
	{
	Spawn:
		ICIC L 1 Bright NoDelay {
			A_SetScale(scale.x + 0.07);
			A_FadeOut(0.08);
		}
		Loop;
	}
}

//HIT SPAWNERS

class ChillgraspSpawnerMist : ChillgraspBase
{
	Default
	{
		ReactionTime 6;
	}
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay {
			if(GetCvar("GC_ToasterMode")) { tm = 164; }
			else { tm = 0; }
		}
	Looplet:
		TNT1 A 0 {
			A_Countdown();
			A_SpawnItemEx("ChillgraspMist",
				frandom(-65.0,65.0),random(-65.0,65.0),random(-35.0,35.0),
				0,0,0,0,SXF_CLIENTSIDE,tm);
		}
		Loop;
	Death:
		TNT1 AAAAA random(1,3) A_SpawnItemEx("ChillgraspMist",
			frandom(-65.0,65.0),random(-65.0,65.0),random(-35.0,35.0),
			0,0,0,0,SXF_CLIENTSIDE,tm);
		Stop;
	}
}

class ChillgraspSpawnerShockwave : ChillgraspBase
{
	Default
	{
		ReactionTime 65;
	}
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay {
			if(GetCvar("GC_ToasterMode")) { tm = 164; }
			else { tm = 0; }
		}
	Looplet:
		TNT1 A 0 {
			A_Countdown();
			A_SpawnItemEx("ChillgraspWave",
				frandom(3.0,-3.0),frandom(3.0,-3.0),frandom(3.0,-3.0),
				frandom(6.0,5.0),frandom(0.8,-0.8),frandom(1.8,-1.8),
				frandom(0.0,360.0),SXF_CLIENTSIDE,tm);
		}
		Loop;
	Death:
		TNT1 A 1;
		Stop;
	}
}

class ChillgraspSpawnerSnow : ChillgraspBase
{
	Default
	{
		ReactionTime 10;
	}
	
	States
	{
	Spawn:
		TNT1 A 0 NoDelay {
			if(GetCvar("GC_ToasterMode")) { tm = 164; }
			else { tm = 0; }
		}
	Looplet:
		TNT1 A 0 {
			A_Countdown();
			A_SpawnItemEx("ChillgraspSnow",
			frandom(-75.0,95.0),frandom(-75.0,75.0),frandom(-30.0,30.0),
			0,0,0,0,SXF_CLIENTSIDE,tm);
		}
		Loop;
	Death:
		TNT1 AAAAAAA random(1,3) A_SpawnItemEx("ChillgraspSnow",
			frandom(-75.0,75.0),frandom(-75.0,75.0),frandom(-30.0,30.0),
			0,0,0,0,SXF_CLIENTSIDE,tm);
		Stop;
	}
}

//LIGHT ACTORS

class ChillyPulse : ChillgraspBase
{
	//+NOTIMEFREEZE
	States
	{
	Spawn:
		TNT1 A 20;
		Stop;
	}
}


class ChillgraspPulse : ChillgraspBase
{
	//+NOTIMEFREEZE
	States
	{
	Spawn:
		TNT1 A 25;
		Stop;
	}
}
