#include "g_local.h"


//void ProjectileBounce (vec3_t in, vec3_t normal, vec3_t out);
void bfg_lightning(vec3_t start, vec3_t stop, int twist);
void T_BecomeExplosion(edict_t *ent, int mod);
void DoBounce(edict_t *self);
void MakeBounce(edict_t *self, vec3_t start, vec3_t in, vec3_t normal, int shottype, int dmg);

int bounces = 0;

/*
=================
check_dodge

This is a support routine used when a client is firing
a non-instant attack weapon.  It checks to see if a
monster's dodge function should be called.
=================
*/
static void check_dodge (edict_t *self, vec3_t start, vec3_t dir, int speed)
{
	vec3_t	end;
	vec3_t	v;
	trace_t	tr;
	float	eta;

	// easy mode only ducks one quarter the time
	if (skill->value == 0)
	{
		if (random() > 0.25)
			return;
	}
	VectorMA (start, 8192, dir, end);
	tr = gi.trace (start, NULL, NULL, end, self, MASK_SHOT);
	if ((tr.ent) && (tr.ent->svflags & SVF_MONSTER) && (tr.ent->health > 0) && (tr.ent->monsterinfo.dodge) && infront(tr.ent, self))
	{
		VectorSubtract (tr.endpos, start, v);
		eta = (VectorLength(v) - tr.ent->maxs[0]) / speed;
		tr.ent->monsterinfo.dodge (tr.ent, self, eta);
	}
}


/*
=================
fire_hit

Used for all impact (hit/punch/slash) attacks
=================
*/
qboolean fire_hit (edict_t *self, vec3_t aim, float range, int damage, int kick, int dflags)
{
	trace_t		tr;
	vec3_t		forward, right, up;
	vec3_t		v;
	vec3_t		point;
	vec3_t		dir;

	if(self->enemy != NULL)
	{
		//see if enemy is in range
		VectorSubtract (self->enemy->s.origin, self->s.origin, dir);
		if (range > aim[0])
			return false;
	
		if (aim[1] > self->mins[0] && aim[1] < self->maxs[0])
		{
			// the hit is straight on so back the range up to the edge of their bbox
			range -= self->enemy->maxs[0];
		}
		else
		{
			// this is a side hit so adjust the "right" value out to the edge of their bbox
			if (aim[1] < 0)
				aim[1] = self->enemy->mins[0];
			else
				aim[1] = self->enemy->maxs[0];
		}
		VectorMA (self->s.origin, range, dir, point);
	}
	else
	{
		VectorMA (self->s.origin, range, aim, point);
	}
	

	tr = gi.trace (self->s.origin, self->mins, self->maxs, point, self, MASK_SHOT);
	if (tr.fraction < 1)
	{
		if (!tr.ent->takedamage)
			return false;
		// if it will hit any client/monster then hit the one we wanted to hit
		//if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client))
		//	tr.ent = self->enemy;
	}
	else
		return false;

	AngleVectors(self->s.angles, forward, right, up);
	VectorMA (self->s.origin, range, forward, point);
	VectorMA (point, aim[1], right, point);
	VectorMA (point, aim[2], up, point);
	VectorSubtract (point, tr.ent->s.origin, dir);

	// do the damage
	T_Damage (tr.ent, self, self, dir, point, vec3_origin, damage, kick/2, dflags | DAMAGE_NO_KNOCKBACK, MOD_HIT);

	if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client))
		return false;

	// do our special form of knockback here
	VectorMA (tr.ent->absmin, 0.5, tr.ent->size, v);
	VectorSubtract (v, point, v);
	VectorNormalize (v);
	VectorMA (tr.ent->velocity, kick, v, tr.ent->velocity);
	if (tr.ent->velocity[2] > 0)
		tr.ent->groundentity = NULL;
	return true;
}



