///////////////////////////////////////////////////////////////////////////////
//	p_phys.c
//
//	general physics routines for physics.dll
///////////////////////////////////////////////////////////////////////////////

#include	"p_global.h"
#include	"p_user.h" 

/*
pushmove objects do not obey gravity, and do not interact with each other or trigger fields, but block normal movement and push normal objects when they move.

onground is set for toss objects when they come to a complete rest.  it is set for steping or walking objects 

doors, plats, etc are SOLID_BSP, and MOVETYPE_PUSH
bonus items are SOLID_TRIGGER touch, and MOVETYPE_TOSS
corpses are SOLID_NOT and MOVETYPE_TOSS
crates are SOLID_BBOX and MOVETYPE_TOSS
walking monsters are SOLID_SLIDEBOX and MOVETYPE_STEP
flying/floating monsters are SOLID_SLIDEBOX and MOVETYPE_FLY

solid_edge items only clip against bsp models.

*/

///////////////////////////////////////////////////////////////////////////////
//	defines
///////////////////////////////////////////////////////////////////////////////

#define	PHYS_MAX_CLIP_PLANES	5
#define	PHYS_STOP_EPSILON		0.1
#define	PHYS_MAX_PUSHES			4

#define	PHYS_BLOCKED_FLOOR		0x01	//	1 = floor
#define	PHYS_BLOCKED_STEP		0x02	//	2 = wall / step
#define	PHYS_BLOCKED_STOPPED	0x04	//	4 = dead stop
#define	PHYS_BLOCKED_STUCK		0x08	//	8 = stuck inside something

//FIXME: P_AddRotationalFriction:  hacked in for E3 demo
#define	p_stopspeed		100
#define p_friction			6
#define p_waterfriction	1

#define	PHYS_STEPSIZE    18

#define	SVF_PUSHED		0x00000800	

///////////////////////////////////////////////////////////////////////////////
//	typedefs
///////////////////////////////////////////////////////////////////////////////

typedef	struct
{
	trace_t	trace;
} float_pushed_t;

typedef struct
{
	edict_t	*ent;
	vec3_t	origin;
	vec3_t	angles;
	float	deltayaw;
} pushed_t;

///////////////////////////////////////////////////////////////////////////////
//	globals
///////////////////////////////////////////////////////////////////////////////

pushed_t		pushed[MAX_EDICTS], *pushed_p;
edict_t			*obstacle;
static	int		p_run_think;


///////////////////////////////////////////////////////////////////////////////
//	P_GetWaterLevel
//
//	gets the current liqud level of an entity
//	0 = not in a loquid
//	1 = feet in a liquid
//	2 = origin (-mins above feet) in a liquid
//	3 = entirely submerged in a liquid
//
//	also checks to see in the entity transitioned from a liquid to air or
//	vice versa, and plays a default sound if there was a transition and
//	SVF_NOSPLASH is not set
///////////////////////////////////////////////////////////////////////////////

void	P_GetWaterLevel (edict_t *ent)
{
	vec3_t	test_org;
	int		water_type = 0;
	int		last_water_type = ent->watertype;
	int		last_water_level = ent->waterlevel;

	VectorCopy (ent->s.origin, test_org);
	ent->watertype = 0;
	ent->waterlevel = 0;
	
	///////////////////////////////////////////////////////////////////////////
	//	check feet first, if they aren't in water, don't bother check the
	//	other points
	///////////////////////////////////////////////////////////////////////////

	test_org [2] += (ent->s.mins [2] + 1);
	ent->watertype |= (gi.pointcontents (test_org) & MASK_WATER);
	if (ent->watertype != 0)
	{
		//	feet are in water
		ent->waterlevel = 1;

		///////////////////////////////////////////////////////////////////////////
		//	check origin
		///////////////////////////////////////////////////////////////////////////

		test_org [2] -= (ent->s.mins [2] + 1);
		water_type = (gi.pointcontents (test_org) & MASK_WATER);
		if (water_type != 0)
		{
			//	oriing is in water
			ent->watertype |= water_type;
			ent->waterlevel = 2;

			///////////////////////////////////////////////////////////////////////////
			//	check top
			///////////////////////////////////////////////////////////////////////////

			test_org [2] += (ent->s.maxs [2] - 1);
			water_type = (gi.pointcontents (test_org) & MASK_WATER);
			if (water_type != 0)
			{
				ent->watertype |= water_type;
				ent->waterlevel = 3;
			}
		}
	}

	//	don't splash if this is first frame for this entity
	//	otherwise, entity can spawn in water and make a splashing noise
	if (ent->svflags & SVF_NEWSPAWN)
		return;

	//	don't splash if SVF_NOSPLASH set or if this is the first physics frame
	if (ent->svflags & SVF_NOSPLASH || level.framenum < 2)
		return;

	if (ent->waterlevel == 0 && last_water_level > 0)
		//	exited water
		gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex("engine/waterhit.wav"), 1, 1, 0);
	else if (ent->waterlevel > 0 && last_water_level == 0)
		//	entered water
		gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex("engine/waterhit.wav"), 1, 1, 0);
}

///////////////////////////////////////////////////////////////////////////////
//	P_CheckWaterTransition
//
//	determine if an object has just crossed a water boundary
///////////////////////////////////////////////////////////////////////////////

void	P_CheckWaterTransition (edict_t *ent, vec3_t old_origin)
{
	qboolean	wasinwater, isinwater;

	wasinwater = (ent->watertype & MASK_WATER);
	ent->watertype = gi.pointcontents (ent->s.origin);
	isinwater = ent->watertype & MASK_WATER;

	if (isinwater)
		ent->waterlevel = 1;
	else
		ent->waterlevel = 0;

	//	don't splash if this is first frame for this entity
	//	otherwise, entity can spawn in water and make a splashing noise
	if (ent->svflags & SVF_NEWSPAWN)
		return;

	//	don't splash if SVF_NOSPLASH set or if this is the first physics frame
	if (ent->svflags & SVF_NOSPLASH || level.framenum < 2)
		return;

	if (ent->movetype == MOVETYPE_FLOAT)
	{
		//	MOVETYPE_FLOAT only spashes at high velocity
		if (VectorLength (ent->velocity) > 180)//ent->velocity [2] > 240 || ent->velocity [2] < -240)
		{
			if (!wasinwater && isinwater)
				//	entering water sound
				gi.positioned_sound (old_origin, g_edicts, CHAN_AUTO, gi.soundindex("player/playerlandinwater.wav"), 1, 1, 0);
			else if (wasinwater && !isinwater)
				//	exiting water sound
				gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex("engine/waterhit.wav"), 1, 1, 0);
		}
		else
		{
			//	maybe play a slight gurgling sound here... but definitely no splash!
			//	only play on entering water!
			//	FIXME:	enable when we get a better sound!
/*
			if (!wasinwater && !sinwater)
				//	exiting water sound
				gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex("player/playerexitwater.wav"), 1, 1, 0);
*/
		}
	}
	else
	{
		if (!wasinwater && isinwater)
			gi.positioned_sound (old_origin, g_edicts, CHAN_AUTO, gi.soundindex("engine/waterhit.wav"), 1, 1, 0);
		else if (wasinwater && !isinwater)
			gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex("engine/waterhit.wav"), 1, 1, 0);
	}
}

///////////////////////////////////////////////////////////////////////////////
//	P_CheckGround
///////////////////////////////////////////////////////////////////////////////

