
local meta = FindMetaTable( "Player" );

PlayerRagdolls = { }

function meta:CallEvent( name )

	umsg.Start( "_" .. name, self ); umsg.End();

end

function meta:BaseInitialize()

	self:GetTable().Vars = { }

	for k, v in pairs( PlayerVars ) do
	
		self:GetTable().Vars[k] = v;
	
	end

end

function meta:Initialize()

	

end

function meta:MakeInvisible( b )

	if( b == nil ) then
		b = true;
	end

	self:SetNotSolid( b );
	self:SetNoDraw( b );
	self:DrawViewModel( !b );
	
	if( self:GetActiveWeapon():IsValid() ) then
		self:GetActiveWeapon():SetNoDraw( b );
	end

end

function meta:MakeNotInvisible()

	self:MakeInvisible( false );

end

function meta:RagdollPlayer()

	if( self:GetTable().IsRagdolled ) then
		return;
	end

	local ragdoll = ents.Create( "prop_ragdoll" );
	
	ragdoll:SetPos( self:GetPos() );
	ragdoll:SetAngles( self:GetAngles() );
	ragdoll:SetModel( self:GetModel() );
	ragdoll:SetOwner( self );
	
	ragdoll:Spawn();
	
	local c = ragdoll:GetPhysicsObjectCount();
	
	local vel = self:GetVelocity();
	
	for n = 1, c do
		
		local bone = ragdoll:GetPhysicsObjectNum( n );
		
		if( bone and bone:IsValid() ) then
		
			local bonepos, boneang = self:GetBonePosition( ragdoll:TranslatePhysBoneToBone(n) );
			
			bone:SetPos( bonepos );
			bone:SetAngle( boneang );
			bone:AddVelocity( vel );
			
		end
		
	end

	self:MakeInvisible();
	
	self:Freeze( true );
	
	self:GetTable().IsRagdolled = true;
	self:GetTable().RagdollEntity = ragdoll;
	ragdoll:GetTable().IsPlayerRagdoll = true;
	ragdoll:GetTable().Player = self;
	
	table.insert( PlayerRagdolls, ragdoll );
	
	return ragdoll;
	
end

function meta:UnragdollPlayer()

	self:GetTable().IsRagdolled = false;

	self:MakeNotInvisible();
	self:Freeze( false );
	self:CrosshairDisable();

	local spawnpos;

	if( self:GetTable().RagdollEntity and self:GetTable().RagdollEntity:IsValid() ) then
	
		if( self:Health() > 0 ) then
			spawnpos = self:GetTable().RagdollEntity:GetPos();
			self:RemoveRagdoll();
		end
		
	end
	
	if( self:Health() > 0 ) then
	
		self:Spawn();

		if( spawnpos ) then
		
			self:SetPos( spawnpos );
		
		end

	end

end

function meta:RemoveRagdoll()

	if( self:GetTable().RagdollEntity and self:GetTable().RagdollEntity:IsValid() ) then
		
		self:GetTable().RagdollEntity:Remove();
		self:GetTable().RagdollEntity = nil;

	end

end