/*
=================
fire_lead

This is an internal support routine used for bullet/pellet based weapons.
=================
*/
void fire_lead (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int te_impact, int hspread, int vspread, int mod)
{
	trace_t		tr;
	vec3_t		dir;
	vec3_t		forward, right, up;
	vec3_t		end;
	float		r;
	float		u;
	vec3_t		water_start;
	qboolean	water = false;
	int			content_mask = MASK_SHOT | MASK_WATER;
	edict_t		*ignore = self;

	tr = gi.trace (self->s.origin, NULL, NULL, start, ignore, MASK_SHOT);
	if (!(tr.fraction < 1.0))
	{
		vectoangles (aimdir, dir);
		AngleVectors (dir, forward, right, up);

		r = crandom()*hspread;
		u = crandom()*vspread;
		VectorMA (start, 8192, forward, end);
		VectorMA (end, r, right, end);
		VectorMA (end, u, up, end);

		if (gi.pointcontents (start) & MASK_WATER)
		{
			water = true;
			VectorCopy (start, water_start);
			content_mask &= ~MASK_WATER;
		}

		tr = gi.trace (start, NULL, NULL, end, ignore, content_mask);

		// see if we hit water
		if (tr.contents & MASK_WATER)
		{
			int		color;

			water = true;
			VectorCopy (tr.endpos, water_start);

			if (!VectorCompare (start, tr.endpos))
			{
				if (tr.contents & CONTENTS_WATER)
				{
					if (strcmp(tr.surface->name, "*brwater") == 0)
						color = SPLASH_BROWN_WATER;
					else
						color = SPLASH_BLUE_WATER;
				}
				else if (tr.contents & CONTENTS_SLIME)
					color = SPLASH_SLIME;
				else if (tr.contents & CONTENTS_LAVA)
					color = SPLASH_LAVA;
				else
					color = SPLASH_UNKNOWN;

				if (color != SPLASH_UNKNOWN)
				{
					gi.WriteByte (svc_temp_entity);
					gi.WriteByte (TE_SPLASH);
					gi.WriteByte (8);
					gi.WritePosition (tr.endpos);
					gi.WriteDir (tr.plane.normal);
					gi.WriteByte (color);
					gi.multicast (tr.endpos, MULTICAST_PVS);
				}

				// change bullet's course when it enters water
				VectorSubtract (end, start, dir);
				vectoangles (dir, dir);
				AngleVectors (dir, forward, right, up);
				r = crandom()*hspread*2;
				u = crandom()*vspread*2;
				VectorMA (water_start, 8192, forward, end);
				VectorMA (end, r, right, end);
				VectorMA (end, u, up, end);
			}

			// re-trace ignoring water this time
			tr = gi.trace (water_start, NULL, NULL, end, ignore, MASK_SHOT);
		}
	}

	// send gun puff / flash
	if(tr.surface && (tr.surface->flags & SURF_SKY))
	{
		if(mod == MOD_LIGHTNING)
			bfg_lightning(start, tr.endpos, 60);
			
	}
	else
	{
		if (tr.fraction < 1.0)
		{
			if(mod == MOD_LIGHTNING)
				bfg_lightning(start, tr.endpos, 30);
				
			if (tr.ent->takedamage)
			{				
				if(mod == MOD_LIGHTNING)
					T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, DAMAGE_ENERGY | DAMAGE_NO_BLEED, mod);
				else
					T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, DAMAGE_BULLET, mod);
			}
			else
			{
				if (strncmp (tr.surface->name, "sky", 3) != 0)
				{
					vec3_t x, n;
					x[0] = tr.endpos[0];
					x[1] = tr.endpos[1];
					x[2] = tr.endpos[2];
					
					n[0] = tr.plane.normal[0];
					n[1] = tr.plane.normal[1];
					n[2] = tr.plane.normal[2];
					if(mod == MOD_GRENADE || mod == MOD_HG_SPLASH || mod == MOD_G_SPLASH)
					{
						vec3_t diff;
						float distance;
						
						
						diff[0] = x[0] - start[0];
						diff[1] = x[1] - start[1];
						diff[2] = x[2] - start[2];
						distance = sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);			
						damage = ((float) damage) * 1 / (1 + distance * distance / 5000);
						if(distance < 1) damage -= 1;
					}
					//else
					//{
						gi.WriteByte (svc_temp_entity);
						gi.WriteByte (te_impact);
						gi.WritePosition (x);
						gi.WriteDir (n);
						gi.multicast (x, MULTICAST_PVS);
					//}
					if(damage > 0)
						MakeBounce(self, x, aimdir, n, mod, damage);

					if (self->client)
						PlayerNoise(self, x, PNOISE_IMPACT);
				}
			}
		}
	}

	// if went through water, determine where the end and make a bubble trail
	if (water)
	{
		vec3_t	pos;

		VectorSubtract (tr.endpos, water_start, dir);
		VectorNormalize (dir);
		VectorMA (tr.endpos, -2, dir, pos);
		if (gi.pointcontents (pos) & MASK_WATER)
			VectorCopy (pos, tr.endpos);
		else
			tr = gi.trace (pos, NULL, NULL, water_start, tr.ent, MASK_WATER);

		VectorAdd (water_start, tr.endpos, pos);
		VectorScale (pos, 0.5, pos);

		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_BUBBLETRAIL);
		gi.WritePosition (water_start);
		gi.WritePosition (tr.endpos);
		gi.multicast (pos, MULTICAST_PVS);
	}
	/*
	if(tr.surface->flags & SURF_SKY)
	{
	}
	else
	{
		if(mod == MOD_GRENADE)
		{
			vec3_t diff;
			float distance;
			diff[0] = tr.endpos[0] - start[0];
			diff[1] = tr.endpos[1] - start[1];
			diff[2] = tr.endpos[2] - start[2];
			distance = sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);			
			damage = ((float) damage) * 1 / (1 + distance / 15);
			if(distance < 1) damage -= 1;
			if(damage > 5)
				T_RadiusDamage(self, self, damage / 5, NULL, damage, mod);
		}
		if(damage > 0)
			MakeBounce(self, tr.endpos, aimdir, tr.plane.normal, mod, damage);	
	}
	*/
}


/*
=================
fire_bullet

Fires a single round.  Used for machinegun and chaingun.  Would be fine for
pistols, rifles, etc....
=================
*/
void fire_bullet (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int mod)
{
	fire_lead (self, start, aimdir, damage, kick, TE_GUNSHOT, hspread, vspread, mod);
}


/*
=================
fire_shotgun

Shoots shotgun pellets.  Used by shotgun and super shotgun.
=================
*/
void fire_shotgun (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int count, int mod)
{
	int		i;

	for (i = 0; i < count; i++)		
		fire_lead (self, start,          aimdir,         damage,    kick, TE_SHOTGUN, hspread, vspread, mod);
}