void P_CheckGround (edict_t *ent)
{
	vec3_t		point;
	trace_t		trace;

//	if (ent->flags & (FL_SWIM | FL_FLY))
	if (ent->movetype == MOVETYPE_FLY)
	{
		ent->groundEntity = NULL;
		ent->groundSurface = NULL;
		return;
	}

	// if the hull point one-quarter unit down is solid the entity is on ground
	point[0] = ent->s.origin[0];
	point[1] = ent->s.origin[1];
	point[2] = ent->s.origin[2] - 1.00;

	if (ent->clipmask)
		trace = gi.trace (ent->s.origin, ent->s.mins, ent->s.maxs, point, ent, ent->clipmask);
	else
		trace = gi.trace (ent->s.origin, ent->s.mins, ent->s.maxs, point, ent, MASK_MONSTERSOLID);

	// check steepness
	if ( trace.plane.normal[2] < 0.7 && !trace.startsolid)
	{
//		gi.conprintf ("P_CheckGround: Plane too steep for groundEntity.\n");
		ent->groundEntity = NULL;
		ent->groundSurface = NULL;
		return;
	}

//	if (!trace.startsolid && !trace.allsolid)
		VectorCopy (trace.endpos, ent->s.origin);
	ent->groundEntity = trace.ent;
	ent->groundEntity_linkcount = trace.ent->linkcount;
	ent->groundSurface = trace.surface;
	ent->velocity[2] = 0;

}

///////////////////////////////////////////////////////////////////////////////
//	P_TestEntityPosition
//
///////////////////////////////////////////////////////////////////////////////

edict_t	*P_TestEntityPosition (edict_t *ent)
{
	trace_t	trace;

	if (ent->clipmask)
		trace = gi.trace (ent->s.origin, ent->s.mins, ent->s.maxs, ent->s.origin, ent, ent->clipmask);
	else
		trace = gi.trace (ent->s.origin, ent->s.mins, ent->s.maxs, ent->s.origin, ent, MASK_SOLID);
	
	if (trace.startsolid || trace.allsolid)
		return trace.ent;
		
	return NULL;
}

///////////////////////////////////////////////////////////////////////////////
//	P_CheckVelocity
//
///////////////////////////////////////////////////////////////////////////////

void P_CheckVelocity (edict_t *ent)
{
	int		i;

//
// bound velocity
//
	for (i=0 ; i<3 ; i++)
	{
		if (ent->velocity[i] > p_maxvelocity->value)
			ent->velocity[i] = p_maxvelocity->value;
		else if (ent->velocity[i] < -p_maxvelocity->value)
			ent->velocity[i] = -p_maxvelocity->value;
	}
}

///////////////////////////////////////////////////////////////////////////////
//	P_RunThink
//	
//	Runs thinking code for this frame if necessary
///////////////////////////////////////////////////////////////////////////////

qboolean P_RunThink (edict_t *ent, int run_think)
{
	float	thinktime;

	//	physics called from p_client, so don't run a think
	if (!run_think)
		return	true;

	thinktime = ent->nextthink;
	
	if (thinktime <= 0 || thinktime > level.time + 0.001)
	{
//		if (ent->flags & (FL_MONSTER + FL_CLIENT + FL_BOT))
//			dll_think_stub (ent);
		return true;
	}
	
	if (thinktime < level.time)
		thinktime = level.time;

	ent->nextthink = 0;

//	if (!ent->think)
//		gi.error ("NULL ent->think");

	if (ent->think)
	{
		serverState.time = thinktime;
		ent->think (ent);
	}

	return false;
}

///////////////////////////////////////////////////////////////////////////////
//	P_StaticFriction
//
//	returns the force required to overcome a stopped entity's static friction
//
//	this isn't 100% correct, because true friction depends on both the 
//	ground surface and the object's surface, but this only considers the
//	ground surface.
///////////////////////////////////////////////////////////////////////////////

float	P_StaticFriction (edict_t *ent)
{
	float	force;
	float	friction_coefficient;

	if (!ent->groundEntity || !ent->groundSurface)
		return	0;

	//	get the friction coefficient according to the surface flags
	if (ent->groundSurface->flags & SURF_WOOD)
		friction_coefficient = 0.3;
	else if (ent->groundSurface->flags & SURF_METAL)
		//	metal is really hard to start a push on
		//	but slides easily once it is moving
		friction_coefficient = 0.3;	
	else if (ent->groundSurface->flags & SURF_STONE)
		friction_coefficient = 0.6;
	else if (ent->groundSurface->flags & SURF_GLASS)
		friction_coefficient = 0.3;
	else if (ent->groundSurface->flags & SURF_ICE)
		friction_coefficient = 0.025;
	else if (ent->groundSurface->flags & SURF_CARPET)
		friction_coefficient = 0.4;
	else
		//	all other surface flags are standard friction
		friction_coefficient = 0.3;

	force = p_gravity->value * ent->mass * friction_coefficient;

	return	force;
}

///////////////////////////////////////////////////////////////////////////////
//	P_MomentumPush
//
//	totally inelastic collision
//
//	objects collide and both go off in the same direction,
//	with the same velocity
//
//	since object 1 has to be moving already, we check to
//	see if object 2 is stationary.  If so, we determine 
//	the force necessary to overcome its friction and subtract
//	that from the applied force of the pusher
//
//	pushes entities using velocity vectors
//	different from P_PushEntity which moves
//	the pushed entity instead of changing its
//	velocity
//
///////////////////////////////////////////////////////////////////////////////

void	P_MomentumPush (edict_t *e1, edict_t *e2, vec3_t push_velocity)
{
	vec3_t	new_dir, impact_vel, end;
	float	momentum1, momentum2, vf, dp2;
	trace_t	trace;

	if (e1->movetype == MOVETYPE_PUSH || e1->solid == SOLID_BSP ||
		e2->movetype == MOVETYPE_PUSH || e2->solid == SOLID_BSP ||
		!(e2->flags & FL_PUSHABLE) || !(e1->flags & FL_NOPUSH))
		return;

	if (!push_velocity)
		VectorCopy (e1->velocity, impact_vel);
	else
		VectorCopy (push_velocity, impact_vel);

	//	if standing on the pushed object, don't make it slide around in x/y
	if (e1->groundEntity == e2)
		impact_vel [0] = impact_vel [1] = 0;

	// find the momentum of each object
	momentum1 = VectorLength (impact_vel) * e1->mass;
	momentum2 = VectorLength (e2->velocity) * e2->mass;

	//	if the impacted object is not moving, find the force
	//	needed to overcome it's friction
	if (VectorLength (e2->velocity) == 0.0 || 
		e2->groundEntity && 
		!e2->svflags & SVF_PUSHED)
		// FIXME: once we have texture detection, base friction
		// coeffecient on the current surface
		// assume friction of approximately steel on steel
		dp2 = P_StaticFriction (e2);
//		dp2 = 800 * e2->mass * 0.3;
	// otherwise, give it no additional friction
	else
		dp2 = 800 * e2->mass * P_StaticFriction (e2) * 0.3;
//		dp2 = 0;

	//	fudge momentum a bit...
//	dp2 *= 0.5;

	momentum1 = momentum1 - dp2;
	if (momentum1 < 0) momentum1 = 0;

	//	add the two velocities to get the resulting direction
	VectorAdd (impact_vel, e2->velocity, new_dir);
	VectorNormalize (new_dir);

	//	calculate final velocities using Law of Conservation of Momentum
	vf = (momentum1 + momentum2) / (e1->mass + e2->mass);

	if (vf == 0)
		return;

	// scale the resultant vector by the final velocity
	VectorScale (new_dir, vf, e2->velocity);

	e2->groundEntity = NULL;	
	e2->groundSurface = NULL;
	e2->svflags |= SVF_PUSHED;

	//	move the pushed entity up one unit
	VectorCopy (e2->s.origin, end);
	end [2] += 1;
	if (e2->clipmask)
		trace = gi.trace (e2->s.origin, e2->s.mins, e2->s.maxs, end, e2, e2->clipmask);
	else
		trace = gi.trace (e2->s.origin, e2->s.mins, e2->s.maxs, end, e2, MASK_SOLID);

	VectorCopy (trace.endpos, e2->s.origin);
}

///////////////////////////////////////////////////////////////////////////////
//	P_Impact
//	
//	Two entities have touched, so call P_MomentumPush to compute
//	velocities and then run their touch functions
///////////////////////////////////////////////////////////////////////////////