void bfg_lightning(vec3_t start, vec3_t stop, int twist)
{
	vec3_t s1, s2, c, d;
	if(random() > 0.5)
	{
		s1[0] = start[0];
		s1[1] = start[1];
		s1[2] = start[2];

		s2[0] = stop[0];
		s2[1] = stop[1];
		s2[2] = stop[2];
	}
	else
	{
		s2[0] = start[0];
		s2[1] = start[1];
		s2[2] = start[2];

		s1[0] = stop[0];
		s1[1] = stop[1];
		s1[2] = stop[2];
	}
	d[0] = s2[0] - s1[0];
	d[1] = s2[1] - s1[1];
	d[2] = s2[2] - s1[2];
	while(VectorLength(d) > 180)
	{
		VectorNormalize(d);
		c[0] = s1[0] + crandom() * twist;
		c[1] = s1[1] + crandom() * twist;
		c[2] = s1[2] + crandom() * twist;
		VectorMA(c, 120, d, c);
		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_BFG_LASER);
		gi.WritePosition (s1);
		gi.WritePosition (c);
		gi.multicast (start, MULTICAST_PHS);

		s1[0] = c[0];
		s1[1] = c[1];
		s1[2] = c[2];

		d[0] = s2[0] - s1[0];
		d[1] = s2[1] - s1[1];
		d[2] = s2[2] - s1[2];
	}
	gi.WriteByte (svc_temp_entity);
	gi.WriteByte (TE_BFG_LASER);
	gi.WritePosition (s1);
	gi.WritePosition (s2);
	gi.multicast (start, MULTICAST_PHS);
}

/*
=================
fire_blaster

Fires a single blaster bolt.  Used by the blaster and hyper blaster.
=================
*/

void blaster_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
	int		mod;
	int		effects = DAMAGE_ENERGY | DAMAGE_NO_BLEED;
	if (other == self->owner)
		return;

	if(self->spawnflags == -1)
	{
		mod = MOD_MAGICK;
		effects |= DAMAGE_NO_PROTECTION;
	}
	else if (self->spawnflags & 1)
		mod = MOD_HYPERBLASTER;
	else
		mod = MOD_BLASTER;
	
		
	//self->movetype = MOVETYPE_NONE;
	self->think = G_FreeEdict;
	self->nextthink = level.time + FRAMETIME;

	if (surf && (surf->flags & SURF_SKY))
	{
	//	G_FreeEdict (self);
		return;
	}

	if (self->owner->client)
	{
		PlayerNoise(self->owner, self->s.origin, PNOISE_IMPACT);		
	}

	if (other->takedamage)
	{
		T_Damage (other, self, self->owner, self->velocity, self->s.origin, plane->normal, self->dmg, 1, effects, mod);
	}
	else
	{
		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_BLASTER);
		gi.WritePosition (self->s.origin);
		if (!plane)
			gi.WriteDir (vec3_origin);
		else
			gi.WriteDir (plane->normal);
		gi.multicast (self->s.origin, MULTICAST_PVS);
		if(plane && self->dmg > 1)
			MakeBounce(self->owner, self->s.origin, self->velocity, plane->normal, mod, self->dmg - 1);
			
		
	}
	
}

void fire_blaster (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int effect, int hyper)
{
	edict_t	*bolt;
	trace_t	tr;

	VectorNormalize (dir);

	bolt = G_Spawn();
	bolt->classname = "bolt";
	VectorCopy (start, bolt->s.origin);
	VectorCopy (start, bolt->s.old_origin);
	vectoangles (dir, bolt->s.angles);
	VectorMA(self->velocity, speed, dir, bolt->velocity);
	bolt->movetype = MOVETYPE_FLYMISSILE;
	bolt->clipmask = MASK_SHOT;
	bolt->solid = SOLID_BBOX;
	VectorClear (bolt->mins);
	VectorClear (bolt->maxs);
	
	bolt->s.modelindex = gi.modelindex ("models/objects/laser/tris.md2");
	bolt->s.effects |= effect;
	
	//bolt->s.renderfx |= RF_BEAM;
	//bolt->s.skinnum = 0xe0e1e2e3;
	//bolt->s.frame = 2;

	bolt->s.sound = gi.soundindex ("misc/lasfly.wav");
	bolt->owner = self;
	bolt->touch = blaster_touch;
	bolt->dmg = damage;
	
	bolt->spawnflags = hyper;
	gi.linkentity (bolt);

	if (self->client)
		check_dodge (self, bolt->s.origin, dir, speed);

	tr = gi.trace (self->s.origin, NULL, NULL, bolt->s.origin, bolt, MASK_SHOT);
	if (tr.fraction < 1.0)
	{
		VectorMA (bolt->s.origin, -10, dir, bolt->s.origin);
		bolt->touch (bolt, tr.ent, NULL, NULL);
	}
}	


/*
=================
fire_grenade
=================
*/
void Grenade_Explode (edict_t *ent)
{
	vec3_t		origin;
	int			mod, i;

	
	if (ent->owner && ent->owner->client)
		PlayerNoise(ent->owner, ent->s.origin, PNOISE_IMPACT);
	if (ent->spawnflags & 2)
		mod = MOD_HELD_GRENADE;
	else if (ent->spawnflags & 1)
		mod = MOD_HG_SPLASH;
	else
		mod = MOD_G_SPLASH;
	T_RadiusDamage(ent, ent->owner, ent->dmg, ent->enemy, ent->dmg_radius, mod);
	
	for(i = 0; i < ent->dmg_radius; i++)
	{
		vec3_t sdir;
		int dmg;
		dmg = rand() % 5 + 1;
		sdir[0] = crandom();
		sdir[1] = crandom();
		sdir[2] = crandom();
		VectorNormalize(sdir);
		fire_lead (ent->owner, ent->s.origin, sdir, dmg * 10 + 1, 0, TE_SPARKS, 0, 0, mod);
		i += dmg;	
	}
	VectorMA (ent->s.origin, -0.02, ent->velocity, origin);
	gi.WriteByte (svc_temp_entity);
	if (ent->waterlevel)
	{
		if (ent->groundentity)
			gi.WriteByte (TE_GRENADE_EXPLOSION_WATER);
		else
			gi.WriteByte (TE_ROCKET_EXPLOSION_WATER);
	}
	else
	{
		if (ent->groundentity)
			gi.WriteByte (TE_GRENADE_EXPLOSION);
		else
			gi.WriteByte (TE_ROCKET_EXPLOSION);
	}
	gi.WritePosition (origin);
	gi.multicast (ent->s.origin, MULTICAST_PHS);

	//G_FreeEdict (ent);
	T_BecomeExplosion(ent, mod);
}
void Grenade_Die (edict_t *ent, int mod)
{
	Grenade_Explode(ent);
}

static void Grenade_Touch (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
{
	if (other == ent->owner || VectorLength(ent->velocity) < 5)
		return;

	if (surf && (surf->flags & SURF_SKY))
	{
		G_FreeEdict (ent);
		return;
	}

	if (other->takedamage)
	{
		T_Damage(other, ent, ent->owner, ent->velocity, ent->s.origin, plane->normal, 1, 0, DAMAGE_NO_BLEED, MOD_G_HIT);
		//gi.dprintf("Whack!");
	}
	else
	{
		if (ent->spawnflags & 1)
		{
			if (random() > 0.5)
				gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb1a.wav"), 1, ATTN_NORM, 0);
			else
				gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb2a.wav"), 1, ATTN_NORM, 0);
		}
		else
		{
			gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/grenlb1b.wav"), 1, ATTN_NORM, 0);
		}
		return;
	}
	return;
	ent->enemy = other;
	Grenade_Explode (ent);
}

void fire_grenade (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, float timer, float damage_radius)
{
	edict_t	*grenade;
	vec3_t	dir;
	vec3_t	forward, right, up;
	float		accuracy = 1.0 - self->speed / (self->speed + 100.0);
	if(self->client->ps.pmove.pm_flags & PMF_DUCKED)
		accuracy += 1.0;
	

	vectoangles (aimdir, dir);
	AngleVectors (dir, forward, right, up);

	grenade = G_Spawn();
	grenade->classname = "grenade";
	VectorCopy (start, grenade->s.origin);
	VectorScale (aimdir, speed, grenade->velocity);
	VectorMA (grenade->velocity, crandom() * 10.0 / accuracy, up, grenade->velocity);
	VectorMA (grenade->velocity, crandom() * 10.0 / accuracy, right, grenade->velocity);
	VectorSet (grenade->avelocity, 300, 300, 300);
	grenade->movetype = MOVETYPE_BOUNCE;
	grenade->clipmask = MASK_SHOT;
	grenade->solid = SOLID_BBOX;
	grenade->die = Grenade_Die;
	grenade->health = 5;
	grenade->s.effects |= EF_GRENADE;
	//VectorClear (grenade->mins);
	//VectorClear (grenade->maxs);
	grenade->mins[0] = -4;
	grenade->mins[0] = -4;
	grenade->mins[0] = -4;
	grenade->maxs[0] = 4;
	grenade->maxs[0] = 4;
	grenade->maxs[0] = 4;
	grenade->s.modelindex = gi.modelindex ("models/objects/grenade2/tris.md2");
	grenade->owner = self;
	grenade->touch = Grenade_Touch;
	grenade->nextthink = level.time + timer;
	grenade->think = Grenade_Explode;
	grenade->dmg = damage;
	grenade->dmg_radius = damage_radius;
	

	gi.linkentity (grenade);
}

void fire_grenade2 (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, float timer, float damage_radius, qboolean held)
{
	edict_t	*grenade;
	vec3_t	dir;
	vec3_t	forward, right, up;

	vectoangles (aimdir, dir);
	AngleVectors (dir, forward, right, up);

	grenade = G_Spawn();
	grenade->classname = "hgrenade";
	VectorCopy (start, grenade->s.origin);
	VectorScale (aimdir, speed, grenade->velocity);
	VectorMA (grenade->velocity, 200 + crandom() * 10.0, up, grenade->velocity);
	VectorMA (grenade->velocity, crandom() * 10.0, right, grenade->velocity);
	VectorSet (grenade->avelocity, 300, 300, 300);
	grenade->movetype = MOVETYPE_BOUNCE;
	grenade->clipmask = MASK_SHOT;
	grenade->solid = SOLID_BBOX;
	//grenade->s.effects |= EF_GRENADE;
	//VectorClear (grenade->mins);
	//VectorClear (grenade->maxs);
	grenade->mins[0] = -4;
	grenade->mins[0] = -4;
	grenade->mins[0] = -4;
	grenade->maxs[0] = 4;
	grenade->maxs[0] = 4;
	grenade->maxs[0] = 4;	
	grenade->s.modelindex = gi.modelindex ("models/objects/grenade2/tris.md2");
	grenade->owner = self;
	grenade->touch = Grenade_Touch;
	grenade->nextthink = level.time + timer;
	grenade->think = Grenade_Explode;
	grenade->dmg = damage;
	grenade->dmg_radius = damage_radius;
	
	if (held)
		grenade->spawnflags = 3;
	else
		grenade->spawnflags = 1;
	//grenade->s.sound = gi.soundindex("weapons/hgrenc1b.wav");

	if (timer <= 0.0)
		Grenade_Explode (grenade);
	else
	{
		gi.sound (self, CHAN_WEAPON, gi.soundindex ("weapons/hgrent1a.wav"), 1, ATTN_NORM, 0);
		gi.linkentity (grenade);
	}
}


/*
=================
fire_rocket
=================
*/
void rocket_explode(edict_t *ent, int mod)
{
	T_RadiusDamage(ent, ent->owner, ent->radius_dmg, ent, ent->dmg_radius, MOD_R_SPLASH);

	gi.WriteByte (svc_temp_entity);
	if (ent->waterlevel)
		gi.WriteByte (TE_ROCKET_EXPLOSION_WATER);
	else
		gi.WriteByte (TE_ROCKET_EXPLOSION);
	gi.WritePosition (ent->s.origin);
	gi.multicast (ent->s.origin, MULTICAST_PHS);

	//G_FreeEdict (ent);
	T_BecomeExplosion(ent, MOD_R_SPLASH);
}
void rocket_touch (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
{
	vec3_t		origin;
	int			n;

	if (other == ent->owner || other->owner == ent->owner)
		return;

	if (surf && (surf->flags & SURF_SKY))
	{
		G_FreeEdict (ent);
		return;
	}

	if (ent->owner->client)
		PlayerNoise(ent->owner, ent->s.origin, PNOISE_IMPACT);

	// calculate position for the explosion entity
	VectorMA (ent->s.origin, -0.02, ent->velocity, origin);

	if (other->takedamage)
	{
		T_Damage (other, ent, ent->owner, ent->velocity, ent->s.origin, plane->normal, ent->dmg, 0, 0, MOD_ROCKET);
	}
	else
	{
		// don't throw any debris in net games
		if (!deathmatch->value && !coop->value)
		{
			if ((surf) && !(surf->flags & (SURF_WARP|SURF_TRANS33|SURF_TRANS66|SURF_FLOWING)))
			{
				n = rand() % 5;
				while(n--)
					ThrowDebris (ent, "models/objects/debris2/tris.md2", 2, ent->s.origin);
			}
		}
	}

	T_RadiusDamage(ent, ent->owner, ent->radius_dmg, other, ent->dmg_radius, MOD_R_SPLASH);

	gi.WriteByte (svc_temp_entity);
	if (ent->waterlevel)
		gi.WriteByte (TE_ROCKET_EXPLOSION_WATER);
	else
		gi.WriteByte (TE_ROCKET_EXPLOSION);
	gi.WritePosition (origin);
	gi.multicast (ent->s.origin, MULTICAST_PHS);

	//G_FreeEdict (ent);
	T_BecomeExplosion(ent, MOD_R_SPLASH);
}


void rocket_accelerate (edict_t *self)
{
	VectorScale(self->velocity, 0.85, self->velocity);
	VectorMA(self->velocity, self->speed, self->movedir, self->velocity);
	self->movedir[0] += crandom() * 50.0 / (VectorLength(self->velocity) + 50);
	self->movedir[1] += crandom() * 50.0 / (VectorLength(self->velocity) + 50);
	self->movedir[2] += crandom() * 50.0 / (VectorLength(self->velocity) + 50);
	VectorNormalize(self->movedir);
	vectoangles (self->movedir, self->s.angles);
	self->nextthink = level.time + FRAMETIME;
	return;
}

void fire_rocket_small (edict_t *self, vec3_t start, vec3_t dir1, vec3_t dir2, int damage, int speed, float damage_radius, int radius_damage)
{
	edict_t	*rocket;

	rocket = G_Spawn();
	rocket->classname = "rocket";
	VectorCopy (start, rocket->s.origin);
	VectorMA (dir1, -0.05, dir2, rocket->movedir);
	vectoangles (dir1, rocket->s.angles);
	VectorMA (self->velocity, 64, dir2, rocket->velocity);	
	rocket->speed = speed;
	rocket->movetype = MOVETYPE_FLYMISSILE;
	rocket->clipmask = MASK_SHOT;
	rocket->solid = SOLID_BBOX;
	rocket->s.effects |= EF_ROCKET;
	//VectorClear (rocket->mins);
	//VectorClear (rocket->maxs);
	rocket->mins[0] = -1;
	rocket->mins[1] = -1;
	rocket->mins[2] = -1;
	rocket->maxs[0] = 1;
	rocket->maxs[1] = 1;
	rocket->maxs[2] = 1;
	rocket->s.modelindex = gi.modelindex ("models/objects/rocket/tris.md2");
	rocket->owner = self;
	rocket->touch = rocket_touch;
	rocket->nextthink = level.time + 0.5;
	rocket->think = rocket_accelerate;
	rocket->dmg = damage;
	rocket->radius_dmg = radius_damage;
	rocket->dmg_radius = damage_radius;
	rocket->s.sound = gi.soundindex ("weapons/rockfly.wav");
	rocket->health = 50;
	rocket->die = rocket_explode;
	

	if (self->client)
		check_dodge (self, rocket->s.origin, dir1, speed);

	gi.linkentity (rocket);
}

void fire_rocket (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, float damage_radius, int radius_damage)
{
	edict_t	*rocket;

	rocket = G_Spawn();
	rocket->classname = "rocket";
	VectorCopy (start, rocket->s.origin);
	VectorCopy (dir, rocket->movedir);
	vectoangles (dir, rocket->s.angles);
	VectorCopy (self->velocity, rocket->velocity);
	rocket->speed = speed;
	rocket->movetype = MOVETYPE_FLYMISSILE;
	rocket->clipmask = MASK_SHOT;
	rocket->solid = SOLID_BBOX;
	rocket->s.effects |= EF_ROCKET;
	//VectorClear (rocket->mins);
	//VectorClear (rocket->maxs);
	rocket->mins[0] = -1;
	rocket->mins[1] = -1;
	rocket->mins[2] = -1;
	rocket->maxs[0] = 1;
	rocket->maxs[1] = 1;
	rocket->maxs[2] = 1;
	rocket->s.modelindex = gi.modelindex ("models/objects/rocket/tris.md2");
	rocket->owner = self;
	rocket->touch = rocket_touch;
	rocket->nextthink = level.time + FRAMETIME;
	rocket->think = rocket_accelerate;
	rocket->dmg = damage;
	rocket->radius_dmg = radius_damage;
	rocket->dmg_radius = damage_radius;
	rocket->s.sound = gi.soundindex ("weapons/rockfly.wav");
	rocket->health = 50;
	rocket->die = rocket_explode;
	

	if (self->client)
		check_dodge (self, rocket->s.origin, dir, speed);

	gi.linkentity (rocket);
}


/*
=================
fire_rail
=================
*/
void fire_rail (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick)
{
	vec3_t		from;
	vec3_t		end;
	trace_t		tr;
	edict_t		*ignore;
	int			mask;
	qboolean	water;

	VectorMA (start, 8192, aimdir, end);
	VectorCopy (start, from);	
	ignore = self;
	water = false;
	mask = MASK_SHOT|CONTENTS_SLIME|CONTENTS_LAVA;
	while (damage > 0)
	{
		tr = gi.trace (from, NULL, NULL, end, ignore, mask);

		if (tr.contents & (CONTENTS_SLIME|CONTENTS_LAVA))
		{
			mask &= ~(CONTENTS_SLIME|CONTENTS_LAVA);
			water = true;
		}
		else
		{
			if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client))
			{
				ignore = tr.ent;
				VectorCopy (tr.endpos, from);
				damage--;
			}
			else if(tr.surface->flags & SURF_SKY)
			{
				ignore = NULL;
				damage = 0;
			}
			else
			{
				vec3_t skip;
				ignore = NULL;
								
				for(VectorCopy(tr.endpos, skip); damage > 0; damage--)
				{
					VectorMA (skip, 1, aimdir, skip);
					if(!(gi.pointcontents (skip) & MASK_SOLID))
						break;
				}

				if(damage > 0)
					VectorCopy(skip, from);
				else
					VectorCopy(tr.endpos, from);
			}

			if ((tr.ent != self) && (tr.ent->takedamage))
				T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, DAMAGE_ARMOR_PIERCING, MOD_RAILGUN);
		}
		
		
	}

	// send gun puff / flash
	gi.WriteByte (svc_temp_entity);
	gi.WriteByte (TE_RAILTRAIL);
	gi.WritePosition (start);
	gi.WritePosition (tr.endpos);
	gi.multicast (self->s.origin, MULTICAST_PHS);