void P_Impact (edict_t *e1, trace_t *trace)
{
	edict_t		*e2;
//	cplane_t	backplane;

	e2 = trace->ent;

	///	Nelno:	if one entity is a client, then impart his velocity to
	///	the other object
	if ((e1->solid != SOLID_NOT && e2->solid != SOLID_NOT) &&
		(e1 != g_edicts && e2 != g_edicts) && !(e1->flags & FL_NOPUSH))
	{
		if (e2->flags & FL_PUSHABLE)
		{
			if (e1->movetype != MOVETYPE_NONE && e2->movetype != MOVETYPE_NONE)
				P_MomentumPush (e1, e2, NULL);
		}
	}

	if (e1->touch && e1->solid != SOLID_NOT)
		e1->touch (e1, e2, &trace->plane, trace->surface);
	
	if (e2->touch && e2->solid != SOLID_NOT)
		e2->touch (e2, e1, &trace->plane, trace->surface);    // mike: this should send trace info, right??
//		e2->touch (e2, e1, NULL, NULL);
}

///////////////////////////////////////////////////////////////////////////////
//	P_RunTouches
//	
//	Two entities have touched, so run their touch functions
///////////////////////////////////////////////////////////////////////////////

void P_RunTouches (edict_t *e1, trace_t *trace)
{
	edict_t		*e2;

	e2 = trace->ent;

	if (e1->touch && e1->solid != SOLID_NOT)
		e1->touch (e1, e2, &trace->plane, trace->surface);
	
	if (e2->touch && e2->solid != SOLID_NOT)
		e2->touch (e2, e1, &trace->plane, trace->surface);    // mike: this should send trace info, right??
//		e2->touch (e2, e1, NULL, NULL);
}

///////////////////////////////////////////////////////////////////////////////
//	ClipVelocity
//
//	Slide off of the impacting object
//	returns the blocked flags (1 = floor, 2 = step / wall)
///////////////////////////////////////////////////////////////////////////////

int ClipVelocity (vec3_t in_velocity, vec3_t normal, vec3_t out_velocity, float overbounce)
{
	float	backoff;
	float	change;
	int		i, blocked;
	
	blocked = 0;
	if (normal [2] > 0)
		blocked |= 1;		// floor
	if (!normal [2])
		blocked |= 2;		// step
	
	backoff = DotProduct (in_velocity, normal) * overbounce;

	for (i=0 ; i<3 ; i++)
	{
		change = normal [i] * backoff;
		out_velocity[i] = in_velocity[i] - change;
		if (out_velocity [i] > -PHYS_STOP_EPSILON && out_velocity [i] < PHYS_STOP_EPSILON)
			out_velocity [i] = 0;
	}
	
	return blocked;
}

///////////////////////////////////////////////////////////////////////////////
//	ClipEntVelocity
//
//	reflects a velocity vector from a plane with normal normal.
//	scales speed by ent->elasticy, so based on elasticity, ents can either
//	lose speed, gain speed, or keep a constant speed (however, gravity is still
//	affecting the entity, so maintaining a constant speed is unlikely).
///////////////////////////////////////////////////////////////////////////////

int ClipEntVelocity (edict_t *ent, vec3_t in_velocity, vec3_t normal, vec3_t out_velocity)
{
	float	dp;
	float	speed;
	int		i, blocked;

	blocked = 0;
	if (normal [2] > 0)
		blocked |= 1;		// floor
	if (!normal [2])
		blocked |= 2;		// step

	speed = VectorNormalize (in_velocity);
	dp = DotProduct (in_velocity, normal) * 2.0;

	for (i = 0; i < 3; i++)
	{
		out_velocity [i] = in_velocity [i] - (normal [i] * dp);

		if (out_velocity [i] > -PHYS_STOP_EPSILON && out_velocity [i] < PHYS_STOP_EPSILON)
			out_velocity [i] = 0;
	}

	VectorNormalize (out_velocity);
	VectorScale (out_velocity, speed * ent->elasticity, out_velocity);

	return blocked;
}


///////////////////////////////////////////////////////////////////////////////
//	P_FlyMove
//
//	The basic solid body movement clip that slides along multiple planes
//	Returns the clipflags if the velocity was modified (hit something solid)
//	1 = floor
//	2 = wall / step
//	4 = dead stop
//	8 = stuck inside something
///////////////////////////////////////////////////////////////////////////////

int P_FlyMove (edict_t *ent, float time, int mask)
{
	edict_t		*hit;
	int			bumpcount, numbumps;
	vec3_t		dir;
	float		d;
	int			numplanes;
	vec3_t		planes[PHYS_MAX_CLIP_PLANES];
	vec3_t		primal_velocity, original_velocity, new_velocity;
	int			i, j;
	trace_t		trace;
	vec3_t		end;
	float		time_left;
	int			blocked;
	
	numbumps = 4;
	
	blocked = 0;
	VectorCopy (ent->velocity, original_velocity);
	VectorCopy (ent->velocity, primal_velocity);
	numplanes = 0;
	
	time_left = time;

	for (bumpcount=0 ; bumpcount<numbumps ; bumpcount++)
	{
		for (i=0 ; i<3 ; i++)
			end[i] = ent->s.origin[i] + time_left * ent->velocity[i];

		trace = gi.trace (ent->s.origin, ent->s.mins, ent->s.maxs, end, ent, mask);

		if (trace.allsolid || trace.startsolid)
		{	// entity is trapped in another solid
//			gi.conprintf ("FlyMove: %s is trapped in %s\n", ent->className, trace.ent->className);
			VectorCopy (vec3_origin, ent->velocity);
			return PHYS_BLOCKED_STUCK;
		}

		if (trace.fraction > 0)
		{	// actually covered some distance
			VectorCopy (trace.endpos, ent->s.origin);
			VectorCopy (ent->velocity, original_velocity);
			numplanes = 0;
		}

		if (trace.fraction == 1)
			 break;		// moved the entire distance

		hit = trace.ent;

		if (trace.plane.normal[2] > 0.7)
		{
			blocked |= PHYS_BLOCKED_FLOOR;		// floor
//			gi.conprintf ("FlyMove: %s blocked by floor.\n", ent->className);
			if ( hit->solid == SOLID_BSP)// || hit == g_edicts)
			{
				ent->groundEntity = hit;
				ent->groundSurface = trace.surface;
				ent->groundEntity_linkcount = hit->linkcount;
			}
		}

		//	NelnoFIXME:	should we check for step sides that aren't straight up/down?
		if (!trace.plane.normal[2])
		{
			blocked |= PHYS_BLOCKED_STEP;		// step
//			gi.conprintf ("FlyMove: %s blocked by step.\n", ent->className);
		}

//
// run the impact function
//
		P_Impact (ent, &trace);
		if (!ent->inuse)
			break;		// removed by the impact function

		
		time_left -= time_left * trace.fraction;
		
	// cliped to another plane
		if (numplanes >= PHYS_MAX_CLIP_PLANES)
		{	// this shouldn't really happen
//			gi.conprintf ("FlyMove: %s MAX_CLIP_PLANES.\n", ent->className);
			VectorCopy (vec3_origin, ent->velocity);
			return PHYS_BLOCKED_STEP | PHYS_BLOCKED_FLOOR;
		}

		VectorCopy (trace.plane.normal, planes[numplanes]);
		numplanes++;

//
// modify original_velocity so it parallels all of the clip planes
//
		for (i=0 ; i<numplanes ; i++)
		{
			ClipVelocity (original_velocity, planes[i], new_velocity, 1);
			for (j=0 ; j<numplanes ; j++)
				if (j != i)
				{
					if (DotProduct (new_velocity, planes[j]) < 0)
						break;	// not ok
				}
			if (j == numplanes)
				break;
		}
		
		if (i != numplanes)
		{	// go along this plane
			VectorCopy (new_velocity, ent->velocity);
		}
		else
		{	// go along the crease
			if (numplanes != 2)
			{
//				gi.dprintf ("clip velocity, numplanes == %i\n",numplanes);
//				gi.conprintf ("FlyMove: %s dead stop.\n", ent->className);
				VectorCopy (vec3_origin, ent->velocity);
				return PHYS_BLOCKED_STEP | PHYS_BLOCKED_FLOOR | PHYS_BLOCKED_STOPPED;
			}
			CrossProduct (planes[0], planes[1], dir);
			d = DotProduct (dir, ent->velocity);
			VectorScale (dir, d, ent->velocity);
		}

//
// if original velocity is against the original velocity, stop dead
// to avoid tiny occilations in sloping corners
//
		if (DotProduct (ent->velocity, primal_velocity) <= 0)
		{
			VectorCopy (vec3_origin, ent->velocity);
			return blocked;
		}
	}

	return blocked;
}


///////////////////////////////////////////////////////////////////////////////
//	P_AddGravity
//
///////////////////////////////////////////////////////////////////////////////

void P_AddGravity (edict_t *ent)
{
	ent->velocity[2] -= ent->gravity * p_gravity->value * p_frametime_scaled;
//	ent->velocity[2] -= ent->gravity * 1 * p_frametime_scaled;
}

/* ------------------------------- PUSHMOVE -------------------------------- */

///////////////////////////////////////////////////////////////////////////////
//	P_PushEntity
//
//	Does not change the entities velocity at all
///////////////////////////////////////////////////////////////////////////////

trace_t P_PushEntity (edict_t *ent, vec3_t push)
{
	trace_t	trace;
	vec3_t	start;
	vec3_t	end;
	int		mask;

	VectorCopy (ent->s.origin, start);
	VectorAdd (start, push, end);

retry:
	if (ent->clipmask)
		mask = ent->clipmask;
	else
		mask = MASK_SOLID;

	trace = gi.trace (start, ent->s.mins, ent->s.maxs, end, ent, mask);

	if (trace.allsolid || trace.startsolid && (trace.endpos [0] != start [0] && trace.endpos [1] != start [1] && trace.endpos [2] != start [2]))
	{
		//	entity is stuck inside another entity
		//	GET IT OUT!! IT HURTS!! IT HURTS!!
		//gi.dprintf ("%s is stuck in %s.\n", ent->className, trace.ent->className);
		trace.fraction = 0.0;
		VectorCopy (start, trace.endpos);
	}
	
	VectorCopy (trace.endpos, ent->s.origin);
	gi.linkentity (ent);

	if (trace.fraction != 1.0)
	{
		P_Impact (ent, &trace);

		//	if the pushed entity went away and the pusher is still there
		if (!trace.ent->inuse && ent->inuse)
		{
			// move the pusher back and try again
			VectorCopy (start, ent->s.origin);
			gi.linkentity (ent);
			goto retry;
		}
	}

	if (ent->inuse) 
		P_TouchTriggers (ent);

	return trace;
}					

///////////////////////////////////////////////////////////////////////////////
//	P_Float_PushEntity
//
//	tries to move any entity that is touched, except for worldspawn
///////////////////////////////////////////////////////////////////////////////

trace_t P_Float_PushEntity (edict_t *ent, vec3_t push)
{
	trace_t			trace;
	vec3_t			start, end;
	int				mask, i, pushes;
	int				pushed_ents, breakout;
	float			push_len;
	float_pushed_t	float_pushed [PHYS_MAX_PUSHES];

	VectorCopy (ent->s.origin, start);
	VectorAdd (start, push, end);
	
	push_len = qv_len (push);

p_float_pushentity_retry:
	breakout = false;
	pushed_ents = 0;

	memset (float_pushed, 0x00, sizeof (float_pushed_t) * PHYS_MAX_PUSHES);

	if (ent->clipmask)
		mask = ent->clipmask;
	else
		mask = MASK_SOLID;

	for (pushes = 0; pushes < PHYS_MAX_PUSHES; pushes++)
	{
		trace = gi.trace (start, ent->s.mins, ent->s.maxs, end, ent, mask);

		if (trace.allsolid || trace.startsolid && (trace.endpos [0] != start [0] && trace.endpos [1] != start [1] && trace.endpos [2] != start [2]))
		{
			//	entity is stuck inside another entity
			//	GET IT OUT!! IT HURTS!! IT HURTS!!
			//gi.dprintf ("%s is stuck in %s.\n", ent->className, trace.ent->className);

			goto	p_float_pushentity_exit;
		}

		if (trace.fraction == 1.0)
		{
			//	moved all the way
			break;
		}

		if (trace.ent->flags & FL_CLIENT && push [2] < 0.125)
		{
			breakout = true;
		}
		else if (trace.fraction != 1.0 && trace.ent != g_edicts &&
			trace.ent->flags & FL_PUSHABLE)
		{
			//	try to push the entity that is in the way
			P_MomentumPush (ent, trace.ent, ent->velocity);

			//	FIXME:	requires that all p_phys routines for FL_PUSHABLE objects
			//			are re-entrant!!

			if (!(ent->flags & FL_CLIENT))
				P_RunEntity (trace.ent, p_run_think);
			else
				P_PushEntity (trace.ent, push);

			//	if entity didn't move, we can't possible go any farther
			//	so break out of tracing and do the touch functions
			if (trace.ent->s.old_origin [0] == trace.ent->s.origin [0] &&
				trace.ent->s.old_origin [1] == trace.ent->s.origin [1] &&
				trace.ent->s.old_origin [2] == trace.ent->s.origin [2])
			{
				breakout = true;
			}
		}

		//////////////////////////////////////////////////////////////////////
		//	add to list of pushed entities for touching at end of move
		///////////////////////////////////////////////////////////////////////
		if (trace.ent && trace.ent != g_edicts)
		{
			//	add the pushed entity to the float_pushed list if not already added
			if (pushed_ents == 0)
			{
				float_pushed [0].trace = trace;
				pushed_ents++;
			}
			else
			{
				for (i = 0; i < pushed_ents && float_pushed [i].trace.ent != trace.ent; i++);

				//	wasn't in list, so add it
				if (i >= pushed_ents)
				{
					float_pushed [pushed_ents].trace = trace;
					pushed_ents++;
				}
			}
		}

		if (breakout)
				break;
	}

	trace = gi.trace (start, ent->s.mins, ent->s.maxs, end, ent, mask);

	if (trace.allsolid || trace.startsolid)// && (trace.endpos [0] != start [0] && trace.endpos [1] != start [1] && trace.endpos [2] != start [2]))
	{
		//	entity is stuck inside another entity
		//	GET IT OUT!! IT HURTS!! IT HURTS!!
		goto	p_float_pushentity_exit;
	}

	VectorCopy (trace.endpos, ent->s.origin);
	gi.linkentity (ent);

	if (P_TestEntityPosition (ent))
		//	this should never happen!!
		gi.conprintf ("PusEntity: TestEntityPosition failed.\n");

	for (i = 0; i < pushed_ents; i++)
	{
		P_RunTouches (ent, &float_pushed [i].trace);

		//	if the pushed entity went away and the pusher is still there
		if (!float_pushed [i].trace.ent->inuse && ent->inuse)
		{
			// move the pusher back and try again
			VectorCopy (start, ent->s.origin);
			gi.linkentity (ent);
			goto p_float_pushentity_retry;
		}
	}

p_float_pushentity_exit:

	//	FIXME:	touch all pushed entities
	if (ent->inuse) 
		P_TouchTriggers (ent);

	return trace;
}					

///////////////////////////////////////////////////////////////////////////////
//	P_Push
//
//	Objects need to be moved back on a failed push,
//	otherwise riders would continue to slide.
///////////////////////////////////////////////////////////////////////////////