//	gi.multicast (start, MULTICAST_PHS);
	if (water)
	{
		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_RAILTRAIL);
		gi.WritePosition (start);
		gi.WritePosition (tr.endpos);
		gi.multicast (tr.endpos, MULTICAST_PHS);
	}
	
	if (self->client)
		PlayerNoise(self, tr.endpos, PNOISE_IMPACT);
	
	// bounce routine
	if(tr.surface->flags & SURF_SKY)
	{
	}
	else if(damage > 1)
	{
		MakeBounce(self, tr.endpos, aimdir, tr.plane.normal, MOD_RAILGUN, damage - 1);
	}
}


/*
=================
fire_bfg
=================
*/


void bfg_explode (edict_t *self)
{
	edict_t	*ent;
	float	points;
	vec3_t	v;
	float	dist;
	int i;

	if (self->s.frame == 0)
	{		

		// the BFG effect
		ent = NULL;
		while ((ent = findradius(ent, self->s.origin, self->dmg_radius)) != NULL)
		{
			int arcs;
			if (!ent->takedamage)
				continue;
			if (ent == self->owner)
				continue;
			if (!CanDamage (ent, self))
				continue;
			if (!CanDamage (ent, self->owner))
				continue;

			VectorAdd (ent->mins, ent->maxs, v);
			VectorMA (ent->s.origin, 0.5, v, v);
			VectorSubtract (self->s.origin, v, v);
			dist = VectorLength(v);
			points = self->radius_dmg * (1.0 - sqrt(dist/self->dmg_radius));
			//if (ent == self->owner)
			//	points = points * 0.5;

			gi.WriteByte (svc_temp_entity);
			gi.WriteByte (TE_BFG_EXPLOSION);
			gi.WritePosition (ent->s.origin);
			gi.multicast (ent->s.origin, MULTICAST_PHS);
			T_Damage (ent, self, self->owner, self->velocity, ent->s.origin, vec3_origin, (int)points, 0, DAMAGE_ENERGY | DAMAGE_NO_BLEED, MOD_BFG_EFFECT);
			
			for(arcs = 0; arcs < (300 / (dist + 100) + 1); arcs++)
			{
				bfg_lightning(self->s.origin, ent->s.origin, 60);
				bfg_lightning(self->owner->s.origin, ent->s.origin, 75);
			}
			/*
			gi.WriteByte (svc_temp_entity);
			gi.WriteByte (TE_BFG_LASER);
			gi.WritePosition (self->s.origin);
			gi.WritePosition (ent->s.origin);
			gi.multicast (self->s.origin, MULTICAST_PHS);

			gi.WriteByte (svc_temp_entity);
			gi.WriteByte (TE_BFG_LASER);
			gi.WritePosition (self->owner->s.origin);
			gi.WritePosition (ent->s.origin);
			gi.multicast (self->s.origin, MULTICAST_PHS);
			*/
		}
	}

	self->nextthink = level.time + FRAMETIME;
	self->s.frame++;
	if (self->s.frame == 5)
		self->think = G_FreeEdict;
}