int	P_Push (edict_t *pusher, vec3_t move, vec3_t amove)
{
	int			i, e;
	edict_t		*check, *block;
	vec3_t		mins, maxs;
	pushed_t	*p;
	vec3_t		org, org2, move2, forward, right, up;

	// clamp the move to 1/8 units, so the position will
	// be accurate for client side prediction
	for (i=0 ; i<3 ; i++)
	{
		float	temp;
		temp = move[i]*8.0;
		if (temp > 0.0)
			temp += 0.5;
		else
			temp -= 0.5;
		move[i] = 0.125 * (int)temp;
	}

	// find the bounding box
	for (i=0 ; i<3 ; i++)
	{
		mins[i] = pusher->absmin[i] + move[i];
		maxs[i] = pusher->absmax[i] + move[i];
	}

// we need this for pushing things later
	VectorSubtract (vec3_origin, amove, org);
	AngleVectors (org, forward, right, up);

// save the pusher's original position
	pushed_p->ent = pusher;
	VectorCopy (pusher->s.origin, pushed_p->origin);
	VectorCopy (pusher->s.angles, pushed_p->angles);
	if (pusher->client)
		pushed_p->deltayaw = SHORT2ANGLE (pusher->client->ps.pmove.delta_angles[YAW]);
	pushed_p++;

// move the pusher to it's final position
	VectorAdd (pusher->s.origin, move, pusher->s.origin);
	VectorAdd (pusher->s.angles, amove, pusher->s.angles);
	gi.linkentity (pusher);

	// see if any solid entities are inside the final position
	check = g_edicts+1;
	for (e = 1; e < globals.num_edicts; e++, check++)
	{
		if (!check->inuse)
			continue;
		if (check->movetype == MOVETYPE_PUSH
		|| check->movetype == MOVETYPE_STOP
		|| check->movetype == MOVETYPE_NONE
		|| check->movetype == MOVETYPE_NOCLIP)
			continue;

//		if (!check->area.prev)
//			continue;

	// if the entity is standing on the pusher, it will definitely be moved
		if (check->groundEntity != pusher)
		{
			// see if the ent needs to be tested
			if ( check->absmin[0] >= maxs[0]
			|| check->absmin[1] >= maxs[1]
			|| check->absmin[2] >= maxs[2]
			|| check->absmax[0] <= mins[0]
			|| check->absmax[1] <= mins[1]
			|| check->absmax[2] <= mins[2] )
				continue;

			// see if the ent's bbox is inside the pusher's final position
			if (!P_TestEntityPosition (check))
				continue;
		}

		if ((pusher->movetype == MOVETYPE_PUSH) || (check->groundEntity == pusher))
		{
			// move this entity
			pushed_p->ent = check;
			VectorCopy (check->s.origin, pushed_p->origin);
			VectorCopy (check->s.angles, pushed_p->angles);
			pushed_p++;

			// try moving the contacted entity 
			VectorAdd (check->s.origin, move, check->s.origin);

			if (check->client && check->flags & FL_CLIENT)
			{	// FIXME: doesn't rotate monsters?
				check->client->ps.pmove.delta_angles[YAW] += ANGLE2SHORT (amove[YAW]);
			}

			// figure movement due to the pusher's amove
			VectorSubtract (check->s.origin, pusher->s.origin, org);
			org2[0] = DotProduct (org, forward);
			org2[1] = -DotProduct (org, right);
			org2[2] = DotProduct (org, up);
			VectorSubtract (org2, org, move2);
			VectorAdd (check->s.origin, move2, check->s.origin);

			// may have pushed them off an edge
			if (check->groundEntity != pusher)
			{
				check->groundEntity = NULL;
				check->groundSurface = NULL;
			}

			block = P_TestEntityPosition (check);
			if (!block)
			{	// pushed ok
				gi.linkentity (check);
				// impact?
				continue;
			}

			// if it is ok to leave in the old position, do it
			// this is only relevent for riding entities, not pushed
			// FIXME: this doesn't acount for rotation
			VectorSubtract (check->s.origin, move, check->s.origin);
			block = P_TestEntityPosition (check);
			if (!block)
			{
				pushed_p--;
				continue;
			}

			// is the pusher an entity that should force other entities out of 
			// the way instead of not moving ?  (i.e. an escalator)
			if (pusher->flags & FL_FORCEMOVE)
			{
				// if the entity we're colliding with is really SOLID_NOT, 
				// (like a glock shell) we don't care so blow off this collision
				if (check->solid == SOLID_NOT)
				{
					pushed_p--;
					continue;
				}

				// last check... if this is the client or projectile, it could be on
				// an escalator.. if so, let's try bumping it up instead
				// of into the escalator itself..

				if (move[2] < 0)	// train is going down
				{
					// push it forward and up
					check->s.origin[0] += move[0];
					check->s.origin[1] += move[1];
					check->s.origin[2] += 8;
				}
				else				// train is going up
				{
					// push it backwards and up
					check->s.origin[0] -= move[0];
					check->s.origin[1] -= move[1];
					check->s.origin[2] += 8;
				}

				block = P_TestEntityPosition (check);
				if (!block)
				{
					gi.linkentity (check);
					// impact?
					continue;
				}

				// if we're here... we're kinda fucked.. the FL_FORCEMOVE entity is
				// going to collide with 'check'  ... we need to add a 'remove_t' 
				// function pointer to projectiles etc so that we can remove them
				// from the world
				if (check->remove)
				{
					gi.conprintf ("P_Push: Removing entity colliding with FL_FORCEMOVE entity.\n");
					check->remove(check);
					pushed_p--;
					continue;
				}
			}
		}
		
		// save off the obstacle so we can call the block function
		obstacle = check;

		// move back any entities we already moved
		// go backwards, so if the same entity was pushed
		// twice, it goes back to the original position
		for (p=pushed_p-1 ; p>=pushed ; p--)
		{
			VectorCopy (p->origin, p->ent->s.origin);
			VectorCopy (p->angles, p->ent->s.angles);

			//	Nelno:	causes client to slide slightly
			if (p->ent->client && p->ent->flags & FL_CLIENT)
			{
				p->ent->client->ps.pmove.delta_angles[YAW] = ANGLE2SHORT (p->deltayaw);
			}

			gi.linkentity (p->ent);
		}
		return false;
	}

//FIXME: is there a better way to handle this?
	// see if anything we moved has touched a trigger
	for (p=pushed_p-1 ; p>=pushed ; p--)
		P_TouchTriggers (p->ent);

	return true;
}

///////////////////////////////////////////////////////////////////////////////
//	P_Physics_Pusher
//
//	Bmodel objects don't interact with each other, but
//	push all box objects
///////////////////////////////////////////////////////////////////////////////

void P_Physics_Pusher (edict_t *ent)
{
	vec3_t		move, amove, new_ang, new_org, offset;
	vec3_t		forward, right, up;

	edict_t		*part, *mv, *parent = NULL;
	qboolean	bIsParent = FALSE, bParentMoved = FALSE;

	int			i = 0;


	// if not a team captain, so movement will be handled elsewhere
	if ( ent->flags & FL_TEAMSLAVE)
		return;

	// make sure all team slaves can move before commiting
	// any moves or calling any think functions
	// if the move is blocked, all moved objects will be backed out

//retry:
	pushed_p = pushed;
	for (part = ent ; part ; part=part->teamchain)
	{
		// is this the parent entity?
		if (part->teamchain && !(part->flags & FL_TEAMSLAVE))
			bIsParent = TRUE;
		else
			bIsParent = FALSE;

		// is this the parent ? if so.. save his original angles
		if (bIsParent)
		{
			parent = part;
		
			part->s.angles[0] = anglemod ( part->s.angles[0] );
			part->s.angles[1] = anglemod ( part->s.angles[1] );
			part->s.angles[2] = anglemod ( part->s.angles[2] );
		}
		else
		{
			// we need to modify the parent for the movement and rotation of the parent
			// transform according to parent->s.angles... if bParentMoved == TRUE then we'll 
			// recalculate the child's position in relation to the parent
			if (bParentMoved)
			{
				////////////////////////////////////
				// update the position of the child
				////////////////////////////////////

				// transform the offset from the parent
				VectorCopy (part->childOffset, offset);
				// negate Y
				offset[1] = -offset[1];

				new_org[0] = DotProduct (offset, forward) + parent->s.origin[0];
				new_org[1] = DotProduct (offset, right) + parent->s.origin[1];
				new_org[2] = DotProduct (offset, up) + parent->s.origin[2];

				// update the child origin
				VectorCopy( new_org, part->s.origin);
				VectorCopy( part->s.origin, part->s.old_origin);

				// update the transformed origin difference
				VectorSubtract( part->s.origin, parent->s.origin, part->transformedOffset );
				
				////////////////////////////////////
				// update the angles of the child
				////////////////////////////////////
				VectorAdd( parent->s.angles, part->angle_delta, part->s.angles );

				// make sure they are between 0-359
				part->s.angles[0] = anglemod ( part->s.angles[0] );
				part->s.angles[1] = anglemod ( part->s.angles[1] );
				part->s.angles[2] = anglemod ( part->s.angles[2] );
			}
		}

		// if this part has any velocities, it means it's going to move so we need to check physics
		if (bParentMoved ||
			part->velocity[0]  || part->velocity[1]  || part->velocity[2] ||
			part->avelocity[0] || part->avelocity[1] || part->avelocity[2])
		{	// object is moving
			VectorScale (part->velocity, p_frametime_scaled, move);
			VectorScale (part->avelocity, p_frametime_scaled, amove);

			if (!P_Push (part, move, amove))
				break;	// move was blocked

			if (bIsParent)
				bParentMoved = TRUE;
		}

		// save the angular difference of the parent
		if (bIsParent && bParentMoved)
		{
			// calculate the transformation matrix
			VectorCopy (parent->s.angles, new_ang);
			AngleVectors (new_ang, forward, right, up);
		}

	}

	if (pushed_p > &pushed[MAX_EDICTS])
		gi.error ("pushed_p > &pushed[MAX_EDICTS], memory corrupted");

	if (part)
	{
		// the move failed, bump all nextthink times and back out moves
		for (mv = ent ; mv ; mv=mv->teamchain)
		{
			if (mv->nextthink > 0)
				mv->nextthink += p_frametime_scaled;
		}

		// if the pusher has a "blocked" function, call it
		// otherwise, just stay in place until the obstacle is gone
		if (part->blocked)
			part->blocked (part, obstacle);
#if 0
		// if the pushed entity went away and the pusher is still there
		if (!obstacle->inuse && part->inuse)
			goto retry;
#endif
	}
	else
	{
		// the move succeeded, so call all think functions
		for (part = ent ; part ; part=part->teamchain)
		{
			if (part->think) P_RunThink (part, p_run_think);
		}
	}
}

/* -------------------------- MOVETYPE_NONE -------------------------------- */


///////////////////////////////////////////////////////////////////////////////
//  P_Physics_None
//
//	Non moving objects can only think
///////////////////////////////////////////////////////////////////////////////

void P_Physics_None (edict_t *ent)
{
	if (ent->think)
		P_RunThink (ent, p_run_think);
}

/* -------------------------- MOVETYPE_NOCLIP ------------------------------ */

///////////////////////////////////////////////////////////////////////////////
//	P_Physics_Noclip
//
//	A moving object that doesn't obey physics
///////////////////////////////////////////////////////////////////////////////

void P_Physics_Noclip (edict_t *ent)
{
	if (!P_RunThink (ent, p_run_think))
		return;
	
	VectorMA (ent->s.angles, p_frametime_scaled, ent->avelocity, ent->s.angles);
	VectorMA (ent->s.origin, p_frametime_scaled, ent->velocity, ent->s.origin);

	gi.linkentity (ent);
}


/* ------------------ MOVETYPE_TOSS, MOVETYPE_BOUNCE ---------------------- */


///////////////////////////////////////////////////////////////////////////////
//	P_Physics_Toss
//
//	Toss, bounce, and fly movement.  When onground, do nothing.
///////////////////////////////////////////////////////////////////////////////

void P_Physics_Toss (edict_t *ent)
{
	trace_t		trace;
	vec3_t		move;
	vec3_t		old_origin;
	int			mask, blocked;

	// regular thinking
	if (ent->think) 
	{
		P_RunThink (ent, p_run_think);
		if (!ent->inuse)
			//	entity was removed during its think
			return;
	}

	//	already come to a rest, so exit
	//	FIXME:	this won't register touches on toss's that have stopped
	if (ent->groundEntity)
	{
		P_CheckGround (ent);
		if (ent->groundEntity)
			return;
	}

	//	slave, so move when the master moves
	if ( ent->flags & FL_TEAMSLAVE)
		return;

	VectorCopy (ent->s.origin, old_origin);

	//	clamp velocity to p_maxvelocity
	P_CheckVelocity (ent);

	if ((ent->flags & FL_SWIM) && (ent->movetype == MOVETYPE_FLY) && 
		(ent->waterlevel < 3))
	{
		//	add gravity to swimming things if they are not completely submerged
		P_AddGravity (ent);		
	}
	else if (ent->movetype != MOVETYPE_FLY && ent->movetype != MOVETYPE_FLYMISSILE && 
		ent->movetype != MOVETYPE_BOUNCEMISSILE)
	{
		//	add gravity to movetypes that have it
		P_AddGravity (ent);
	}

	// move angles
	VectorMA (ent->s.angles, p_frametime_scaled, ent->avelocity, ent->s.angles);
	
	if (ent->svflags & SVF_PUSHED)
	{
		//	entity was pushed by something on last frame, so make it slide
		//	along planes rather than bounce off of them
		if (p_run_think)
			ent->svflags -= SVF_PUSHED;

		if (ent->clipmask)
			mask = ent->clipmask;
		else
			mask = MASK_SOLID;

		blocked = P_FlyMove (ent, p_frametime_scaled, mask);
		if (blocked)
		{
			//	can't go anywhere
			VectorCopy (old_origin, ent->s.origin);
			VectorCopy (vec3_origin, ent->velocity);
		}
		else if (P_TestEntityPosition (ent))
		{
//			gi.conprintf ("SVF_PUSHED:  TestentityPosition failed!\n");
			//	can't go anywhere
			VectorCopy (old_origin, ent->s.origin);
			VectorCopy (vec3_origin, ent->velocity);
		}

		if (ent->percent_submerged == 0.0)
			P_CheckGround (ent);

		gi.linkentity (ent);
	}
	else
	{
		// move origin
		VectorScale (ent->velocity, p_frametime_scaled, move);
		trace = P_PushEntity (ent, move);

		if (!ent->inuse)
			//	touch function may have removed entity
			return;

		//	movement vector is down and entity has not moved
		if ((ent->velocity [2] < 0 && 
			(ent->s.old_origin [0] == ent->s.origin [0] && ent->s.old_origin [1] == ent->s.origin [1] 
			&& ent->s.old_origin [2] == ent->s.origin [2])))
		{
			VectorCopy (vec3_origin, ent->velocity);
			VectorCopy (vec3_origin, ent->avelocity);
			ent->groundEntity = g_edicts;
			ent->groundSurface = trace.surface;
			ent->groundEntity_linkcount = g_edicts [0].linkcount;
			return;
		}

		if (trace.fraction < 1)
			ClipEntVelocity (ent, ent->velocity, trace.plane.normal, ent->velocity);
	}

	//	do MOVETYPE_TOSS's need to touch triggers???
	if (ent->inuse) 
		P_TouchTriggers (ent);

	P_CheckWaterTransition (ent, old_origin);
}

///////////////////////////////////////////////////////////////////////////////
//	P_Physics_Float
//
///////////////////////////////////////////////////////////////////////////////