void bfg_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
	if (other == self->owner)
		return;

	if (surf && (surf->flags & SURF_SKY))
	{
		G_FreeEdict (self);
		return;
	}

	if (self->owner->client)
		PlayerNoise(self->owner, self->s.origin, PNOISE_IMPACT);

	// core explosion - prevents firing it into the wall/floor
	if (other->takedamage)
	{
		T_Damage (other, self, self->owner, self->velocity, self->s.origin, plane->normal, 200, 0, 0, MOD_BFG_BLAST);
		if(other->client->pers.inventory[ITEM_INDEX(FindItem("Imaging Goggles"))] == 0)
			other->client->blinded = 1;
		other->client->bonus_alpha = 1;
	}
	/*if(plane)
	{
		MakeBounce(self->owner, self->s.origin, self->velocity, plane->normal, MOD_BFG_BLAST, self->dmg);
		G_FreeEdict (self);
	}	
	else*/
	{
		int i;
		T_RadiusDamage(self, self->owner, 200, other, 100, MOD_BFG_BLAST);
		
		for(i = 0; i < 10; i++)
		{
			vec3_t sdir;
			sdir[0] = crandom();
			sdir[1] = crandom();
			sdir[2] = crandom();
			VectorNormalize(sdir);
			fire_lead (self, self->s.origin, sdir, 5, 5, TE_SPARKS, 1750, 1750, MOD_LIGHTNING);						
		}
	
		gi.sound (self, CHAN_VOICE, gi.soundindex ("weapons/bfg__x1b.wav"), 1, ATTN_NORM, 0);
		self->solid = SOLID_NOT;
		self->touch = NULL;
		VectorMA (self->s.origin, -1 * FRAMETIME, self->velocity, self->s.origin);
		VectorClear (self->velocity);
		self->s.modelindex = gi.modelindex ("sprites/s_bfg3.sp2");
		self->s.frame = 0;
		self->s.sound = 0;
		self->s.effects &= ~EF_ANIM_ALLFAST;
		self->think = bfg_explode;
		self->nextthink = level.time + FRAMETIME;
		self->enemy = other;

		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_BFG_BIGEXPLOSION);
		gi.WritePosition (self->s.origin);
		gi.multicast (self->s.origin, MULTICAST_PVS);
	}
}