void P_Physics_Float (edict_t *ent)
{
	trace_t		trace;
	vec3_t		move;
	vec3_t		old_origin;
	int			mask, blocked;

	// regular thinking
	if (ent->think) 
	{
		P_RunThink (ent, p_run_think);
		if (!ent->inuse)
			//	entity was removed during its think
			return;
	}

	if (ent->groundEntity && ent->percent_submerged == 0.0)
	{
		P_CheckGround (ent);
		if (ent->groundEntity)
			return;
	}

	//	slave, so move when the master moves
	if ( ent->flags & FL_TEAMSLAVE)
		return;

	VectorCopy (ent->s.origin, old_origin);

	//	clamp velocity to p_maxvelocity
	P_CheckVelocity (ent);

	ent->percent_submerged = P_PhysicsFloat (ent);
	if (ent->percent_submerged == 0.0)
		//	not floating, so add gravity
		P_AddGravity (ent);

	if (ent->svflags & SVF_PUSHED)
	{
		//	entity was pushed by something on last frame, so make it slide
		//	along planes rather than bounce off of them
		if (p_run_think)
			ent->svflags -= SVF_PUSHED;

		if (ent->clipmask)
			mask = ent->clipmask;
		else
			mask = MASK_SOLID;

		blocked = P_FlyMove (ent, p_frametime_scaled, mask);
		if (blocked)
		{
			//	can't go anywhere
			VectorCopy (old_origin, ent->s.origin);
			VectorCopy (vec3_origin, ent->velocity);
		}
		else if (P_TestEntityPosition (ent))
		{
//			gi.conprintf ("SVF_PUSHED:  TestentityPosition failed!\n");
			//	can't go anywhere
			VectorCopy (old_origin, ent->s.origin);
			VectorCopy (vec3_origin, ent->velocity);
		}

		if (ent->percent_submerged == 0.0)
			P_CheckGround (ent);


		gi.linkentity (ent);
	}
	else
	{
		// move origin
		VectorScale (ent->velocity, p_frametime_scaled, move);
//		trace = P_PushEntity (ent, move);
		trace = P_Float_PushEntity (ent, move);

		if (!ent->inuse)
			//	touch function may have removed entity
			return;

		//	movement vector is down and entity has not moved
		if (ent->velocity [2] < 0 && ent->percent_submerged == 0.0 && 
			ent->s.old_origin [0] == ent->s.origin [0] && 
			ent->s.old_origin [1] == ent->s.origin [1] 
			&& ent->s.old_origin [2] == ent->s.origin [2])
		{
			VectorCopy (vec3_origin, ent->velocity);
			VectorCopy (vec3_origin, ent->avelocity);
			ent->groundEntity = g_edicts;
			ent->groundSurface = trace.surface;
			ent->groundEntity_linkcount = g_edicts [0].linkcount;
			return;
		}

		if (trace.fraction < 1)
			ClipEntVelocity (ent, ent->velocity, trace.plane.normal, ent->velocity);
	}

	//	do MOVETYPE_FLOAT's need to touch triggers???
	if (ent->inuse) 
		P_TouchTriggers (ent);

	P_CheckWaterTransition (ent, old_origin);
}

/* ---------------------------- MOVETYPE_STEP ------------------------------ */

///////////////////////////////////////////////////////////////////////////////
//	P_CheckBottom
//
//	Returns false if any part of the bottom of the entity is off an edge that
//	is not a staircase.
///////////////////////////////////////////////////////////////////////////////

qboolean P_CheckBottom (edict_t *ent)
{
	vec3_t	start, stop;
	trace_t	trace;

	start [0] = stop [0] = ent->s.origin [0];
	start [1] = stop [1] = ent->s.origin [1];
	start [2] = stop [2] = ent->s.origin [2];
	stop [2] += 1;

	trace = gi.trace (start, ent->s.mins, ent->s.maxs, stop, ent, MASK_MONSTERSOLID);

	if (trace.fraction == 1.0)
		//	not on ground
		return	false;
	else
		return	true;
}

///////////////////////////////////////////////////////////////////////////////
//	P_AddRotationalFricton
//
///////////////////////////////////////////////////////////////////////////////

void P_AddRotationalFriction (edict_t *ent)
{
	int		n;
	float	adjustment;

	VectorMA (ent->s.angles, p_frametime_scaled, ent->avelocity, ent->s.angles);
	adjustment = p_frametime_scaled * p_stopspeed * p_friction;
	for (n = 0; n < 3; n++)
	{
		if (ent->avelocity[n] > 0)
		{
			ent->avelocity[n] -= adjustment;
			if (ent->avelocity[n] < 0)
				ent->avelocity[n] = 0;
		}
		else
		{
			ent->avelocity[n] += adjustment;
			if (ent->avelocity[n] > 0)
				ent->avelocity[n] = 0;
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
//	P_Physics_Step
//
//	Monsters freefall when they don't have a ground entity, otherwise
//	all movement is done with discrete steps.
//
//	This is also used for objects that have become still on the ground, but
//	will fall if the floor is pulled out from under them.
//	FIXME: is this true?
///////////////////////////////////////////////////////////////////////////////

void P_Physics_Step (edict_t *ent)
{
	qboolean	wasonground;
	qboolean	hitsound = false;
	float		*vel;
	float		speed, newspeed, control;
	float		friction;
	edict_t		*groundEntity;
	int			mask;

	// airborn monsters should always check for ground
	//	Nelno: removed temporarily
	if (!ent->groundEntity)
		P_CheckGround (ent);

	groundEntity = ent->groundEntity;

	P_CheckVelocity (ent);

	if (groundEntity)
		wasonground = true;
	else
		wasonground = false;
		
	if (ent->avelocity[0] || ent->avelocity[1] || ent->avelocity[2])
		P_AddRotationalFriction (ent);

	// add gravity except:
	//   flying monsters
	//   swimming monsters who are in the water
	if (! wasonground)
		if (ent->movetype == MOVETYPE_FLY && (ent->flags & FL_SWIM))
			if (!((ent->flags & FL_SWIM) && (ent->waterlevel > 2)))
			{
				if (ent->velocity[2] < p_gravity->value*-0.1)
					hitsound = true;
				if (ent->waterlevel == 0)
					P_AddGravity (ent);
			}

	//	Nelno:	why is this in here twice?
	//	friction for flying monsters that have been given vertical velocity
	if ((ent->movetype == MOVETYPE_FLY) && !(ent->flags & FL_SWIM) && (ent->velocity[2] != 0))
	{
		speed = fabs(ent->velocity[2]);
		control = speed < p_stopspeed ? p_stopspeed : speed;
		friction = p_friction/3;
		newspeed = speed - (p_frametime_scaled * control * friction);
		if (newspeed < 0)
			newspeed = 0;
		newspeed /= speed;
		ent->velocity[2] *= newspeed;
	}

	//	friction for swimming monsters that have been given vertical velocity
	if ((ent->flags & FL_SWIM) && (ent->velocity[2] != 0))
	{
		speed = fabs(ent->velocity[2]);
		control = speed < p_stopspeed ? p_stopspeed : speed;
		newspeed = speed - (p_frametime_scaled * control * p_waterfriction * ent->waterlevel);
		if (newspeed < 0)
			newspeed = 0;
		newspeed /= speed;
		ent->velocity[2] *= newspeed;
	}

	if (ent->velocity[2] || ent->velocity[1] || ent->velocity[0])
	{
		// apply friction
		// let dead monsters who aren't completely onground slide
		if ((wasonground) || (ent->movetype == MOVETYPE_FLY))
			if (!(ent->health <= 0.0 && !P_CheckBottom (ent)))
			{
				vel = ent->velocity;
				speed = sqrt(vel[0]*vel[0] +vel[1]*vel[1]);
				if (speed)
				{
					friction = p_friction;

					control = speed < p_stopspeed ? p_stopspeed : speed;
					newspeed = speed - p_frametime_scaled * control * friction;

					if (newspeed < 0)
						newspeed = 0;
					newspeed /= speed;

					vel[0] *= newspeed;
					vel[1] *= newspeed;
				}
			}

		if (ent->svflags & SVF_MONSTER)
			mask = MASK_MONSTERSOLID;
		else
			mask = MASK_SOLID;
		P_FlyMove (ent, p_frametime_scaled, mask);

		gi.linkentity (ent);
		P_TouchTriggers (ent);

		if (ent->groundEntity)
			if (!wasonground)
				if (hitsound)
					gi.sound (ent, 0, gi.soundindex("world/land.wav"), 1, 1, 0);
	}

// regular thinking
	if (ent->think) P_RunThink (ent, p_run_think);
}

/* --------------------------- MOVETYPE_WALK ------------------------------- */

///////////////////////////////////////////////////////////////////////////////
//	P_BotFriction
//
//	Nelno's routine to stop bots from sliding all over the damn place
//	
//	FIXME:	make so only bots with a flag set can walk off of ledges
//	Q2FIXME:make p_friction, p_stopspeed and cvars!
///////////////////////////////////////////////////////////////////////////////

void P_BotFriction (edict_t *ent)
{
	vec3_t	vel, origin;
	float	speed, newspeed, control;
	vec3_t	start, stop;
	float	friction;
	trace_t	trace;

	// if bot is in the air, don't apply friction!!!
	if (!ent->groundEntity)
		return;

	VectorCopy (ent->velocity, vel);
	VectorCopy (ent->s.origin, origin);
	
	//	get the speed in the xy plane
	speed = sqrt (vel [0] * vel [0] + vel [1] * vel [1]);
	
	if (!speed)
		return;

	//	if the leading edge is over a dropoff, increase friction
	//	start exactly at the bottom of ent's bounding box
	start [0] = stop [0] = origin [0];
	start [1] = stop [1] = origin [1];
	start [2] = origin[2];
	
	//	end 34 units below (stair height + 10, or jump height + 2)
	stop [2] = start [2] + ent->s.mins [2];

	trace = gi.trace (start, ent->s.mins, ent->s.maxs, stop, ent, CHOOSE_CLIP(ent));

	//	no friction if going up/down a slope
	if (trace.fraction < 1.0 && trace.plane.normal [2] < 1.0 && speed != 0)
			return;

	friction = p_friction * 2.0;

	// apply friction	
	control = speed < p_stopspeed ? p_stopspeed : speed;
	newspeed = speed - p_frametime_scaled * control * friction;
	
	if (newspeed < 0)
		newspeed = 0;
	
	newspeed /= speed;

	ent->velocity [0] = vel [0] * newspeed;
	ent->velocity [1] = vel [1] * newspeed;
	ent->velocity [2] = vel [2] * newspeed;
}

///////////////////////////////////////////////////////////////////////////////
//	P_BotWalkMove
//
//	monster/bot movement code
//	FIXME:	optimize this, only call this when monster is moving
///////////////////////////////////////////////////////////////////////////////

void P_BotWalkMove (edict_t *ent)
{
    vec3_t			upmove, downmove;
    vec3_t			oldorg, oldvel;
    vec3_t			nosteporg, nostepvel;
    int				clip, mask;
    trace_t			downtrace;

	///////////////////////////////////////////////////////////////////////////
	//	determine if there is ground right under our feet
	///////////////////////////////////////////////////////////////////////////

    VectorCopy (ent->s.origin, oldorg);
    VectorCopy (ent->velocity, oldvel);
    
	if (!ent->clipmask)
		mask = MASK_MONSTERSOLID;
	else
		mask = ent->clipmask;

    clip = P_FlyMove (ent, p_frametime_scaled, mask);

    if (!(clip & PHYS_BLOCKED_STEP))
		return;        // move didn't block on a step

	//	Q2FIXME:	this should work...
//    if (!oldonground && ent->waterlevel == 0)
//        return;        // don't stair up while jumping

    if (ent->flags & FL_WATERJUMP)
		//	jumping out of water
        return;

    VectorCopy (ent->s.origin, nosteporg);
    VectorCopy (ent->velocity, nostepvel);

//
// try moving up and forward to go up a step
//
	VectorCopy (oldorg, ent->s.origin);    // back to start pos

    VectorCopy (vec3_origin, upmove);
    VectorCopy (vec3_origin, downmove);
    
	upmove [2] = PHYS_STEPSIZE;
    downmove [2] = - PHYS_STEPSIZE + oldvel [2] * p_frametime_scaled;

	// move up
    P_PushEntity (ent, upmove);

	// move forward
    ent->velocity[0] = oldvel[0];
    ent->velocity[1] = oldvel[1];
    ent->velocity[2] = 0;
    
	clip = P_FlyMove (ent, p_frametime_scaled, mask);

	// move down
    downtrace = P_PushEntity (ent, downmove);

    if (downtrace.plane.normal [2] > 0.7)
    {
        if (ent->solid == SOLID_BSP || ent->solid == SOLID_BBOX)
		{
            ent->groundEntity = downtrace.ent;
			ent->groundSurface = downtrace.surface;
		}
    }
    else
    {
		//	if the push down didn't end up on good ground, use the move without
		//	the step up.  This happens near wall / slope combinations, and can
		//	cause the player to hop up higher on a slope too steep to climb    
        VectorCopy (nosteporg, ent->s.origin);
        VectorCopy (nostepvel, ent->velocity);
    }
}


///////////////////////////////////////////////////////////////////////////////
//	Physics_Walk
//
//	physics for MOVETYPE_WALK
//	FIXME:	add water detection here!!
///////////////////////////////////////////////////////////////////////////////

void	Physics_Walk (edict_t *ent)
{
	vec3_t	old_origin, move;
	trace_t	trace;

	VectorCopy (ent->s.origin, old_origin);

	P_GetWaterLevel (ent);

	if (!ent->groundEntity)
		P_AddGravity (ent);

	//	if ent is not moving in x/y plane, just account for up/down movement
	if (ent->velocity [0] == 0 && ent->velocity [1] == 0 && !ent->groundEntity)
	{
		if (ent->velocity [2] != 0)
		{
			//	entity is falling, so determine if it will hit the floor in
			//	this frame
			VectorScale (ent->velocity, p_frametime_scaled, move);
			trace = P_PushEntity (ent, move);

			if (trace.allsolid || trace.startsolid)
			{
				if (trace.ent && trace.ent->className && ent->className)
				{
					//gi.conprintf ("Physics_Walk: %s is stuck inside of %s!\n", ent->className, trace.ent->className);
				}
			}

			if (trace.fraction < 1.0)
			{
				if (ent->velocity [2] < 0)
				{
					//	if falling, entity must have just hit the ground
					ent->groundEntity = trace.ent;
					ent->groundSurface = trace.surface;
					ent->groundEntity_linkcount = trace.ent->linkcount;
				}

				ent->velocity[2] = 0;
			}
		}
	}
	else
	{
		P_BotWalkMove (ent);
		P_BotFriction (ent);

		gi.linkentity (ent);
	}

	P_CheckGround (ent);

	//	run think function
	if (ent->think) P_RunThink (ent, p_run_think);
}

///////////////////////////////////////////////////////////////////////////////
//	P_RunEntity
//
//	Nelno:	similar to P_Physics in Quake 1 source
///////////////////////////////////////////////////////////////////////////////

void P_RunEntity (edict_t *ent, int run_think)
{
	p_run_think = run_think;

	switch (ent->movetype)
	{
		case	MOVETYPE_PUSH:
		case	MOVETYPE_STOP:
				P_Physics_Pusher (ent);
				break;

		case	MOVETYPE_NONE:
				P_Physics_None (ent);
				break;

		case	MOVETYPE_NOCLIP:
				P_Physics_Noclip (ent);
				break;

		case	MOVETYPE_STEP:
				P_Physics_Step (ent);
				break;

		case	MOVETYPE_TOSS:
		case	MOVETYPE_BOUNCE:
		case	MOVETYPE_FLY:
		case	MOVETYPE_FLYMISSILE:
		case	MOVETYPE_BOUNCEMISSILE:
				P_Physics_Toss (ent);
				break;

		case	MOVETYPE_FLOAT:
				P_Physics_Float (ent);
				break;

		case	MOVETYPE_WALK:
				Physics_Walk (ent);
				break;
		
		default:
				gi.error ("P_RunEntity: bad movetype %i", (int)ent->movetype);			
	}
}