void bfg_think (edict_t *self)
{
	edict_t	*ent;
	edict_t	*ignore;
	vec3_t	point;
	vec3_t	dir;
	vec3_t	start;
	vec3_t	end;
	int		dmg;
	trace_t	tr;

	if (deathmatch->value)
		dmg = 5;
	else
		dmg = 10;

	ent = NULL;
	while ((ent = findradius(ent, self->s.origin, 256)) != NULL)
	{
		if (ent == self)
			continue;

		if (ent == self->owner)
			continue;

		if (!ent->takedamage)
			continue;

		if (!(ent->svflags & SVF_MONSTER) && (!ent->client) && (strcmp(ent->classname, "misc_explobox") != 0))
			continue;

		VectorMA (ent->absmin, 0.5, ent->size, point);

		VectorSubtract (point, self->s.origin, dir);
		VectorNormalize (dir);

		ignore = self;
		VectorCopy (self->s.origin, start);
		VectorMA (start, 2048, dir, end);
		while(1)
		{
			tr = gi.trace (start, NULL, NULL, end, ignore, CONTENTS_SOLID|CONTENTS_MONSTER|CONTENTS_DEADMONSTER);

			if (!tr.ent)
				break;

			// hurt it if we can
			if ((tr.ent->takedamage) && !(tr.ent->flags & FL_IMMUNE_LASER) && (tr.ent != self->owner))
				T_Damage (tr.ent, self, self->owner, dir, tr.endpos, vec3_origin, dmg, 1, DAMAGE_ENERGY | DAMAGE_NO_BLEED, MOD_BFG_LASER);

			// if we hit something that's not a monster or player we're done
			if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client))
			{
				gi.WriteByte (svc_temp_entity);
				gi.WriteByte (TE_LASER_SPARKS);
				gi.WriteByte (4);
				gi.WritePosition (tr.endpos);
				gi.WriteDir (tr.plane.normal);
				gi.WriteByte (self->s.skinnum);
				gi.multicast (tr.endpos, MULTICAST_PVS);
				break;
			}

			ignore = tr.ent;
			VectorCopy (tr.endpos, start);
		}
		bfg_lightning(tr.endpos, self->s.origin, 45);
		/*
		gi.WriteByte (svc_temp_entity);
		gi.WriteByte (TE_BFG_LASER);
		gi.WritePosition (self->s.origin);
		gi.WritePosition (tr.endpos);
		gi.multicast (self->s.origin, MULTICAST_PHS);
		*/
	}
	if(!(rand() % 4))
	{		
		vec3_t sdir;
		sdir[0] = crandom();
		sdir[1] = crandom();
		sdir[2] = crandom();
		VectorNormalize(sdir);
		fire_lead (self, self->s.origin, sdir, 5, 5, TE_SPARKS, 1750, 1750, MOD_LIGHTNING);						
	}
	self->nextthink = level.time + FRAMETIME;
}


void fire_bfg (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, float damage_radius)
{
	edict_t	*bfg;

	bfg = G_Spawn();
	bfg->classname = "bfg blast";
	VectorCopy (start, bfg->s.origin);
	VectorCopy (dir, bfg->movedir);
	vectoangles (dir, bfg->s.angles);
	VectorScale (dir, speed, bfg->velocity);
	bfg->movetype = MOVETYPE_FLYMISSILE;
	bfg->clipmask = MASK_SHOT;
	bfg->solid = SOLID_BBOX;
	bfg->s.effects |= EF_BFG | EF_ANIM_ALLFAST;//|= EF_BFG | EF_ANIM_ALLFAST;
	VectorClear (bfg->mins);
	VectorClear (bfg->maxs);
	bfg->s.modelindex = gi.modelindex ("sprites/s_bfg1.sp2");
	bfg->owner = self;
	bfg->touch = bfg_touch;
	bfg->nextthink = level.time + 8000/speed;
	bfg->think = G_FreeEdict;
	bfg->radius_dmg = damage;
	bfg->dmg_radius = damage_radius;
	
	bfg->s.sound = gi.soundindex ("weapons/bfg__l1a.wav");

	bfg->think = bfg_think;
	bfg->nextthink = level.time + FRAMETIME;
	bfg->teammaster = bfg;
	bfg->teamchain = NULL;

	if (self->client)
		check_dodge (self, bfg->s.origin, dir, speed);

	gi.linkentity (bfg);
}

/*
=================
MakeBounce, DoBounce

These routine are used to make ricochets
=================
*/
void DoBounce(edict_t *self)
{
	float speed;
	switch (self->style)
	{
	case MOD_LIGHTNING:			
		if(rand() % 10)
		{
			fire_lead (self, self->s.origin, self->velocity, 1, 0, TE_SPARKS, 5000 / self->dmg, 5000 / self->dmg, self->style);
			//gi.WriteByte (svc_temp_entity);
			//gi.WriteByte (TE_BFG_EXPLOSION);
			//gi.WritePosition (self->s.origin);
			//gi.multicast (self->s.origin, MULTICAST_PHS);
		}
		else
		{
			T_RadiusDamage(self, self->owner, 100, self, 250, MOD_LIGHTNING);
			
			gi.WriteByte (svc_temp_entity);
			gi.WriteByte (TE_BFG_BIGEXPLOSION);
			gi.WritePosition (self->s.origin);
			gi.multicast (self->s.origin, MULTICAST_PHS);
		}
		break;
	case MOD_MACHINEGUN:
	case MOD_CHAINGUN:
		self->dmg -= ((rand() % self->dmg) + (rand() % 10));
		if(self->dmg > 0)
			fire_lead (self, self->s.origin, self->velocity, self->dmg, 0, TE_GUNSHOT, 5000 / self->dmg, 5000 / self->dmg, self->style);
		break;
	case MOD_HANDGRENADE:
	case MOD_G_SPLASH:
	case MOD_HG_SPLASH:
	case MOD_GRENADE:
		//self->dmg-= ((rand() % 3) + 1);
		if(self->dmg > 0)
			fire_lead (self, self->s.origin, self->velocity, self->dmg, 0, TE_SPARKS, 0, 0, self->style);
		break;
	case MOD_BLASTER:
		break;
	case MOD_HYPERBLASTER:
		speed = VectorNormalize(self->velocity);
		self->dmg /= 2;
		if(self->dmg >= 1)
			fire_blaster (self, self->s.origin, self->velocity, self->dmg, speed, EF_BOOMER, 1);
		break;
	case MOD_RAILGUN:	
		//fire_rail(self, self->s.origin, self->velocity, self->dmg, 0);
		break;
	case MOD_BFG_BLAST:		
		speed = VectorNormalize(self->velocity);
		fire_bfg(self, self->s.origin, self->velocity, self->dmg, speed, 200);
		break;
	default:
		;
	}
	G_FreeEdict(self);	
//	gi.dprintf("freeing bounce %d\n", bounces--);
//	gi.dprintf("%d bounces\n", bounces);

	
}

/*
void ProjectileBounce(vec3_t in, vec3_t normal, vec3_t out)
{
	float backoff;
	int i;
	
	//length = VectorNormalize(velocity);
	backoff = DotProduct (in, normal) * 2;
	
	for (i=0 ; i<3 ; i++)
		out[i] = in[i] - normal[i]*backoff;
	
}
*/

void MakeBounce(edict_t *self, vec3_t start, vec3_t in, vec3_t normal, int shottype, int dmg)
{
	float backoff;
	int i;
	edict_t *ricochet;
	vec3_t out;
	
	ricochet = G_Spawn();
	ricochet->classname = "ricochet";	
//	gi.dprintf("making bounce %d\n", bounces++);
//	gi.dprintf("%d bounces\n", bounces);
	
	backoff = DotProduct (in, normal) * 2;
	
	for (i=0 ; i<3 ; i++)			
		out[i] = in[i] - normal[i]*backoff;

	VectorCopy (start, ricochet->s.origin);
	VectorCopy (out, ricochet->velocity);
	ricochet->movetype = MOVETYPE_NONE;
	ricochet->solid = SOLID_NOT;
	VectorClear (ricochet->mins);
	VectorClear (ricochet->maxs);
	ricochet->owner = self;
	ricochet->nextthink = level.time + FRAMETIME;
	ricochet->think = DoBounce;
	ricochet->style = shottype;
	ricochet->dmg = dmg;
	
	ricochet->s.effects = self->s.effects;
	if(shottype == MOD_HANDGRENADE || shottype == MOD_GRENADE || shottype == MOD_HG_SPLASH || shottype == MOD_G_SPLASH)
	{
		T_RadiusDamage (ricochet, self->owner, 5, NULL, 15, shottype);	
	}
}