#include <amxmodx>
#include <amxmisc>
#include <engine>
#include <fun>
#include <cstrike>
#include <fakemeta>
#include <hamsandwich>
#include <xs>
#include <colorchat>
#include <zombieplague>

native zp_cs_get_user_money(id)
native zp_cs_set_user_money(id, num)


#define A_ADMIN  ADMIN_USER	// флаг l


#if AMXX_VERSION_NUM < 183
	#define message_begin_f(%0,%1,%2,%3)	engfunc(EngFunc_MessageBegin,%0,%1,%2,%3)
	#define write_coord_f(%0)		engfunc(EngFunc_WriteCoord,%0)
	
	#include <dhudmessage>
	
#endif
	

#define is_valid_player(%1) ( 1 <= %1 <= g_iMaxPlayers )
#define is_valid_team(%1) ( 0 < %1 < 3 )

#define is_entity_on_ground(%1) ( entity_get_int ( %1, EV_INT_flags ) & FL_ONGROUND )

#define is_team(%1,%2)		(bool:(get_user_team(%1) == %2))

// сколько пушек у игрока уже построено
#define GetSentryCount(%1) g_iPlayerSentries[%1]


#define MAXUPGRADERANGE			75.0
#define SENTRYEXPLODERADIUS		50.0			// радиус отброса при взрыве
#define SENTRYTILTRADIUS		830.0			// likely you won't need to touch this. it's how accurate the cannon will aim at the target vertically (up/down, just for looks, aim is calculated differently)

#define SENTRYMINDISTANCE		256.0

#define MAXSENTRIES				32 * 10

#define TASK_GODMODE 114455

#define FREEZ_TASK_ID 9865 //Для верной работы таска заморозки
#define FREEZ_ENT_TIME EV_FL_teleport_time

#define SENTRY_INT_PEOPLE		 EV_INT_iuser2 // max 5 users using 6 bits!
#define SENTRY_INT_UGPRADERS	 EV_INT_iuser3
#define SENTRY_PEOPLE_BITS		6
#define OWNER					0
#define UPGRADER_1				1
#define UPGRADER_2				2
#define TARGET					3
#define UPGRADER_3				4
#define UPGRADER_				4
#define MASK_OWNER				0xFFFFFFC0 // 11111111111111111111111111000000
#define MASK_UPGRADER_1			0xFFFFF03F // 11111111111111111111000000111111
#define MASK_UPGRADER_2			0xFFFC0FFF // 11111111111111000000111111111111
#define MASK_TARGET				0xFF03FFFF // 11111111000000111111111111111111
#define MASK_UPGRADER_3			0xC0FFFFFF // 11000000111111111111111111111111
new const MASKS_PEOPLE[5] = {MASK_OWNER, MASK_UPGRADER_1, MASK_UPGRADER_2, MASK_TARGET, MASK_UPGRADER_3}

GetSentryPeople(const SENTRY, const WHO) {
	new data = entity_get_int(SENTRY, SENTRY_INT_PEOPLE)
	data |= MASKS_PEOPLE[WHO]
	data ^= MASKS_PEOPLE[WHO]
	data = (data>>(WHO*SENTRY_PEOPLE_BITS))
	return data
}
SetSentryPeople(const SENTRY, const WHO, const IS) {
	new data = entity_get_int(SENTRY, SENTRY_INT_PEOPLE)
	data &= MASKS_PEOPLE[WHO] // nullify the setting
	data |= (IS<<(WHO*SENTRY_PEOPLE_BITS)) // set the setting
	entity_set_int(SENTRY, SENTRY_INT_PEOPLE, data) // store
}

#define SENTRY_FREEZ_TIME		EV_FL_scale
#define SENTRY_INT_SETTINGS		EV_INT_iuser1
#define SENTRY_ROCKET_TIME		EV_FL_teleport_time
#define SENTRY_SETTINGS_BITS	2
#define SENTRY_SETTING_FIREMODE	0
#define SENTRY_SETTING_TEAM		1
#define SENTRY_SETTING_LEVEL	2
#define SENTRY_SETTING_PENDDIR	3
#define MASK_FIREMODE			0xFFFFFFFC // 11111111111111111111111111111100 = FFFFFFFC
#define MASK_TEAM				0xFFFFFFF3 // 11111111111111111111111111110011 = FFFFFFF3
#define MASK_LEVEL				0xFFFFFFCF // 11111111111111111111111111001111 = FFFFFFCF
#define MASK_PENDDIR			0xFFFFFF3F // 11111111111111111111111100111111 = FFFFFF3F
new const MASKS_SETTINGS[4] = {MASK_FIREMODE, MASK_TEAM, MASK_LEVEL, MASK_PENDDIR}

GetSentrySettings(const SENTRY, const SETTING) {
	new data = entity_get_int(SENTRY, SENTRY_INT_SETTINGS)
	data |= MASKS_SETTINGS[SETTING]
	data ^= MASKS_SETTINGS[SETTING]
	//data = (data>>(SETTING*SENTRY_SETTINGS_BITS))
	return (data>>(SETTING*SENTRY_SETTINGS_BITS))
}
SetSentrySettings(const SENTRY, const SETTING, const VALUE) {
	new data = entity_get_int(SENTRY, SENTRY_INT_SETTINGS)
	data &= MASKS_SETTINGS[SETTING] // nullify the setting
	//data |= (VALUE<<(SETTING*SENTRY_SETTINGS_BITS)) // set the setting
	entity_set_int(SENTRY, SENTRY_INT_SETTINGS, data | (VALUE<<(SETTING*SENTRY_SETTINGS_BITS))) // store
}

GetSentryFiremode(const SENTRY) {
	return GetSentrySettings(SENTRY, SENTRY_SETTING_FIREMODE)
}
SetSentryFiremode(const SENTRY, const MODE) {
	SetSentrySettings(SENTRY, SENTRY_SETTING_FIREMODE, MODE)
}
CsTeams:GetSentryTeam(const SENTRY) {
	return CsTeams:GetSentrySettings(SENTRY, SENTRY_SETTING_TEAM)
}
SetSentryTeam(const SENTRY, const CsTeams:TEAM) {
	SetSentrySettings(SENTRY, SENTRY_SETTING_TEAM, int:TEAM)
}
GetSentryLevel(const SENTRY) {
	return GetSentrySettings(SENTRY, SENTRY_SETTING_LEVEL)
}
SetSentryLevel(const SENTRY, const LEVEL) {
	SetSentrySettings(SENTRY, SENTRY_SETTING_LEVEL, LEVEL)
}
GetSentryPenddir(const SENTRY) {
	return GetSentrySettings(SENTRY, SENTRY_SETTING_PENDDIR)
}
SetSentryPenddir(const SENTRY, const PENDDIR) {
	SetSentrySettings(SENTRY, SENTRY_SETTING_PENDDIR, PENDDIR)
}

#define DATA_CUBE_OWNER			EV_INT_iuser1
#define SENTRY_ENT_BASE			EV_ENT_euser1

#define SENTRY_FL_ANGLE			EV_FL_fuser1
#define SENTRY_FL_SPINSPEED		EV_FL_fuser2
#define SENTRY_FL_MAXSPIN		EV_FL_fuser3
#define SENTRY_FL_LASTTHINK		EV_FL_fuser4

#define SENTRY_DIR_CANNON		0

#define BASE_ENT_SENTRY			EV_ENT_euser1
#define BASE_INT_TEAM			EV_INT_iuser1

#define SENTRY_LEVEL_1			0
#define SENTRY_LEVEL_2			1
#define SENTRY_LEVEL_3			2
#define SENTRY_LEVEL_4			3
#define SENTRY_FIREMODE_NO		0
#define SENTRY_FIREMODE_YES		1
#define SENTRY_FIREMODE_NUTS	2
#define DMG_BULLET				(1<<1)	//выстрел
#define DMG_BLAST				(1<<6)	// explosive blast damage
#define TE_EXPLFLAG_NONE		0
#define TE_EXPLOSION			3
#define TE_TRACER				6
#define TE_BREAKMODEL			108
#define PENDULUM_MAX			45.0 // how far sentry turret turns in each direction when idle, before turning back
#define PENDULUM_INCREMENT		10.0 // speed of turret turning...
#define SENTRYSHOCKPOWER		3.0 // multiplier, increase to make exploding sentries throw stuff further away
#define CANNONHEIGHTFROMFEET	20.0 // tweakable to make tracer originate from the same height as the sentry's cannon. Also traces rely on this Y-wise offset.
#define PLAYERORIGINHEIGHT		36.0 // this is the distance from a player's EV_VEC_origin to ground, if standing up
#define HEIGHTDIFFERENCEALLOWED	200.0 // increase value to allow building in slopes with higher angles. You can set to 0.0 and you will only be able to build on exact flat ground. note: mostly applies to downhill building, uphill is still likely to "collide" with ground...

#define PLACE_RANGE				45.0

#define SENTRY_RADAR			20 // use as high as possible but should still be working (ie be able to see sentries plotted on radar while in menu, too high values doesn't seem to work)
#define SENTRY_RADAR_TEAMBUILT	21 // same as above


#define TASK_LEAVE_ID 10100
#define TASK_CHECK_ACCU 0.30
#define TASK_CHECK_ACCU 0.30

new cvar_base_model
new Model_base[90]

new cvar_model_1T, cvar_model_2T, cvar_model_3T, cvar_model_4T
new cvar_model_1CT, cvar_model_2CT, cvar_model_3CT, cvar_model_4CT
new cvar_model_1T_VIP, cvar_model_2T_VIP, cvar_model_3T_VIP, cvar_model_4T_VIP
new cvar_model_1CT_VIP, cvar_model_2CT_VIP, cvar_model_3CT_VIP, cvar_model_4CT_VIP

new Model_SentryT_1[90], Model_SentryT_2[90], Model_SentryT_3[90], Model_SentryT_4[90]
new Model_SentryCT_1[90], Model_SentryCT_2[90], Model_SentryCT_3[90], Model_SentryCT_4[90]
new Model_SentryT_1_VIP[90], Model_SentryT_2_VIP[90], Model_SentryT_3_VIP[90], Model_SentryT_4_VIP[90]
new Model_SentryCT_1_VIP[90], Model_SentryCT_2_VIP[90], Model_SentryCT_3_VIP[90], Model_SentryCT_4_VIP[90]

#define Model_Rocket "models/NewSentry_VIP/rpgrocket.mdl"

#define FROZEN_CUBE "models/NewSentry_VIP/icecube.mdl"

#define Model_Computergibs "models/computergibs.mdl"




#define Sound_rocet_1 "nova/sentry/fire_charge_1.wav"
#define Sound_rocet_2 "nova/sentry/nuke_fly.wav"
#define Sound_rocet_3 "nova/sentry/rocket_explosion.wav"

#define Sound_tok "nova/sentry/tok.wav"
#define Sound_tok_2 "nova/sentry/tok2.wav"

#define Sound_ignor "nova/sentry/ignor.wav"


#define Sprite_tok "sprites/nova/tok.spr"

#define Sprite_Sentry_1 "sprites/nova/spr_6.spr"
#define Sprite_Sentry_2 "sprites/nova/spr_12.spr"
#define Sprite_Sentry_3 "sprites/nova/spr_10.spr"

#define Sprite_Chastic "sprites/nova/spr_2.spr"


#define Sprite_up "sprites/nova/upgrade.spr"
#define Sprite_trall "sprites/zerogxplode.spr"
#define Sprite_moroz "sprites/nova/moroz.spr"

#define	Sound_fire "dmsentries/fire.wav"



new const gDispenserDestroy[ ] = "grab_bury.wav";

new const szSounds[][] =
{
	"debris/bustmetal1.wav",
	"debris/bustmetal2.wav",
	"debris/metal1.wav",
	"debris/metal3.wav",
	"dmsentries/turridle.wav",
	"dmsentries/turrset.wav",
	"dmsentries/turrspot.wav",
	"CSSB/sentry_gun/build_1.wav",
	"weapons/rocket1.wav"
}

new g_SentryId[33];
#define SENTRYOWNERAWARD	300
#define SENTRYASSISTAWARD	150

new const g_DMG[4] = {3, 5, 8, 10}								// Урон на 1,2,3,4.
new const Float:g_THINKFREQUENCIES[4] = {1.5, 1.0, 0.5, 0.25}		// через сколько захватывается цель	
#define g_sentriesNum (g_teamsentriesNum[0]+g_teamsentriesNum[1])
new g_teamsentriesNum[2]	
new g_sentries[MAXSENTRIES]
new g_iPlayerSentries[33]
new g_iPlayerSentriesEdicts[33][10]
new g_sModelIndexFireball
new g_sModelIndexFireball2
new g_sModelIndexMoroz
new g_msgDamage
new g_msgDeathMsg
new g_msgScoreInfo
new g_msgHostagePos
new g_msgHostageK
new g_iMaxPlayers
new Float:g_ONEEIGHTYTHROUGHPI
new Float:g_sentryOrigins[32][3]
new bool:g_inBuilding[33]
new sentries_num[33]
new gMsgID
new g_iSPR_Smoke3;



new g_OffSpam[33];
new g_iKillSentry[500];

new g_OwnName[33];
new g_OwnId
new g_StatsKill[33];

new higher_score;
new g_MsgSync;
new keys = MENU_KEY_1|MENU_KEY_2|MENU_KEY_3|MENU_KEY_4|MENU_KEY_5|MENU_KEY_6|MENU_KEY_7|MENU_KEY_8|MENU_KEY_9;

new Float:g_fTime[33]



new g_SentryMode[300]

new g_Sprite_sentry_1
new g_Sprite_sentry_2
new g_Sprite_sentry_3
new g_Sprite_sentry_up

new g_Chastic

new g_iCvar[8]
new g_Flag


new g_Cvar_nograda, g_Cvar_uron[7], g_Cvar_remont[3], g_Cvar_sentry_destone[4],g_Cvar_nagryzka[2]
new g_Cvar_mode_cost[4], g_Cvar_mode_aktiv[4], g_Cvar_mode_rpg[3], g_Cvar_mode_led[2]
new g_Cvar_up[2], g_Cvar_max_sg[2]

new g_bar_time
new Float:g_HEALTHS[4]
new g_SENTRYCOST[10]


new pust
new g_sentry_team
new cvar_sg_cost[10], cvar_hp_sentry[4]
new is_sentry_ammo
new byild_zaraza
new is_mod_zp
public plugin_init() 
{
	register_plugin("Sentry guns", "3.0", "forgame.su");
	
	register_dictionary("nv_sentru_gun.txt");
	
	register_clcmd("sentry_build", "cmd_CreateSentry", 0, "- build a sentry gun where you are");
	register_clcmd("say /sgstats", "sgstats", 0, "- stats sentry");
	
	
	RegisterHam ( Ham_Spawn, "player", "fw_PlayerSpawn_Post", 1 );
	RegisterHam ( Ham_TakeDamage, "func_breakable", "fw_TakeDamage" )
	
	register_forward(FM_CmdStart,"fm_cmdstart");
	
	register_menu("Menu",keys , "MenuFunc");
	
	register_touch ("sentry", "player", "fw_TouchSentry" );
	register_touch ("rpg_rocket", "*","fw_RpgTouch");
	register_forward ( FM_TraceLine, "fw_TraceLine_Post", 1 )
	
	register_message ( 23, "msg_TempEntity" );
	
	register_think ("sentrybase", "think_sentrybase");
	register_think ( "sentry", "fw_ThinkSentry" );
	
	register_event("Spectator", "ev_Spectation", "a");
	register_event("TextMsg", "EventGameRestart", "a", "2&#Game_will_restart_in");
	register_event("TextMsg", "EventGameRestart", "a", "2&#Game_C");
	register_event("DeathMsg", "onDeath", "a") 
	

	g_msgDamage = get_user_msgid("Damage")
	g_msgDeathMsg = get_user_msgid("DeathMsg")
	g_msgScoreInfo = get_user_msgid("ScoreInfo")
	g_msgHostagePos = get_user_msgid("HostagePos")
	g_msgHostageK = get_user_msgid("HostageK")
	gMsgID = get_user_msgid("StatusIcon")
	g_bar_time = get_user_msgid("BarTime2")
	
	g_iMaxPlayers = get_global_int(GL_maxClients)
	g_ONEEIGHTYTHROUGHPI = 180.0 / 3.141592654
	
	g_MsgSync = CreateHudSyncObj()

	register_logevent("RoundStart", 2, "1=Round_Start")
	
	g_Flag = register_cvar("nv_admin_flag", "a")	//флаг админа
	g_iCvar[0]=register_cvar("nv_remont_max","4000.0")	//до скольки хп можно лечить
	g_Cvar_remont[0]=register_cvar("nv_remont_cost","1")
	g_Cvar_remont[1]=register_cvar("nv_remont_speed","25.0")
	g_Cvar_remont[2]=register_cvar("nv_remont_on","1")
	g_Cvar_nograda = register_cvar("nv_up_cost","200")
	g_Cvar_uron[0] = register_cvar("nv_uron_1","1")
	g_Cvar_uron[1] = register_cvar("nv_uron_2","2")
	g_Cvar_uron[2] = register_cvar("nv_uron_3","3")
	g_Cvar_uron[3] = register_cvar("nv_uron_4","4")
	g_Cvar_uron[4] = register_cvar("nv_uron_castiz","3")
	g_Cvar_uron[5] = register_cvar("nv_uron_razbros","30")
	g_Cvar_uron[6] = register_cvar("nv_hp_smoke","1000.0")
	g_Cvar_sentry_destone[0] = register_cvar("nv_sentry_destone_1","1000")
	g_Cvar_sentry_destone[1] = register_cvar("nv_sentry_destone_2","2000")
	g_Cvar_sentry_destone[2] = register_cvar("nv_sentry_destone_3","3000")
	g_Cvar_sentry_destone[3] = register_cvar("nv_sentry_destone_4","4000")   
	g_Cvar_nagryzka[0] = register_cvar("nv_obnow_lider","1.0")
	g_Cvar_nagryzka[1] = register_cvar("nv_info_sentry","180.0")
	g_Cvar_mode_cost[0] = register_cvar("nv_mode_cost_1","10000") 
	g_Cvar_mode_cost[1] = register_cvar("nv_mode_cost_2","5000") 
	g_Cvar_mode_cost[2] = register_cvar("nv_mode_cost_3","7000") 
	g_Cvar_mode_aktiv[0] = register_cvar("nv_mode_1_on","1") 
	g_Cvar_mode_aktiv[1] = register_cvar("nv_mode_2_on","1") 
	g_Cvar_mode_aktiv[2] = register_cvar("nv_mode_3_on","1")  
	g_Cvar_mode_led[0] =  register_cvar("nv_led_stop","3.0")
	g_Cvar_mode_led[1] =  register_cvar("nv_led_vreme","2.0")
	g_Cvar_mode_rpg[0] = register_cvar("nv_rpg_radius","250.0")
	g_Cvar_mode_rpg[1] = register_cvar("nv_rpg_damage","150.0")
	g_Cvar_mode_rpg[2] = register_cvar("nv_rpg_distanze","400.0")
	g_Cvar_up[0] = register_cvar("nv_sg_up_2","300")
	g_Cvar_up[1] = register_cvar("nv_sg_up_3","3000")
	g_Cvar_max_sg[0] = register_cvar("nv_maxsentry_vip","3")
	g_Cvar_max_sg[1] = register_cvar("nv_maxsentry_player","2")
	
	cvar_hp_sentry[0] = register_cvar("nv_sg_hp_1","3000.0")
	cvar_hp_sentry[1] = register_cvar("nv_sg_hp_2","4000.0")
	cvar_hp_sentry[2] = register_cvar("nv_sg_hp_3","6000.0")
	cvar_hp_sentry[3] = register_cvar("nv_sg_hp_4","8000.0")
	
	cvar_sg_cost[0] = register_cvar("nv_sg_1","3000")
	cvar_sg_cost[1] = register_cvar("nv_sg_2","3500")
	cvar_sg_cost[2] = register_cvar("nv_sg_3","4000")
	cvar_sg_cost[3] = register_cvar("nv_sg_4","4500")
	cvar_sg_cost[4] = register_cvar("nv_sg_5","5000")
	cvar_sg_cost[5] = register_cvar("nv_sg_6","5500")
	cvar_sg_cost[6] = register_cvar("nv_sg_7","6000")
	cvar_sg_cost[7] = register_cvar("nv_sg_8","6500")
	cvar_sg_cost[8] = register_cvar("nv_sg_9","7000")
	cvar_sg_cost[9] = register_cvar("nv_sg_10","7500")
	
	is_sentry_ammo = register_cvar("nv_sentry_ammo","0")
	g_sentry_team = register_cvar("nv_sentry_team","0")
	byild_zaraza = register_cvar("nv_sentry_zp","0")
	is_mod_zp = register_cvar("nv_is_mod_zp","0")
	register_clcmd("basa_connect", "MYSQL_Load")
	register_clcmd("basa_zapros", "InsertData")
	set_task(2.0, "MYSQL_Load")
	
	set_task(0.09,"sprite_sentry",1345,_,_,"b")
}

public plugin_cfg()
{
	g_SENTRYCOST[0] = get_pcvar_num(cvar_sg_cost[0])
	g_SENTRYCOST[1] = get_pcvar_num(cvar_sg_cost[1])
	g_SENTRYCOST[2] = get_pcvar_num(cvar_sg_cost[2])
	g_SENTRYCOST[3] = get_pcvar_num(cvar_sg_cost[3])
	g_SENTRYCOST[4] = get_pcvar_num(cvar_sg_cost[4])
	g_SENTRYCOST[5] = get_pcvar_num(cvar_sg_cost[5])
	g_SENTRYCOST[6] = get_pcvar_num(cvar_sg_cost[6])
	g_SENTRYCOST[7] = get_pcvar_num(cvar_sg_cost[7])
	g_SENTRYCOST[8] = get_pcvar_num(cvar_sg_cost[8])
	g_SENTRYCOST[9] = get_pcvar_num(cvar_sg_cost[9])
	
	g_HEALTHS[0] = get_pcvar_float(cvar_hp_sentry[0])
	g_HEALTHS[1] = get_pcvar_float(cvar_hp_sentry[1])
	g_HEALTHS[2] = get_pcvar_float(cvar_hp_sentry[2])
	g_HEALTHS[3] = get_pcvar_float(cvar_hp_sentry[3])
	
	new configsdir[128]
	get_localinfo("amxx_configsdir", configsdir, 127)
	server_cmd("exec %s/nova/sentry.cfg", configsdir)
	server_exec()
}

new Float:g_sprite_tok[500]

public sprite_sentry()
{
	new ent
	while((ent = find_ent_by_class(ent,"sentry")) != 0){
		if(pev(ent, pev_euser3) == 1) continue
		new Float:fOriginSentry[3]
		entity_get_vector ( ent, EV_VEC_origin, fOriginSentry )
		fOriginSentry[2] += CANNONHEIGHTFROMFEET
		
		if(GetSentryLevel(ent) < 2){
			prite_zona_UP(fOriginSentry)
		}
		
		if(GetSentryLevel(ent) == 3){
			if(g_SentryMode[ent] == 3){
				prite_zona_3(fOriginSentry)
			}else if(g_SentryMode[ent] == 2){
				
				if(g_sprite_tok[ent] < get_gametime()){
					prite_zona_2(fOriginSentry)
					g_sprite_tok[ent] = get_gametime() + 0.3
				}
			}else if(g_SentryMode[ent] == 1){
				prite_zona_1(fOriginSentry)
			}
		}
	}
}


public RoundStart()
{
	remove_task(1)
	remove_task(2)
	
	set_task ( get_pcvar_float(g_Cvar_nagryzka[0]), "show_BestPlayer", 1, _, _, "b" )
	set_task ( get_pcvar_float(g_Cvar_nagryzka[1]), "sgstats", 2, _, _, "b" )
}

public zp_round_ended(win_team)
{
	for(new id = 1; id <= get_maxplayers(); id++) 
	{
		if(is_user_connected(id))
		{
			if ( !is_user_alive ( id ) )
				return

			g_inBuilding[id] = false

			while ( GetSentryCount ( id ) > 0 )
				sentry_detonate_by_owner ( id, true )

			ammo_hud ( id, 0 )
			sentries_num[id] = 0
		}
	}
}




public plugin_precache() {
	cvar_base_model = 0
	cvar_model_1T = 0
	cvar_model_2T = 0
	cvar_model_3T = 0
	cvar_model_4T = 0
	cvar_model_1CT = 0
	cvar_model_2CT = 0
	cvar_model_3CT = 0
	cvar_model_4CT = 0   
	cvar_model_1T_VIP = 0
	cvar_model_2T_VIP = 0
	cvar_model_3T_VIP = 0
	cvar_model_4T_VIP = 0	
	cvar_model_1CT_VIP = 0
	cvar_model_2CT_VIP = 0
	cvar_model_3CT_VIP = 0
	cvar_model_4CT_VIP = 0
	
	new iFile = fopen("addons/amxmodx/configs/nova/sentry.cfg", "rt");
	if(iFile){
		new szLineBuffer[600]
		while(!(feof(iFile))){
			fgets(iFile, szLineBuffer, charsmax(szLineBuffer));
				
			if(!(szLineBuffer[0]) || szLineBuffer[0] == ';' || szLineBuffer[0] == '#')
			{
				continue;
			}
			new Imeil[600]
			new Model[600]
			
			parse(szLineBuffer, Imeil, charsmax(Imeil),Model, charsmax(Model));
			
			if(equal(Imeil, "mdl_base")){	
				cvar_base_model = 1
				formatex(Model_base, charsmax(Model_base), "%s", Model);
			} if(equal(Imeil, "mdl_sg_1_t")){	
				cvar_model_1T = 1
				formatex(Model_SentryT_1, charsmax(Model_SentryT_1), "%s", Model);
			} if(equal(Imeil, "mdl_sg_2_t")){	
				cvar_model_2T = 1
				formatex(Model_SentryT_2, charsmax(Model_SentryT_2), "%s", Model);
			} if(equal(Imeil, "mdl_sg_3_t")){	
				cvar_model_3T = 1
				formatex(Model_SentryT_3, charsmax(Model_SentryT_3), "%s", Model);
			} if(equal(Imeil, "mdl_sg_4_t")){	
				cvar_model_4T = 1
				formatex(Model_SentryT_4, charsmax(Model_SentryT_4), "%s", Model);
			} if(equal(Imeil, "mdl_sg_1_ct")){	
				cvar_model_1CT = 1
				formatex(Model_SentryCT_1, charsmax(Model_SentryCT_1), "%s", Model);
			} if(equal(Imeil, "mdl_sg_2_ct")){	
				cvar_model_2CT = 1
				formatex(Model_SentryCT_2, charsmax(Model_SentryCT_2), "%s", Model);
			} if(equal(Imeil, "mdl_sg_3_ct")){	
				cvar_model_3CT = 1
				formatex(Model_SentryCT_3, charsmax(Model_SentryCT_3), "%s", Model);
			} if(equal(Imeil, "mdl_sg_4_ct")){	
				cvar_model_4CT = 1
				formatex(Model_SentryCT_4, charsmax(Model_SentryCT_4), "%s", Model);
			} if(equal(Imeil, "mdl_sg_1_t_vip")){	
				cvar_model_1T_VIP = 1
				formatex(Model_SentryT_1_VIP, charsmax(Model_SentryT_1_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_2_t_vip")){	
				cvar_model_2T_VIP = 1
				formatex(Model_SentryT_2_VIP, charsmax(Model_SentryT_2_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_3_t_vip")){	
				cvar_model_3T_VIP = 1
				formatex(Model_SentryT_3_VIP, charsmax(Model_SentryT_3_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_4_t_vip")){	
				cvar_model_4T_VIP = 1
				formatex(Model_SentryT_4_VIP, charsmax(Model_SentryT_4_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_1_ct_vip")){	
				cvar_model_1CT_VIP = 1
				formatex(Model_SentryCT_1_VIP, charsmax(Model_SentryCT_1_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_2_ct_vip")){	
				cvar_model_2CT_VIP = 1
				formatex(Model_SentryCT_2_VIP, charsmax(Model_SentryCT_2_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_3_ct_vip")){	
				cvar_model_3CT_VIP = 1
				formatex(Model_SentryCT_3_VIP, charsmax(Model_SentryCT_3_VIP), "%s", Model);
			} if(equal(Imeil, "mdl_sg_4_ct_vip")){	
				cvar_model_4CT_VIP = 1
				formatex(Model_SentryCT_4_VIP, charsmax(Model_SentryCT_4_VIP), "%s", Model);
			}
		}
	}
	fclose(iFile)
	
	if(cvar_base_model == 0){
		formatex(Model_base, charsmax(Model_base), "models/NewSentry_VIP/base.mdl");
	} if(cvar_model_1T == 0){
		formatex(Model_SentryT_1, charsmax(Model_SentryT_1), "models/NewSentry_VIP/lvl_01_VIP_te.mdl");
	} if(cvar_model_2T == 0){
		formatex(Model_SentryT_2, charsmax(Model_SentryT_2), "models/NewSentry_VIP/lvl_02_VIP_te.mdl");
	} if(cvar_model_3T == 0){
		formatex(Model_SentryT_3, charsmax(Model_SentryT_3), "models/NewSentry_VIP/lvl_03_VIP_te.mdl");
	} if(cvar_model_4T == 0){
		formatex(Model_SentryT_4, charsmax(Model_SentryT_4), "models/NewSentry_VIP/lvl_04_VIP_te.mdl");
	} if(cvar_model_1CT == 0){
		formatex(Model_SentryCT_1, charsmax(Model_SentryCT_1), "models/NewSentry_VIP/lvl_01_VIP_ct.mdl");
	} if(cvar_model_2CT == 0){
		formatex(Model_SentryCT_2, charsmax(Model_SentryCT_2), "models/NewSentry_VIP/lvl_02_VIP_ct.mdl");
	} if(cvar_model_3CT == 0){
		formatex(Model_SentryCT_3, charsmax(Model_SentryCT_3), "models/NewSentry_VIP/lvl_03_VIP_ct.mdl");
	} if(cvar_model_4CT == 0){
		formatex(Model_SentryCT_4, charsmax(Model_SentryCT_4), "models/NewSentry_VIP/lvl_04_VIP_ct.mdl");
	} if(cvar_model_1T_VIP == 0){
		formatex(Model_SentryT_1_VIP, charsmax(Model_SentryT_1_VIP), "models/NewSentry_VIP/lvl_01_VIP_te.mdl");
	} if(cvar_model_2T_VIP == 0){
		formatex(Model_SentryT_2_VIP, charsmax(Model_SentryT_2_VIP), "models/NewSentry_VIP/lvl_02_VIP_te.mdl");
	} if(cvar_model_3T_VIP == 0){
		formatex(Model_SentryT_3_VIP, charsmax(Model_SentryT_3_VIP), "models/NewSentry_VIP/lvl_03_VIP_te.mdl");
	} if(cvar_model_4T_VIP == 0){
		formatex(Model_SentryT_4_VIP, charsmax(Model_SentryT_4_VIP), "models/NewSentry_VIP/lvl_04_VIP_te.mdl");
	} if(cvar_model_1CT_VIP == 0){
		formatex(Model_SentryCT_1_VIP, charsmax(Model_SentryCT_1_VIP), "models/NewSentry_VIP/lvl_01_VIP_ct.mdl");
	} if(cvar_model_2CT_VIP == 0){
		formatex(Model_SentryCT_2_VIP, charsmax(Model_SentryCT_2_VIP), "models/NewSentry_VIP/lvl_02_VIP_ct.mdl");
	} if(cvar_model_3CT_VIP == 0){
		formatex(Model_SentryCT_3_VIP, charsmax(Model_SentryCT_3_VIP), "models/NewSentry_VIP/lvl_03_VIP_ct.mdl");
	} if(cvar_model_4CT_VIP == 0){
		formatex(Model_SentryCT_4_VIP, charsmax(Model_SentryCT_4_VIP), "models/NewSentry_VIP/lvl_04_VIP_ct.mdl");
	}
	
	precache_model(Model_base)
	precache_model(Model_SentryT_1) 
	precache_model(Model_SentryT_2) 
	precache_model(Model_SentryT_3) 
	precache_model(Model_SentryT_4)	
	precache_model(Model_SentryCT_1) 
	precache_model(Model_SentryCT_2) 
	precache_model(Model_SentryCT_3)
	precache_model(Model_SentryCT_4)
	precache_model(Model_Rocket)	 
	precache_model(FROZEN_CUBE)
	precache_model(Model_Computergibs)  
	precache_model(Model_SentryT_1_VIP) 
	precache_model(Model_SentryT_2_VIP) 
	precache_model(Model_SentryT_3_VIP) 
	precache_model(Model_SentryT_4_VIP)  
	precache_model(Model_SentryCT_1_VIP) 
	precache_model(Model_SentryCT_2_VIP) 
	precache_model(Model_SentryCT_3_VIP)
	precache_model(Model_SentryCT_4_VIP)
	
	for(new i=0;i<sizeof(szSounds);i++)
		precache_sound(szSounds[i])
	g_sModelIndexFireball = precache_model("sprites/zerogxplode.spr")
	precache_sound(Sound_rocet_1)
	precache_sound(Sound_rocet_2)
	precache_sound(Sound_rocet_3)
	precache_sound(Sound_tok)
	precache_sound(Sound_tok_2)
	precache_sound(Sound_ignor)
	precache_sound(Sound_fire)
	precache_sound( gDispenserDestroy )

	g_iSPR_Smoke3 = precache_model("sprites/black_smoke4.spr")
	g_Sprite_sentry_1 = precache_model(Sprite_Sentry_1)
	g_Sprite_sentry_2 = precache_model(Sprite_Sentry_2)
	g_Sprite_sentry_3 = precache_model(Sprite_Sentry_3)
	g_Sprite_sentry_up = precache_model(Sprite_up)
	g_Chastic = precache_model(Sprite_Chastic)
	g_sModelIndexFireball2 = precache_model(Sprite_tok)
	g_sModelIndexMoroz = precache_model(Sprite_moroz)
}

public plugin_natives ()
{
	register_native ( "get_sentry_people", "native_get_sentry_people", 1 )
	register_native ( "get_sentry_team", "native_get_sentry_team", 1 )
	register_native ( "sentry_detonate_by_owner", "native_sentry_detonate_by_owner", 1 )
	register_native ( "get_sentry_t", "native_get_sentry_t", 1 )
	register_native ( "get_sentry_ct", "native_get_sentry_ct", 1 )
	register_native ( "get_sentry_lvl", "native_get_sentry_lvl", 1 )
	set_native_filter( "native_filter" ); 
}

public native_filter( const name[], index, trap ) { 
	if ( !trap ) 
	{ 
		return PLUGIN_HANDLED; 
	} 
	return PLUGIN_CONTINUE; 
}

public native_get_sentry_people ( sentry, who )
{
	return GetSentryPeople ( sentry, who )
}

public native_get_sentry_lvl(sentry)
{
	return GetSentryLevel(sentry)
}

public native_get_sentry_t()
{
	return g_teamsentriesNum[0]
}

public native_get_sentry_ct()
{
	return g_teamsentriesNum[1]
}

public CsTeams:native_get_sentry_team ( sentry )
{
	return GetSentryTeam ( sentry )
}

public native_sentry_detonate_by_owner ( id )
{
	while(GetSentryCount(id) > 0)
		sentry_detonate_by_owner(id)
}

public sgstats(id)
{

	set_hudmessage(255, 255, 255, 0.7, 0.75, 0, 0.5, 12.0, 2.0, 2.0, -1);
	ChatColor ( id, "%L", id, "SG_INFO_TXT", g_teamsentriesNum[1],g_teamsentriesNum[0],g_sentriesNum)
	show_hudmessage(id, "%L", id, "SG_INFO_HUD",g_sentriesNum, g_teamsentriesNum[1],g_teamsentriesNum[0]);

}

new remont_is[33]

public fm_cmdstart(id, uc_handle, seed) {
	if(!is_user_alive(id)) return
	if(g_fTime[id]>get_gametime()) return
	if(get_pcvar_num(g_Cvar_remont[2])!=1) return
	
	new buttons = get_uc(uc_handle,UC_Buttons)

	if(buttons & IN_USE){
		new target, body
		get_user_aiming(id, target, body, 128)
		
		static ClassName[32]
		pev(target, pev_classname, ClassName, charsmax(ClassName))
		if (equal(ClassName, "sentry")){
			g_fTime[id]=get_gametime()+0.1
			new CsTeams:team = GetSentryTeam ( target )
			if ( team != get_users_team_zp ( id ) )
				return 
			remont_is[id] = 1
			new Float:Health
			pev(target, pev_health, Health)

			if(get_user_money_s(id) < get_pcvar_num(g_Cvar_remont[0])){
				ColorChat(id,BLUE,"%L",id, "SG_REM_TXT_1", get_pcvar_num(g_Cvar_remont[0]))
				return
			}
			new iLevel = GetSentryLevel ( target )
			new Float:Max=g_HEALTHS[iLevel]
			if(Health>=Max)return
			if(Health>=Max - get_pcvar_float(g_Cvar_remont[1])){
				ColorChat(id,BLUE,"%L",id, "SG_REM_TXT_2" )
				
				Health = Max
				
				message_begin(MSG_ONE, g_bar_time, _, id)
				write_short(10000)
				write_short(100)
				message_end()
				
			}else{
				new Float:max_pro = Max/100
				
				new Float:progres_bar = Health / max_pro
				
				message_begin(MSG_ONE, g_bar_time, _, id)
				write_short(10000)
				write_short(floatround(progres_bar))
				message_end()
				Health+=get_pcvar_float(g_Cvar_remont[1])
			}

			g_fTime[id]=get_gametime()+0.1

			set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_remont[0]))

			set_pev(target, pev_health, Health)

		}
	}else{
		if(remont_is[id] == 1)
		{
			remont_is[id] = 0
			message_begin(MSG_ONE, 108, _, id)
			write_byte(0)
			write_byte(0)
			message_end()
		}
	}
}
public EventGameRestart()
{
	higher_score = 0;
	g_OwnName = "Остутствует";
}

public ev_Spectation ()
{
	new id = read_data ( 1 )

	if ( is_user_connected ( id ) && get_users_team_zp ( id ) == CS_TEAM_SPECTATOR )
		while ( GetSentryCount ( id ) > 0 )
			sentry_detonate_by_owner ( id )
}

public fw_TakeDamage ( ent, idinflictor, idattacker, Float:damage, damagebits)
{
	if ( !pev_valid ( ent ) )
		return HAM_IGNORED
	
	new sClassname[11]
	pev ( ent, pev_classname, sClassname, charsmax ( sClassname ) )
	
	if ( equal ( sClassname, "sentry" ) || equal ( sClassname, "sentrybase" ) )
	{
		new iOwner = GetSentryPeople ( ent, OWNER )

		if ( !is_user_connected ( iOwner ) || !is_valid_player ( iOwner ) || !is_user_connected ( idattacker ) || !is_valid_player ( idattacker ) )
		   return HAM_IGNORED
	
		if ( get_users_team_zp ( iOwner ) == get_users_team_zp ( idattacker ) && idattacker != iOwner )
		   return HAM_SUPERCEDE

		if(idattacker != iOwner )
		{
			if(GetSentryLevel(ent) == SENTRY_LEVEL_1){
			   set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_uron[0]), 9999999 ))
			}else if(GetSentryLevel(ent) == SENTRY_LEVEL_2){
				set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_uron[1]), 9999999 ))
			}else if(GetSentryLevel(ent) == SENTRY_LEVEL_3){
				set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_uron[2]), 9999999 ))
			}else if(GetSentryLevel(ent) == SENTRY_LEVEL_4){
				set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_uron[3]), 9999999 ))
			}
		}
		new Float:entorigin[3]
		pev( ent, pev_origin, entorigin )
		
		message_begin(MSG_ALL, SVC_TEMPENTITY);
		write_byte(TE_SPRITETRAIL);
		engfunc(EngFunc_WriteCoord, entorigin[0] + random_num(- 15, 15));
		engfunc(EngFunc_WriteCoord, entorigin[1] + random_num(- 15, 15));
		engfunc(EngFunc_WriteCoord, entorigin[2] + random_num(10, 30));
		engfunc(EngFunc_WriteCoord, entorigin[0] - random_num(- get_pcvar_num(g_Cvar_uron[5]), get_pcvar_num(g_Cvar_uron[5])));
		engfunc(EngFunc_WriteCoord, entorigin[1] - random_num(- get_pcvar_num(g_Cvar_uron[5]), get_pcvar_num(g_Cvar_uron[5])));
		engfunc(EngFunc_WriteCoord, entorigin[2] + random_num(- get_pcvar_num(g_Cvar_uron[5]), get_pcvar_num(g_Cvar_uron[5])));
		write_short(g_Chastic); // Индекс спрайта из прекеша (index of precached sprite)
		write_byte(get_pcvar_num(g_Cvar_uron[4]));	//колличество спрайтов
		write_byte(1); //вроде время сущиствования
		write_byte(1); //размер
		write_byte(1); // 10's
		write_byte(5); // 10's
		message_end(); 
		
		if ( pev ( ent, pev_health ) - damage <= 0.0 )
		{
			CREATE_SPRITETRAIL(entorigin)
		
			emit_sound( ent, CHAN_STATIC, gDispenserDestroy, VOL_NORM, ATTN_NORM, 0, PITCH_NORM )
			if(idattacker != iOwner )
			{
				if(GetSentryLevel(ent) == SENTRY_LEVEL_1){
					ChatColor ( idattacker, "%L",idattacker , "SG_DESTONE_1", get_pcvar_num(g_Cvar_sentry_destone[0]))
					set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_sentry_destone[0]), 9999999 ) )
				}else if(GetSentryLevel(ent) == SENTRY_LEVEL_2){
					ChatColor ( idattacker, "%L",idattacker , "SG_DESTONE_2", get_pcvar_num(g_Cvar_sentry_destone[1]))
					set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_sentry_destone[1]), 9999999 ) )
				}else if(GetSentryLevel(ent) == SENTRY_LEVEL_3){
					ChatColor ( idattacker, "%L",idattacker , "SG_DESTONE_3", get_pcvar_num(g_Cvar_sentry_destone[2]))
					set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_sentry_destone[2]), 9999999 ) )
				}else if(GetSentryLevel(ent) == SENTRY_LEVEL_4){
					ChatColor ( idattacker, "%L",idattacker , "SG_DESTONE_4", get_pcvar_num(g_Cvar_sentry_destone[3]))
					set_user_money_s ( idattacker, min ( get_user_money_s ( idattacker ) + get_pcvar_num(g_Cvar_sentry_destone[3]), 9999999 ) )
				}
			}
		}
	}																							 
	return HAM_IGNORED	
}

stock CREATE_SPRITETRAIL(Float:fOrigin[3])
{
	message_begin(MSG_ALL, SVC_TEMPENTITY);
	write_byte(TE_SPRITETRAIL);
	engfunc(EngFunc_WriteCoord, fOrigin[0]);
	engfunc(EngFunc_WriteCoord, fOrigin[1]);
	engfunc(EngFunc_WriteCoord, fOrigin[2]);
	engfunc(EngFunc_WriteCoord, fOrigin[0]);
	engfunc(EngFunc_WriteCoord, fOrigin[1]);
	engfunc(EngFunc_WriteCoord, fOrigin[2] + 5.0);
	write_short(g_Sprite_sentry_1); // Индекс спрайта из прекеша (index of precached sprite)
	write_byte(50);
	write_byte(10); // 0.1's
	write_byte(1);
	write_byte(100); // 10's
	write_byte(10); // 10's
	message_end(); 
}

public cmd_CreateSentry ( id )
{
	new iSentry = AimingAtSentry ( id )

	if ( iSentry && entity_range ( iSentry, id ) <= MAXUPGRADERANGE )
		SentryUpgrade ( id, iSentry, 0)
	else
		SentryBuild ( id )
		
	return PLUGIN_HANDLED
}

public SentryBuild (id)
{
	
	if(get_pcvar_num(byild_zaraza) == 1)
	{
		if(zp_has_round_started() == 0)
		{
			ChatColor ( id, "%L",id,"SG_ZAPRET_8")
			return
		}
	}

	switch(get_pcvar_num(g_sentry_team))
	{
		case 1:{
			if(get_users_team_zp(id) == CS_TEAM_CT)
			{
				ChatColor ( id, "%L",id,"SG_ZAPRET_0_1")
				return
			}
		}
		case 2:{
			if(get_users_team_zp(id) == CS_TEAM_T){
				ChatColor ( id, "%L",id,"SG_ZAPRET_0_2")
				return
			}
		}
	}
	if ( !is_user_alive ( id ) )
	{
		ChatColor ( id, "%L",id,"SG_ZAPRET_6")
		emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
		return
	}
	new iSentryCount = GetSentryCount ( id )
	
	new max_sentry = get_pcvar_num(g_Cvar_max_sg[1])
	
	if(get_user_flags(id) & get_pcvar_flags(g_Flag))
	{
		max_sentry = get_pcvar_num(g_Cvar_max_sg[0])
	}
	
	if ( iSentryCount >= max_sentry )
	{
		ChatColor ( id, "%L",id,"SG_ZAPRET_1", max_sentry)
		emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
		return
	}
   
	
	
	if ( g_inBuilding[id] )
	{
		ChatColor ( id, "%L", id, "SG_ZAPRET_3")
		emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
		return
	}
	if ( !is_entity_on_ground ( id ) )
	{
		ChatColor ( id, "%L", id, "SG_ZAPRET_2")
		emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
		return
	}
	
	new Float:origin[3],classname[32],e
	entity_get_vector(id,EV_VEC_origin,origin)

	while((e = find_ent_in_sphere(e,origin,SENTRYMINDISTANCE))){
		entity_get_string(e,EV_SZ_classname,classname,charsmax(classname))
		
		if(strcmp(classname,"sentrybase") == 0 && entity_get_int(e, BASE_INT_TEAM) == _:get_users_team_zp(id) && GetSentryPeople ( e, OWNER ) != id){
			ChatColor ( id, "%L", id, "SG_ZAPRET_4")
			emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
			return
		}
	}
	
	if ( get_user_money_s ( id ) < g_SENTRYCOST[iSentryCount] )
	{
		ChatColor ( id, "%L", id, "SG_ZAPRET_5", g_SENTRYCOST[iSentryCount] )
		return
	}

	new Float:fPlayerOrigin[3], Float:fOrigin[3], Float:fAngle[3]
	pev ( id, pev_origin, fPlayerOrigin )
	pev ( id, pev_angles, fAngle )
	fOrigin = fPlayerOrigin

	fOrigin[0] += floatcos ( fAngle[1], degrees ) * PLACE_RANGE
	fOrigin[1] += floatsin ( fAngle[1], degrees ) * PLACE_RANGE
	fOrigin[0] += floatcos ( fAngle[0], degrees) * PLACE_RANGE
	fOrigin[1] += floatcos ( fAngle[1], degrees )
	fOrigin[0] -= floatsin ( fAngle[1], degrees )
	fOrigin[1] += floatcos ( fAngle[2], degrees )
	fOrigin[1] -= floatsin ( fAngle[2], degrees ) * PLACE_RANGE
	fOrigin[0] -= floatsin ( fAngle[0], degrees ) * PLACE_RANGE
	fOrigin[0] -= PLACE_RANGE

	if ( pev ( id, pev_flags ) & FL_DUCKING )
		fOrigin[2] += 18.0, fPlayerOrigin[2] += 18.0

	new tr = 0, Float:fFraction
	engfunc ( EngFunc_TraceLine, fPlayerOrigin, fOrigin, 0, id, tr )
	get_tr2 ( tr, TR_flFraction, fFraction )

	if ( fFraction != 1.0 )
	{
		ChatColor ( id, "%L", id, "SG_ZAPRET_7")
		return
	}

	
	if ( CreateSentryBase ( fOrigin, id ) )
	{
		set_user_money_s ( id, get_user_money_s ( id ) - g_SENTRYCOST[iSentryCount] )
		ammo_hud ( id, 0 )
		sentries_num[id] += 1
		ammo_hud ( id, 1 )
	}
	else
		ChatColor ( id, "%L", id, "SG_ZAPRET_7")
}

IncreaseSentryCount ( id, sentry )
{
	g_iPlayerSentriesEdicts[id][g_iPlayerSentries[id]] = sentry
	g_iPlayerSentries[id]++
	new Float:fSentryOrigin[3], iSentryOrigin[3], iPlayerOrigin[3]
	entity_get_vector ( sentry, EV_VEC_origin, fSentryOrigin )
	FVecIVec ( fSentryOrigin, iSentryOrigin )

	new sName[32]
	get_user_name ( id, sName, charsmax ( sName ) )
	new CsTeams:iTeam = get_users_team_zp ( id )

	for ( new i = 1; i <= g_iMaxPlayers; i++ )
	{
		if ( !is_user_connected ( i ) || !is_user_alive ( i ) || get_users_team_zp ( i ) != iTeam || id == i )
			continue

		get_user_origin ( i, iPlayerOrigin )

		client_print ( i, print_center, "%L",i ,"SG_INFORMER_IN", sName, get_distance ( iPlayerOrigin, iSentryOrigin ) )

		message_begin ( MSG_ONE_UNRELIABLE, g_msgHostagePos, .player = i )
		write_byte ( i )
		write_byte ( SENTRY_RADAR_TEAMBUILT )
		write_coord ( iSentryOrigin[0] )
		write_coord ( iSentryOrigin[1] )
		write_coord ( iSentryOrigin[2] )
		message_end ()

		message_begin ( MSG_ONE_UNRELIABLE, g_msgHostageK, .player = i )
		write_byte ( SENTRY_RADAR_TEAMBUILT )
		message_end ()
	}
}
 
DecreaseSentryCount ( id, sentry )
{
	for ( new i; i < g_iPlayerSentries[id]; i++ )
	{
		if ( g_iPlayerSentriesEdicts[id][i] == sentry )
		{
			g_iPlayerSentriesEdicts[id][i] = g_iPlayerSentriesEdicts[id][g_iPlayerSentries[id] - 1]
			g_iPlayerSentriesEdicts[id][g_iPlayerSentries[id] - 1] = 0
			break
		}
	}
	if ( g_iPlayerSentries[id] > 0 ) g_iPlayerSentries[id]--
}

stock bool:CreateSentryBase ( Float:origin[3], creator, level = SENTRY_LEVEL_1 )
{
	if ( !CheckLocation ( origin ) )
		return false

	new Float:hitPoint[3], Float:originDown[3]
	originDown = origin
	originDown[2] = -5000.0 // dunno the lowest possible height...
	trace_line(0, origin, originDown, hitPoint)
	new Float:baDistanceFromGround = vector_distance(origin, hitPoint)

	new Float:difference = PLAYERORIGINHEIGHT - baDistanceFromGround
	if (difference < -1 * HEIGHTDIFFERENCEALLOWED || difference > HEIGHTDIFFERENCEALLOWED) return false

	new entbase = create_entity("func_breakable") // func_wall
	if (!entbase)
		return false

	#define SIZE 16.0

	new Float:fTraceEnds[5][3], Float:fTraceHit[3], iType, tr = create_tr2 ()
	fTraceEnds[0][0] = origin[0] - SIZE
	fTraceEnds[0][1] = origin[1] - SIZE
	fTraceEnds[0][2] = origin[2] + SIZE + SIZE
	fTraceEnds[1][0] = origin[0] + SIZE
	fTraceEnds[1][1] = origin[1] - SIZE
	fTraceEnds[1][2] = origin[2] + SIZE + SIZE
	fTraceEnds[2][0] = origin[0] - SIZE
	fTraceEnds[2][1] = origin[1] + SIZE
	fTraceEnds[2][2] = origin[2] + SIZE + SIZE
	fTraceEnds[3][0] = origin[0] + SIZE
	fTraceEnds[3][1] = origin[1] + SIZE
	fTraceEnds[3][2] = origin[2] + SIZE + SIZE
	fTraceEnds[4][0] = origin[0]
	fTraceEnds[4][1] = origin[1]
	fTraceEnds[4][2] = origin[2] + SIZE + SIZE

	for ( new i; i < 5; i++ )
	{
		fTraceHit = fTraceEnds[i]
		fTraceHit[2] += 40.0

		engfunc ( EngFunc_TraceLine, fTraceEnds[i], fTraceHit, 0, 0, tr )
		get_tr2 ( tr, TR_vecEndPos, fTraceHit )

		if ( fTraceHit[2] - fTraceEnds[i][2] != 40.0 )
		{
			iType = 1
			break
		}
	}

	if ( iType )
	{
		fTraceEnds[0][0] = origin[0] - SIZE
		fTraceEnds[0][1] = origin[1] - SIZE
		fTraceEnds[0][2] = origin[2] - SIZE - SIZE
		fTraceEnds[1][0] = origin[0] + SIZE
		fTraceEnds[1][1] = origin[1] - SIZE
		fTraceEnds[1][2] = origin[2] - SIZE - SIZE
		fTraceEnds[2][0] = origin[0] - SIZE
		fTraceEnds[2][1] = origin[1] + SIZE
		fTraceEnds[2][2] = origin[2] - SIZE - SIZE
		fTraceEnds[3][0] = origin[0] + SIZE
		fTraceEnds[3][1] = origin[1] + SIZE
		fTraceEnds[3][2] = origin[2] - SIZE - SIZE
		fTraceEnds[4][0] = origin[0]
		fTraceEnds[4][1] = origin[1]
		fTraceEnds[4][2] = origin[2] - SIZE - SIZE
		new Float:fMinDistance, Float:fDistance
		for ( new i; i < 5; i++ )
		{
			fTraceHit[0] = fTraceEnds[i][0]
			fTraceHit[1] = fTraceEnds[i][1]
			fTraceHit[2] = -8192.0
	
			engfunc ( EngFunc_TraceLine, fTraceEnds[i], fTraceHit, IGNORE_MONSTERS, 0, tr )
			get_tr2 ( tr, TR_vecEndPos, fTraceHit )
	
			fDistance = vector_distance ( fTraceEnds[i], fTraceHit )
	
			if ( fDistance < fMinDistance || fMinDistance <= 0.0 )
			{
				fMinDistance = fDistance
				origin[2] = fTraceHit[2]
			}
		}
	}
	
	origin[2] = origin[2] - 36.0

	new Float:fHighest[3]
	fHighest = origin
	fHighest[2] = 1000.0
	engfunc ( EngFunc_TraceLine, origin, fHighest, DONT_IGNORE_MONSTERS, 0, tr )
	get_tr2 ( tr, TR_vecEndPos, fHighest )
	free_tr2 ( tr )

	new healthstring[16]
	num_to_str(floatround(100000.0), healthstring, 15)
	DispatchKeyValue(entbase, "health", healthstring)
	DispatchKeyValue(entbase, "material", "6")

	DispatchSpawn(entbase)
	entity_set_string(entbase, EV_SZ_classname, "sentrybase")
	entity_set_model(entbase, Model_base) // later set according to level
	SetSentryPeople ( entbase, OWNER, creator )
	
	new Float:mins[3], Float:maxs[3]
	mins[0] = -16.0
	mins[1] = -16.0
	mins[2] = 0.0
	maxs[0] = 16.0
	maxs[1] = 16.0
	maxs[2] = floatclamp ( vector_distance ( origin, fHighest ), 128.0, 1000.0 ) // Set to 16.0 later.
	entity_set_size(entbase, mins, maxs)
	entity_set_origin(entbase, origin)
	
	entity_set_int(entbase, EV_INT_solid, SOLID_SLIDEBOX)
	entity_set_int(entbase, EV_INT_movetype, MOVETYPE_NONE) 
	entity_set_int(entbase, BASE_INT_TEAM, _:get_users_team_zp(creator))

	new parms[4]
	parms[0] = entbase
	parms[1] = creator
	parms[2] = level
	parms[3] = iType

	if ( iType ) origin[2] += 16.0

	g_sentryOrigins[creator - 1] = origin

	emit_sound(creator, CHAN_AUTO, "CSSB/sentry_gun/build_1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)

	set_task(0.01, "createsentryhead", 0, parms, 4)
	
	
	g_inBuilding[creator] = true

	return true
}

public createsentryhead(parms[4])
{
	new entbase = parms[0]
	new level = parms[2]
	new creator = parms[1]

	if ( !is_user_connected ( creator ) || !g_inBuilding[creator] ){
		if (is_valid_ent(entbase))
			remove_entity(entbase)

		return
	}
	new CsTeams:crteam = get_users_team_zp(creator)
	if ( !is_valid_team ( _:crteam ) ){
		if (is_valid_ent(entbase))
			remove_entity(entbase)

		sentries_num[creator]--
		return
	}

	new Float:origin[3]
	origin = g_sentryOrigins[creator - 1]
	
	origin[2] = origin[2] + 22.5

	new ent = create_entity("func_breakable")
	if (!ent){
		if (is_valid_ent(entbase)){
			remove_entity(entbase)
		}
		return
	}

	new Float:mins[3], Float:maxs[3]
	if (is_valid_ent(entbase)) {
		mins[0] = -10.0
		mins[1] = -10.0
		mins[2] = 0.0
		
		maxs[0] = 10.0
		maxs[1] = 10.0
		maxs[2] = 22.5
		entity_set_size(entbase, mins, maxs)

		entity_set_edict(ent, SENTRY_ENT_BASE, entbase)
		entity_set_edict(entbase, BASE_ENT_SENTRY, ent)
	}

	g_sentries[g_sentriesNum] = ent

	new healthstring[16]
	num_to_str(floatround(g_HEALTHS[0]), healthstring, 15)
	DispatchKeyValue(ent, "health", healthstring)
	DispatchKeyValue(ent, "material", "6")

	
	if(get_user_flags(creator) & get_pcvar_flags(g_Flag)){
		set_pev(ent, pev_euser4, 1)
	}else{
		set_pev(ent, pev_euser4, 0)
	}
	
	set_pev(ent, pev_euser3, 0)
	
	DispatchSpawn(ent)
	entity_set_string(ent, EV_SZ_classname, "sentry")
	
	if(pev(ent, pev_euser4) == 1){
		switch(_:crteam){
			case 1:{
				switch(level){
					case SENTRY_LEVEL_1: entity_set_model(ent, Model_SentryT_1_VIP)
				}
			}
			case 2:{
				switch(level){
					case SENTRY_LEVEL_1: entity_set_model(ent, Model_SentryCT_1_VIP)
				}
			}
		}
	}else{
		switch(_:crteam){
			case 1:{
				switch(level){
					case SENTRY_LEVEL_1: entity_set_model(ent, Model_SentryT_1)
				}
			}
			case 2:{
				switch(level){
					case SENTRY_LEVEL_1: entity_set_model(ent, Model_SentryCT_1)
				}
			}
		}
	}
	
	
	mins[0] = -16.0
	mins[1] = -16.0
	mins[2] = 0.0
	maxs[0] = 16.0
	maxs[1] = 16.0
	maxs[2] = 16.0
	entity_set_size(ent, mins, maxs)
	entity_set_origin(ent, origin)
	entity_get_vector(creator, EV_VEC_angles, origin)
	origin[0] = 0.0
	origin[1] += 180.0
	entity_set_float(ent, SENTRY_FL_ANGLE, origin[1])
	origin[2] = 0.0
	entity_set_vector(ent, EV_VEC_angles, origin)
	entity_set_int(ent, EV_INT_solid, SOLID_SLIDEBOX) // SOLID_SLIDEBOX
	entity_set_int(ent, EV_INT_movetype, MOVETYPE_NONE) // head flies, base doesn't
	set_anim(ent, 0)
	
	
	SetSentryPeople(ent, OWNER, creator)
	
	SetSentryTeam ( ent, crteam )
	SetSentryLevel ( ent, level )

	g_teamsentriesNum[_:crteam-1]++
	
	IncreaseSentryCount(creator, ent)

	new directions = (random_num(0, 1)<<SENTRY_DIR_CANNON)
	SetSentryPenddir ( ent, directions )

	g_inBuilding[creator] = false

	if (!is_valid_ent(entbase))
		SetSentryFiremode ( ent, SENTRY_FIREMODE_NUTS )

	entity_set_float ( ent, SENTRY_FL_LASTTHINK, get_gametime () + g_THINKFREQUENCIES[0] )
	entity_set_float ( ent, EV_FL_nextthink, get_gametime () + 0.01 )

	/*static bool:bHamRegistred

	if ( !bHamRegistred )
	{
		RegisterHamFromEntity ( Ham_Think, ent, "fw_ThinkSentry", 1 )
		bHamRegistred = true
	}*/
}

stock bool:CheckLocation ( const Float:origin[3] )
{
	if ( engfunc ( EngFunc_PointContents, origin ) != CONTENTS_EMPTY )
		return false

	new tr = create_tr2 ()

	engfunc ( EngFunc_TraceHull, origin, origin, 0, HULL_HEAD/*HUMAN*/, 0, tr )
	if ( !get_tr2 ( tr, TR_InOpen ) || get_tr2 ( tr, TR_StartSolid ) || get_tr2 ( tr, TR_AllSolid ) )
	{
		free_tr2 ( tr )
		return false
	}

	#define SIZE 16.0

	new Float:fTraceEnds[9][3], Float:fTraceHit[3], iHitEnt
	fTraceEnds[0][0] = origin[0]
	fTraceEnds[0][1] = origin[1]
	fTraceEnds[0][2] = origin[2] - SIZE - SIZE
	fTraceEnds[1][0] = origin[0] - SIZE
	fTraceEnds[1][1] = origin[1] - SIZE
	fTraceEnds[1][2] = origin[2] - SIZE - SIZE
	fTraceEnds[2][0] = origin[0] + SIZE
	fTraceEnds[2][1] = origin[1] - SIZE
	fTraceEnds[2][2] = origin[2] - SIZE - SIZE
	fTraceEnds[3][0] = origin[0] - SIZE
	fTraceEnds[3][1] = origin[1] + SIZE
	fTraceEnds[3][2] = origin[2] - SIZE - SIZE
	fTraceEnds[4][0] = origin[0] + SIZE
	fTraceEnds[4][1] = origin[1] + SIZE
	fTraceEnds[4][2] = origin[2] - SIZE - SIZE
	fTraceEnds[5][0] = origin[0] - SIZE
	fTraceEnds[5][1] = origin[1] - SIZE
	fTraceEnds[5][2] = origin[2] + SIZE + SIZE
	fTraceEnds[6][0] = origin[0] + SIZE
	fTraceEnds[6][1] = origin[1] - SIZE
	fTraceEnds[6][2] = origin[2] + SIZE + SIZE
	fTraceEnds[7][0] = origin[0] - SIZE
	fTraceEnds[7][1] = origin[1] + SIZE
	fTraceEnds[7][2] = origin[2] + SIZE + SIZE
	fTraceEnds[8][0] = origin[0] + SIZE
	fTraceEnds[8][1] = origin[1] + SIZE
	fTraceEnds[8][2] = origin[2] + SIZE + SIZE

	for (new i = 0, b = 0; i < 9; i++)
	{
		if ( engfunc ( EngFunc_PointContents, fTraceEnds[i] ) != CONTENTS_EMPTY )
		{
			free_tr2 ( tr )
			return false
		}

		engfunc ( EngFunc_TraceLine, origin, fTraceEnds[i], 0, 0, tr )
		iHitEnt = get_tr2 ( tr, TR_pHit )

		if ( iHitEnt != -1 )
		{
			free_tr2 ( tr )
			return false
		}

		get_tr2 ( tr, TR_vecEndPos, fTraceHit )

		for ( b = 0; b < 3; b++ )
		{
			if ( fTraceEnds[i][b] != fTraceHit[b] )
			{
				free_tr2 ( tr )
				return false
			}
		}
		if ( i < 5 )
		{
			fTraceHit[0] = fTraceEnds[i][0]
			fTraceHit[1] = fTraceEnds[i][1]
			fTraceHit[2] = -8192.0

			engfunc ( EngFunc_TraceLine, fTraceEnds[i], fTraceHit, 0, 0, tr )
			//get_tr2 ( tr, TR_vecEndPos, fTraceHit )
			iHitEnt = get_tr2 ( tr, TR_pHit )

			if ( pev_valid ( iHitEnt ) )
			{
				new sClassname[16]
				pev ( iHitEnt, pev_classname, sClassname, charsmax ( sClassname ) )
				if ( equal ( sClassname, "sentry" ) || equal ( sClassname, "NiceDispenser" ) )
				{
					free_tr2 ( tr )
					return false
				}
			}
		}
	}
	free_tr2 ( tr )
	return true
}

bool:sentry_pendulum ( sentry )
{
	if(!(is_valid_ent(sentry))) return true
	
	switch ( GetSentryFiremode ( sentry ) )
	{
		case SENTRY_FIREMODE_NO:
		{
			new Float:fAngles[3]
			entity_get_vector ( sentry, EV_VEC_angles, fAngles )
			new Float:fBaseAngle = entity_get_float ( sentry, SENTRY_FL_ANGLE )
			new iDirections = GetSentryPenddir ( sentry )
			
			if ( iDirections & (1<<SENTRY_DIR_CANNON) )
			{
				fAngles[1] -= ( PENDULUM_INCREMENT * 0.01 )
				if ( fAngles[1] < fBaseAngle - PENDULUM_MAX )
				{
					fAngles[1] = fBaseAngle - PENDULUM_MAX
					iDirections &= ~(1<<SENTRY_DIR_CANNON)
					SetSentryPenddir ( sentry, iDirections )
				}
			}
			else 
			{
				fAngles[1] += ( PENDULUM_INCREMENT * 0.01 )
				if ( fAngles[1] > fBaseAngle + PENDULUM_MAX ) 
				{
					fAngles[1] = fBaseAngle + PENDULUM_MAX
					iDirections |= (1<<SENTRY_DIR_CANNON)
					SetSentryPenddir ( sentry, iDirections )
				}
			}

			entity_set_vector ( sentry, EV_VEC_angles, fAngles )
			return true
		}
		case SENTRY_FIREMODE_NUTS:
		{
			new Float:fAngles[3]
			entity_get_vector ( sentry, EV_VEC_angles, fAngles )

			new Float:fSpinSpeed = entity_get_float ( sentry, SENTRY_FL_SPINSPEED )
			if ( GetSentryPenddir ( sentry ) & (1<<SENTRY_DIR_CANNON) )
			{
				fAngles[1] -= ( fSpinSpeed * 0.1 )
				if ( fAngles[1] < 0.0 )
					fAngles[1] = 360.0 + fAngles[1]
			}
			else
			{
				fAngles[1] += ( fSpinSpeed * 0.1 )
				if ( fAngles[1] > 360.0 )
					fAngles[1] = fAngles[1] - 360.0
			}
			entity_set_float ( sentry, SENTRY_FL_SPINSPEED, ( fSpinSpeed += random_float ( 5.0, 10.0 ) ) )

			new Float:fMaxSpin = entity_get_float ( sentry, SENTRY_FL_MAXSPIN )
			if ( fMaxSpin == 0.0 )
			{
				entity_set_float ( sentry, SENTRY_FL_LASTTHINK, 0.5 )
				entity_set_float ( sentry, SENTRY_FL_MAXSPIN, fMaxSpin = random_float ( 500.0, 750.0 ) )
			}
			else if ( fSpinSpeed >= fMaxSpin )
			{
				sentry_detonate ( sentry, false, false )
				return false
			}
			entity_set_vector ( sentry, EV_VEC_angles, fAngles )
			return true
		}
	}
	return true
}

//#define	TE_TRACER			6		// tracer effect from point to point
tracer(Float:start[3], Float:end[3]) {
	new start_[3], end_[3]
	FVecIVec(start, start_)
	FVecIVec(end, end_)
	message_begin(MSG_BROADCAST, SVC_TEMPENTITY) //  MSG_PAS MSG_BROADCAST
	write_byte(TE_TRACER)
	write_coord(start_[0])
	write_coord(start_[1])
	write_coord(start_[2] + 5)
	write_coord(end_[0])
	write_coord(end_[1])
	write_coord(end_[2])
	message_end()
}

prite_zona_UP(Float:start[3])
{
	new start_[3]
	FVecIVec(start, start_)

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
	write_byte(TE_SPRITE)//говорим что хотим создать, в данном случае спрайт
	write_coord(start_[0])//х - координата
	write_coord(start_[1])//у - координата
	write_coord(start_[2] + 20)//z - координата
	write_short(g_Sprite_sentry_up)// id спрайта
	write_byte(6) //масштаб
	write_byte(500)//яркость
	message_end()
	
	
}


prite_zona_3(Float:start[3])
{
	new start_[3]
	FVecIVec(start, start_)

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
	write_byte(TE_SPRITE)//говорим что хотим создать, в данном случае спрайт
	write_coord(start_[0])//х - координата
	write_coord(start_[1])//у - координата
	write_coord(start_[2] - 15)//z - координата
	write_short(g_Sprite_sentry_3)// id спрайта
	write_byte(2) //масштаб
	write_byte(200)//яркость
	message_end()
}

prite_zona_2(Float:start[3])
{
	new start_[3]
	FVecIVec(start, start_)

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
	write_byte(TE_SPRITE)//говорим что хотим создать, в данном случае спрайт
	write_coord(start_[0])//х - координата
	write_coord(start_[1])//у - координата
	write_coord(start_[2] - 15)//z - координата
	write_short(g_Sprite_sentry_2)// id спрайта
	write_byte(2) //масштаб
	write_byte(random_num(10, 50))//яркость
	message_end()
}

prite_zona_1(Float:start[3])
{
	new start_[3]
	FVecIVec(start, start_)

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
	write_byte(TE_SPRITE)//говорим что хотим создать, в данном случае спрайт
	write_coord(start_[0])//х - координата
	write_coord(start_[1])//у - координата
	write_coord(start_[2] - 15)//z - координата
	write_short(g_Sprite_sentry_1)// id спрайта
	write_byte(2) //масштаб
	write_byte(1000)//яркость
	message_end()
}

tracer2(Float:start[3], Float:end[3]) {
	new start_[3], end_[3]
	FVecIVec(start, start_)
		
	FVecIVec(end, end_)
	//код выстрела
	message_begin(MSG_BROADCAST, SVC_TEMPENTITY) //  MSG_PAS MSG_BROADCAST
	write_byte(TE_TRACER)
	write_coord(start_[0] - 15)
	write_coord(start_[1] - 15)
	write_coord(start_[2] + 5)
	write_coord(end_[0])
	write_coord(end_[1])
	write_coord(end_[2])
	message_end()
	
	FVecIVec(start, start_)
	FVecIVec(end, end_)
	//код выстрела
	message_begin(MSG_BROADCAST, SVC_TEMPENTITY) //  MSG_PAS MSG_BROADCAST
	write_byte(TE_TRACER)
	write_coord(start_[0] + 15)
	write_coord(start_[1] + 15)
	write_coord(start_[2] + 5)
	write_coord(end_[0])
	write_coord(end_[1])
	write_coord(end_[2])
	message_end()
	
/*
	message_begin(MSG_BROADCAST, SVC_TEMPENTITY);
	write_byte(TE_BEAMPOINTS);
	write_coord(start_[0] + 20);	 //Стартовая точка x
	write_coord(start_[1] - 20);	 //Стартовая точка y
	write_coord(start_[2]);	 //Стартовая точка z
	write_coord(start_[0] - 20);	 //Конечная точка x
	write_coord(start_[1] + 20);	 //Конечная точка y
	write_coord(start_[2]);	 //Конечная точка z
	write_short(g_Fire);		 //Индекс спрайта
	write_byte(0);				 //Стартовый кадр
	write_byte(1);				 //Скорость анимации
	write_byte(5);			//Время существования
	write_byte(100);	 //Толщина луча
	write_byte(0);	 //Искажение
	write_byte(255);			//Цвет красный
	write_byte(255);			//Цвет зеленый
	write_byte(0);			//Цвет синий
	write_byte(1000);			//Яркость
	write_byte(0);				//...
	message_end();
*/
}

stock create_explosion(Float:origin_[3]) {
	new origin[3]
	FVecIVec(origin_, origin)

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY, origin) // MSG_PAS not really good here
	write_byte(TE_EXPLOSION)
	write_coord(origin[0])
	write_coord(origin[1])
	write_coord(origin[2])
	write_short(g_sModelIndexFireball)
	write_byte(random_num(0, 20) + 50) // scale * 10 // random_num(0, 20) + 20
	write_byte(12) // framerate
	write_byte(TE_EXPLFLAG_NONE)
	message_end()

	KnockBack ( origin_ )

	new Float:playerOrigin[3], Float:distance, Float:flDmgToDo, Float:dmgbase = 90.0, newHealth
	for (new i = 1; i <= g_iMaxPlayers; i++) {
		if (!is_user_alive(i) || get_user_godmode(i))
			continue

		entity_get_vector(i, EV_VEC_origin, playerOrigin)
		distance = vector_distance(playerOrigin, origin_)
		if (distance <= SENTRYEXPLODERADIUS) {
			flDmgToDo = dmgbase - (dmgbase * (distance / SENTRYEXPLODERADIUS))
			newHealth = get_user_health(i) - floatround(flDmgToDo)
			if (newHealth <= 0) {
				set_task(0.0, "TicketToHell", i)
				continue
			}

			set_user_health(i, newHealth)

			message_begin(MSG_ONE_UNRELIABLE, g_msgDamage, {0,0,0}, i)
			write_byte(floatround(flDmgToDo))
			write_byte(floatround(flDmgToDo))
			write_long(DMG_BLAST)
			write_coord(origin[0])
			write_coord(origin[1])
			write_coord(origin[2])
			message_end()
		}
	}
}

public TicketToHell(player) {
	if (!is_user_connected(player))
		return
	new frags = get_user_frags(player)
	user_kill(player, 1) // don't decrease frags
	new parms[4]
	parms[0] = player
	parms[1] = frags
	parms[2] = cs_get_user_deaths(player)
	parms[3] = int:get_users_team_zp(player)
	set_task(0.0, "DelayedScoreInfoUpdate", 0, parms, 4)
}

public DelayedScoreInfoUpdate(parms[4]) {
	scoreinfo_update(parms[0], parms[1], parms[2], parms[3])
}

KnockBack ( Float:origin[3] )
{
	new iEntList[32]
	new iEntsFound = find_sphere_class ( 0, "player", SENTRYEXPLODERADIUS, iEntList, g_iMaxPlayers, origin )

	if ( !iEntsFound )
		return

	new Float:fOriginEnt[3]
	new Float:fVelocity[3]
	new Float:fOriginEnd[3]
	new Float:fDistance
	new iPlayer

	for ( new i; i < iEntsFound; i++ )
	{
		iPlayer = iEntList[i]

		if ( !is_user_alive ( iPlayer ) )
			continue

		entity_get_vector ( iPlayer, EV_VEC_origin, fOriginEnt )

		fDistance = vector_distance ( fOriginEnt, origin )

		if ( is_entity_on_ground ( iPlayer ) && fOriginEnt[2] < origin[2] )
			fOriginEnt[2] = origin[2] + fDistance

		entity_get_vector ( iPlayer, EV_VEC_velocity, fVelocity )

		fOriginEnd[0] = ( fOriginEnt[0] - origin[0] ) * SENTRYEXPLODERADIUS / fDistance + origin[0]
		fOriginEnd[1] = ( fOriginEnt[1] - origin[1] ) * SENTRYEXPLODERADIUS / fDistance + origin[1]
		fOriginEnd[2] = ( fOriginEnt[2] - origin[2] ) * SENTRYEXPLODERADIUS / fDistance + origin[2]

		fVelocity[0] += ( fOriginEnd[0] - fOriginEnt[0] ) * SENTRYSHOCKPOWER
		fVelocity[1] += ( fOriginEnd[1] - fOriginEnt[1] ) * SENTRYSHOCKPOWER
		fVelocity[2] += ( fOriginEnd[2] - fOriginEnt[2] ) * SENTRYSHOCKPOWER

		entity_set_vector ( iPlayer, EV_VEC_velocity, fVelocity )
	}
}

public msg_TempEntity ()
{
	if ( get_msg_args () != 15 && get_msg_arg_int ( 1 ) != TE_BREAKMODEL )
		return PLUGIN_CONTINUE

	for ( new i; i < g_sentriesNum; i++ )
	{
		if(is_valid_ent(g_sentries[i]))
		{
			if ( entity_get_float ( g_sentries[i], EV_FL_health ) <= 0.0 )
			{
				sentry_detonate ( i, false, true )
				i--
			}
		}
	}
	return PLUGIN_CONTINUE
}

new Float: Sentry_fire[500]

public fw_ThinkSentry ( ent)
{
	static Float:fGameTime; fGameTime = get_gametime ()
	new Float:entorigin[3]
	pev( ent, pev_origin, entorigin )
	new HP = pev ( ent, pev_health )
	if(GetSentryLevel(ent) > SENTRY_LEVEL_1)
	{
		if(HP<=get_pcvar_float(g_Cvar_uron[6]))
		{
			message_begin(MSG_BROADCAST,SVC_TEMPENTITY)
			write_byte(TE_SMOKE)
			engfunc(EngFunc_WriteCoord, entorigin[0]+random_float(-8.0, 8.0))
			engfunc(EngFunc_WriteCoord, entorigin[1]+random_float(-8.0, 8.0))
			engfunc(EngFunc_WriteCoord, entorigin[2]+random_float(25.0, 35.0) - 10)
			write_short(g_iSPR_Smoke3)
			write_byte(random_num(1,5))
			write_byte(30)
			message_end()
		}
	}
	
	
	if ( !is_valid_ent ( ent ) )
	{	
		entity_set_float ( ent, EV_FL_nextthink, fGameTime + 1.0 )
		return
	}

	static iOwner; iOwner = GetSentryPeople ( ent, OWNER )

	if ( !is_user_connected ( iOwner ) )
		return

	if ( get_users_team_zp ( iOwner ) == CS_TEAM_SPECTATOR )
	{
		sentry_detonate ( ent, true, false )
		return
	}
	
	if ( !sentry_pendulum ( ent ) )
	{
		entity_set_float ( ent, EV_FL_nextthink, fGameTime + 1.0 )
		return
	}
	
	if(pev(ent, pev_euser3) == 1)
	{
		entity_set_float ( ent, EV_FL_nextthink, fGameTime + 1.0 )
		return
	}

	if ( entity_get_float ( ent, SENTRY_FL_LASTTHINK ) <= fGameTime )
	{
		new Float:fOriginSentry[3], Float:fOriginHit[3], iHitEnt
		entity_get_vector ( ent, EV_VEC_origin, fOriginSentry )
		fOriginSentry[2] += CANNONHEIGHTFROMFEET // Move up some, this should be the Y origin of the cannon
	
		new firemode = GetSentryFiremode(ent)
		new target = GetSentryPeople(ent,TARGET)
		
		
		if ( firemode == SENTRY_FIREMODE_YES && is_valid_ent ( target ) && is_user_alive ( target ) && get_users_team_zp ( target ) != GetSentryTeam ( ent ) && !IsInSphere ( target ))
		{
			new sentryLevel = GetSentryLevel ( ent )
	
			new Float:fOriginTarget[3]
			entity_get_vector ( target, EV_VEC_origin, fOriginTarget )
	
			iHitEnt = trace_line ( ent, fOriginSentry, fOriginTarget, fOriginHit )
			if ( iHitEnt == entity_get_edict ( ent, SENTRY_ENT_BASE ) )
				iHitEnt = trace_line ( iHitEnt, fOriginHit, fOriginTarget, fOriginHit )
	
			if ( iHitEnt != target && is_user_alive ( iHitEnt ) && GetSentryTeam ( ent ) != get_users_team_zp ( iHitEnt ) && !IsInSphere ( iHitEnt ) && !get_user_godmode ( iHitEnt ))
			{
				target = iHitEnt
				SetSentryPeople(ent, TARGET, iHitEnt)
			}
			if ( iHitEnt == target )
			{
				SentryTurnToTarget ( ent, fOriginSentry, fOriginTarget )
				
				
				if(Sentry_fire[ent]<=get_gametime())
				{
					emit_sound(ent,CHAN_WEAPON,Sound_fire,1.0, ATTN_NORM, 0, PITCH_NORM )
					Sentry_fire[ent]=get_gametime() + 0.6
				}
				
				if(g_SentryMode[ent] == 2)
				{
					emit_sound ( ent, CHAN_WEAPON, Sound_tok_2, 1.0, ATTN_NORM, 0, PITCH_NORM )
				}
				
	
				if(GetSentryLevel(ent) == SENTRY_LEVEL_4)
				{
					if(g_SentryMode[ent] == 1)	//ракеты
					{
						if(get_gametime() > entity_get_float(ent,SENTRY_ROCKET_TIME)){
							if(entity_range(ent,target) >= get_pcvar_float(g_Cvar_mode_rpg[2])){
								new data[2]
								data[0] = ent
							
								ShootRockets(data)
								ShootRockets(data)
							}
							entity_set_float(ent,SENTRY_ROCKET_TIME,get_gametime() +  2.0)
						}
					}
				}
				
				
				
				if(GetSentryLevel(ent) == SENTRY_LEVEL_4)
				{
					if(g_SentryMode[ent] == 2)	//электро шок
					{
						if(entity_range(ent,target) >= 1)
						{
							new data[2]
							data[0] = ent	
							ShootFreezing(data)
						
							//entity_set_float(ent,SENTRY_FREEZ_TIME,get_gametime() +  3.0)
						}
					}
				}
				
				if(GetSentryLevel(ent) == SENTRY_LEVEL_4)
				{
					if(g_SentryMode[ent] == 3)	//заморозка
					{
						if(get_gametime() > entity_get_float(ent,SENTRY_FREEZ_TIME))
						{
							new data[2]
							data[0] = ent	
							ShootFreezing_cub(data)
						
							//entity_set_float(ent,SENTRY_FREEZ_TIME,get_gametime() +  3.0)
						}
					}
				}
	
				
				sentry_damagetoplayer ( ent, sentryLevel, fOriginSentry, target )
				
				
				set_anim(ent, 1)
				
				if(GetSentryLevel(ent) == SENTRY_LEVEL_1)
				{
					tracer ( fOriginSentry, fOriginHit )
				}
				else
				{
					if(g_SentryMode[ent] == 2)
					{
					}
					else
					{
						tracer2(fOriginSentry, fOriginHit)
					}
				}

				entity_set_float ( ent, SENTRY_FL_LASTTHINK, fGameTime + 0.1 )
				entity_set_float ( ent, EV_FL_nextthink, fGameTime + 0.01 )
				return
			}
			else
				SetSentryFiremode ( ent, SENTRY_FIREMODE_NO )
		}
		else if ( firemode == SENTRY_FIREMODE_NUTS )
		{
			new iHitEnt2 = EntViewHitPoint ( ent, fOriginSentry, fOriginHit )
			
			if(Sentry_fire[ent]<=get_gametime())
			{
				emit_sound(ent,CHAN_WEAPON,Sound_fire,1.0, ATTN_NORM, 0, PITCH_NORM )
				Sentry_fire[ent]=get_gametime() + 0.6
			}

			if(g_SentryMode[ent] == 2)
				{
					emit_sound(ent, CHAN_WEAPON, Sound_tok_2, 1.0, ATTN_NORM, 0, PITCH_NORM)
				}
				
			
			if(GetSentryLevel(ent) == SENTRY_LEVEL_1)
			{
			tracer ( fOriginSentry, fOriginHit )
			
			}
			else
			{
			tracer2(fOriginSentry, fOriginHit)
			
			}
	
			if (is_user_connected(iHitEnt2) && is_user_alive(iHitEnt2) && !get_user_godmode(iHitEnt2))
			{
				sentry_damagetoplayer(ent, GetSentryLevel ( ent ), fOriginSentry, iHitEnt2)
			}
			entity_set_float ( ent, SENTRY_FL_LASTTHINK, fGameTime + 0.1 )
			entity_set_float ( ent, EV_FL_nextthink, fGameTime + 0.01 )
			return
		}
	
		if ( random_num ( 0, 99 ) < 10 )
			emit_sound ( ent, CHAN_AUTO, "dmsentries/turridle.wav", 1.0, ATTN_NORM, 0, PITCH_NORM )
		
		set_anim(ent, 0)
		
		SentryTurnToTargetObnul(ent)
		
		new closestTarget = 0, Float:closestDistance, Float:distance, Float:closestOrigin[3], Float:playerOrigin[3], CsTeams:sentryTeam = GetSentryTeam ( ent )
		for ( new i = 1; i <= g_iMaxPlayers; i++ )
		{
			if ( !is_user_connected ( i ) || !is_user_alive ( i ) || get_users_team_zp ( i ) == sentryTeam || IsInSphere ( i ) )
				continue
	
			entity_get_vector ( i, EV_VEC_origin, playerOrigin )
	
			iHitEnt = trace_line ( ent, fOriginSentry, playerOrigin, fOriginHit )
			if ( iHitEnt == entity_get_edict ( ent, SENTRY_ENT_BASE ) )
				iHitEnt = trace_line(iHitEnt, fOriginHit, playerOrigin, fOriginHit)
	
			if ( iHitEnt == i )
			{
				distance = vector_distance ( fOriginSentry, playerOrigin )
				closestOrigin = playerOrigin
	
				if ( distance < closestDistance || closestTarget == 0 )
				{
					closestTarget = i
					closestDistance = distance
				}
			}
		}
	
		if ( closestTarget )
		{
			emit_sound ( ent, CHAN_AUTO, "dmsentries/turrspot.wav", 1.0, ATTN_NORM, 0, PITCH_NORM )
			set_anim(ent, 0)
			SentryTurnToTarget ( ent, fOriginSentry, closestOrigin )
	
			SetSentryFiremode ( ent, SENTRY_FIREMODE_YES )
			SetSentryPeople ( ent, TARGET, closestTarget )
		}
		else
			SetSentryFiremode ( ent, SENTRY_FIREMODE_NO )

		entity_set_float ( ent, SENTRY_FL_LASTTHINK, fGameTime + g_THINKFREQUENCIES[GetSentryLevel ( ent )] )
	}
	entity_set_float ( ent, EV_FL_nextthink, fGameTime + 0.01 )
}

public think_sentrybase(sentrybase) {
	if ( !pev_valid ( sentrybase ) )
		return PLUGIN_CONTINUE

	sentrybase_broke(sentrybase)
	return PLUGIN_CONTINUE
}

sentrybase_broke(sentrybase) {
	new sentry = entity_get_edict(sentrybase, BASE_ENT_SENTRY)
	if (is_valid_ent(sentrybase))
		remove_entity(sentrybase)

	if ( !pev_valid ( sentry ) )
		return

	SetSentryFiremode ( sentry, SENTRY_FIREMODE_NUTS )
}

sentry_detonate(sentry, bool:quiet, bool:isIndex) {
	
	g_iKillSentry[sentry] = 0;
	g_SentryMode[sentry] = 0
	
	new i
	if (isIndex)
	{
		i = sentry
		sentry = g_sentries[sentry]
		if (!is_valid_ent(sentry))
			return
	}
	else
	{
		if (!is_valid_ent(sentry))
			return

		for (new j = 0; j < g_sentriesNum; j++) {
			if (g_sentries[j] == sentry) {
				i = j
				break
			}
		}
	}
	entity_set_float ( sentry, EV_FL_nextthink, 0.0 )

	new owner = GetSentryPeople(sentry, OWNER)

	if (!quiet) {
		new Float:origin[3]
		entity_get_vector(sentry, EV_VEC_origin, origin)
		create_explosion(origin)
		ChatColor ( owner, "%L", owner, "SG_DEIST_1")
		ammo_hud(owner, 0)
		sentries_num[owner] -= 1
		ammo_hud(owner, 1)
	}
	DecreaseSentryCount(owner, sentry)

	// Remove base first
	if (GetSentryFiremode ( sentry ) != SENTRY_FIREMODE_NUTS)
		if (pev_valid (entity_get_edict(sentry, SENTRY_ENT_BASE)))
			remove_entity(entity_get_edict(sentry, SENTRY_ENT_BASE))

	new iSentryTeam = _:GetSentryTeam ( sentry )

	set_task ( 0.1, "DelayRemoveEntity", sentry )
	//remove_entity(sentry)
	// Put the last sentry in the deleted entity's place
	if(0 > (g_sentriesNum - 1) > MAXSENTRIES) return
	g_sentries[i] = g_sentries[g_sentriesNum - 1]
	
	if ( iSentryTeam ) g_teamsentriesNum[iSentryTeam-1]--
	
	//if(g_teamsentriesNum[1] == 0) sh_reset_hero();
	//else if(g_teamsentriesNum[0] == 0) sh_reset_hero();
}

public DelayRemoveEntity ( ent )
{
	if ( pev_valid ( ent ) )
		remove_entity ( ent )
}

sentry_detonate_by_owner(owner, bool:quiet = false) {
	for(new i = 0; i < g_sentriesNum; i++) {
		if (GetSentryPeople(g_sentries[i], OWNER) == owner) {
			sentry_detonate(i, quiet, true)
			g_iKillSentry[g_sentries[i]] = 0;
			break
		}
	}
}

public client_disconnect(id) {
	g_StatsKill[id] = 0;
	while (GetSentryCount(id) > 0)
		sentry_detonate_by_owner(id)
}

// урон игроку
stock sentry_damagetoplayer(sentry, sentryLevel, Float:sentryOrigin[3], target) {
	new newHealth 

	if(g_SentryMode[sentry] == 2)
	{
		newHealth = get_user_health(target) - (g_DMG[sentryLevel] + 10 )
	}
	else
	{
		newHealth = get_user_health(target) - g_DMG[sentryLevel]
	}
	
	if (newHealth <= 0) {
		new targetFrags = get_user_frags(target) + 1
		new owner = GetSentryPeople(sentry, OWNER)
		
		if(!is_user_connected(owner))
			return
		
		new ownerFrags = get_user_frags(owner) + 1
		set_user_frags(target, targetFrags) // otherwise frags are subtracted from victim for dying (!!)
		set_user_frags(owner, ownerFrags)
		
		new contributors[4]
		contributors[0] = owner
		contributors[1] = GetSentryPeople(sentry, UPGRADER_1)
		contributors[2] = GetSentryPeople(sentry, UPGRADER_2)
		contributors[3] = GetSentryPeople(sentry, UPGRADER_3)
		
		for(new i ; i < sizeof contributors ; i++){
			if(!contributors[i])
				continue
				
			if(!is_user_connected(contributors[i]) || get_users_team_zp(contributors[i]) != get_users_team_zp(contributors[0])){
				switch(i){ // yao face
					case 1: SetSentryPeople(sentry,UPGRADER_1,0)
					case 2: SetSentryPeople(sentry,UPGRADER_2,0)
					case 3: SetSentryPeople(sentry,UPGRADER_3,0)
				}
				
				continue
			}
			
			// izvini 4yvak, no menya nakrilo
			set_user_money_s(contributors[i],
				clamp(
					get_user_money_s(contributors[i]) + (i == 0 ? SENTRYOWNERAWARD : SENTRYASSISTAWARD),
					0,
					9999999
				)
			)
		}

		// ny ebatb kakoy frag
		message_begin(MSG_ALL, g_msgDeathMsg, {0, 0, 0} ,0)
		write_byte(owner)
		write_byte(target)
		write_byte(0)
		write_string("sentry gun")
		message_end()
		
		//add_user_exp ( owner )
		scoreinfo_update(owner, ownerFrags, cs_get_user_deaths(owner), int:get_users_team_zp(owner))
		set_msg_block(g_msgDeathMsg, BLOCK_ONCE)
		
		g_iKillSentry[sentry]++;
		g_StatsKill[owner]++;
		
		for (new i = 1; i <= g_iMaxPlayers; i++)
		{
			if( is_user_connected( i ) && !is_user_bot( i ) )
			{
				new sentry_frags = g_StatsKill[i];
								   
				if( sentry_frags > higher_score )
				{
					higher_score = sentry_frags;
					get_user_name( i, g_OwnName, 31 );
					g_OwnId = i
				}
			}
		}
	}

	set_user_health(target, newHealth)

	message_begin(MSG_ONE_UNRELIABLE, g_msgDamage, {0,0,0}, target)
	write_byte(g_DMG[sentryLevel])
	write_byte(g_DMG[sentryLevel])
	write_long(DMG_BULLET)
	write_coord(floatround(sentryOrigin[0]))
	write_coord(floatround(sentryOrigin[1]))
	write_coord(floatround(sentryOrigin[2]))
	message_end()
}

public show_BestPlayer()
{
	if( higher_score != 0 )
	{   
		//set_dhudmessage(random_num(0, 255), random_num(0, 255), random_num(0, 255), -1.0, 0.0, 0, 6.0, 1.0)
		//show_dhudmessage(0, "/-------------------------\^n^n\-------------------------/")
	
		
		new iSentryCount = GetSentryCount ( g_OwnId )
		
		if ( iSentryCount == 0 )
		{
			set_hudmessage( 0, 255, 0, -1.0, 0.0, 0, 6.0, 6.0, 0.1, 0.2, -1 )
			ShowSyncHudMsg( 0, g_MsgSync, "^nЛидер убийств пушками^n %s - %d убийств^nУ него нет пушек!", g_OwnName, higher_score )
		}
		if ( iSentryCount == 1 )
		{
			set_hudmessage( 0, 255, 0, -1.0, 0.0, 0, 6.0, 6.0, 0.1, 0.2, -1 )
			ShowSyncHudMsg( 0, g_MsgSync, "^nЛидер убийств пушками^n %s - %d убийств^nОдной пушкой", g_OwnName, higher_score )
		}
		if ( iSentryCount == 2 )
		{
			set_hudmessage( 0, 255, 0, -1.0, 0.0, 0, 6.0, 6.0, 0.1, 0.2, -1 )
			ShowSyncHudMsg( 0, g_MsgSync, "^nЛидер убийств пушками^n %s - %d убийств^nДвумя пушками", g_OwnName, higher_score )
		}
		if ( iSentryCount == 3 )
		{
			set_hudmessage( 0, 255, 0, -1.0, 0.0, 0, 6.0, 6.0, 0.1, 0.2, -1 )
			ShowSyncHudMsg( 0, g_MsgSync, "^nЛидер убийств пушками^n %s - %d убийств^nТремя пушками", g_OwnName, higher_score )
		}
	
		
	}
}

scoreinfo_update(id, frags, deaths, team) {
	message_begin(MSG_ALL, g_msgScoreInfo)
	write_byte(id)
	write_short(frags)
	write_short(deaths)
	write_short(0)
	write_short(team)
	message_end()
}


SentryTurnToTarget ( ent, Float:sentry_origin[3], Float:closest_origin[3] )
{
	new Float:fAngle[3]
	entity_get_vector ( ent, EV_VEC_angles, fAngle )
	new Float:x = closest_origin[0] - sentry_origin[0]
	new Float:z = closest_origin[1] - sentry_origin[1]

	new Float:fRadians = floatatan ( z/x, radian )
	fAngle[1] = fRadians * g_ONEEIGHTYTHROUGHPI
	if ( closest_origin[0] < sentry_origin[0] )
		fAngle[1] -= 180.0
	
	
	new Float:h = closest_origin[2] - sentry_origin[2]
	new Float:b = vector_distance(sentry_origin, closest_origin)
	fRadians = floatatan (h/b, radian)
	fAngle[0] = fRadians * (180.0 / 3.141592654)
	

//	entity_set_float ( ent, SENTRY_FL_ANGLE, floatround(fAngle[0]) )
	entity_set_vector ( ent, EV_VEC_angles, fAngle )
}

/*
SentryTurnToTarget ( ent, Float:sentry_origin[3], Float:closest_origin[3] )
{
	new Float:fAngle[3]
	entity_get_vector ( ent, EV_VEC_angles, fAngle )
	new Float:x = closest_origin[0] - sentry_origin[0]
	new Float:z = closest_origin[1] - sentry_origin[1]

	new Float:fRadians = floatatan ( z/x, radian )
	fAngle[1] = fRadians * g_ONEEIGHTYTHROUGHPI
	if ( closest_origin[0] < sentry_origin[0] )
		fAngle[1] -= 180.0

	entity_set_float ( ent, SENTRY_FL_ANGLE, fAngle[1] )
	entity_set_vector ( ent, EV_VEC_angles, fAngle )
}
*/

SentryTurnToTargetObnul(ent)
{
	new Float:fAngle[3]
	entity_get_vector ( ent, EV_VEC_angles, fAngle )
	
	fAngle[0] = 0.0

	entity_set_vector ( ent, EV_VEC_angles, fAngle )
}

AimingAtSentry ( id )
{
	if ( !is_user_alive ( id ) )
		return 0

	new hitEnt, bodyPart
	if (get_user_aiming(id, hitEnt, bodyPart) == 0.0)
		return 0

	if ( is_valid_ent ( hitEnt ) )
	{
		new classname[32], l_sentry
		entity_get_string(hitEnt, EV_SZ_classname, classname, 31)
		if (equal(classname, "sentry_base"))
			l_sentry = entity_get_edict(hitEnt, BASE_ENT_SENTRY)
		else if (equal(classname, "sentry"))
			l_sentry = hitEnt
		else
			l_sentry = 0

		return l_sentry
	}
	return 0
}

new Float:g_time_menu[33]
new Float:g_time_up[33]

// улучшение уровня пушки
bool:SentryUpgrade ( id, sentry,num)
{
	if(g_time_up[id]>get_gametime()) return false
	
	g_time_up[id]=get_gametime()+1.0
	
	new iLevel = GetSentryLevel ( sentry )
		
	if ( iLevel < SENTRY_LEVEL_4 )
	{
		g_SentryMode[sentry] = 0
	}
	
	if ( GetSentryFiremode ( sentry ) == SENTRY_FIREMODE_NUTS )
		return false
	

	if ( iLevel == SENTRY_LEVEL_4 )
		return false
	
	if(get_user_flags(id) & get_pcvar_flags(g_Flag))
	{
		
		//if ( GetSentryPeople ( sentry, OWNER ) == id )
			//return false
	} 
	else if(get_user_flags(id) & A_ADMIN)
	{
		if ( GetSentryPeople ( sentry, OWNER ) == id )
		{
	 
			emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
			ColorChat(id,BLUE,"%L",id, "SG_INFORM_1" )
			
			return false
		}
	}
	
	if(get_users_team_zp(id) != GetSentryTeam(sentry))
		return false							   

	else	 if(get_user_flags(id) & A_ADMIN)
	{
		if(GetSentryPeople(sentry,UPGRADER_1) == id || GetSentryPeople(sentry,UPGRADER_2) == id || GetSentryPeople(sentry,UPGRADER_3) == id)
		{
			emit_sound(id,0,Sound_ignor,1.0, ATTN_NORM, 0, PITCH_NORM )
			ColorChat(id,BLUE,"%L",id, "SG_INFORM_8" )
			return false
		}
	} 
	
	if(iLevel == SENTRY_LEVEL_3 && num == 0) {
		g_SentryId[id] = sentry;
		g_time_up[id] = 0.0
		if(g_time_menu[id]>get_gametime()) return false
		MenuUpgrade(id);
		g_time_menu[id] = get_gametime() + 1.0
		return false
	}
	   
	if(iLevel == SENTRY_LEVEL_1)
	{
		if (get_user_money_s (id) - get_pcvar_num(g_Cvar_up[0]) < 0)
		{
			if(g_OffSpam[id] == 1) 
			{
				ChatColor ( id, "%L",id, "SG_ZAPRET_5", get_pcvar_num(g_Cvar_up[0]))
			}
			return false
		}else{
			set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_up[0]))
		}
	}
	
	if(iLevel == SENTRY_LEVEL_2)
	{
		if (get_user_money_s (id) - get_pcvar_num(g_Cvar_up[1]) < 0)
		{
			if(g_OffSpam[id] == 1) 
			{
				ChatColor ( id, "%L",id, "SG_ZAPRET_5", get_pcvar_num(g_Cvar_up[1]))
			}
			return false
		}else{
			set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_up[1]))
		}
	}
	

	set_user_money_s( id, get_user_money_s( id ) + get_pcvar_num(g_Cvar_nograda))		//Тот самый код вознаграждения
	
	ChatColor ( id, "%L",id, "SG_DEIST_2", get_pcvar_num(g_Cvar_nograda))
	
	iLevel++ 
	
	new iTeam = get_users_team_zp ( id ), iUpgraderField
	if(pev(sentry, pev_euser4) == 1){
		switch ( iLevel )
		{
			// this kod is very zaebisb
			case SENTRY_LEVEL_2:
			{
				switch ( iTeam )
				{
					case 1:entity_set_model ( sentry, Model_SentryT_2_VIP )
					case 2:entity_set_model ( sentry, Model_SentryCT_2_VIP )
				}
				iUpgraderField = UPGRADER_1
			}
			case SENTRY_LEVEL_3:
			{
				switch ( iTeam )
				{
					case 1:entity_set_model ( sentry, Model_SentryT_3_VIP )
					case 2:entity_set_model ( sentry, Model_SentryCT_3_VIP )
				}
				iUpgraderField = UPGRADER_2
			}
			case SENTRY_LEVEL_4:{
				switch(iTeam){
					case 1:entity_set_model ( sentry, Model_SentryT_4_VIP )
					case 2:entity_set_model ( sentry, Model_SentryCT_4_VIP )
				}
			
				entity_set_byte(sentry,EV_BYTE_controller2,120)
				entity_set_byte(sentry,EV_BYTE_controller3,120)
			
				iUpgraderField = UPGRADER_3
			}
		}
	}else{
		switch ( iLevel )
		{
			// this kod is very zaebisb
			case SENTRY_LEVEL_2:
			{
				switch ( iTeam )
				{
					case 1:entity_set_model ( sentry, Model_SentryT_2 )
					case 2:entity_set_model ( sentry, Model_SentryCT_2 )
				}
				iUpgraderField = UPGRADER_1
			}
			case SENTRY_LEVEL_3:
			{
				switch ( iTeam )
				{
					case 1:entity_set_model ( sentry, Model_SentryT_3 )
					case 2:entity_set_model ( sentry, Model_SentryCT_3 )
				}
				iUpgraderField = UPGRADER_2
			}
			case SENTRY_LEVEL_4:{
				switch(iTeam){
					case 1:entity_set_model ( sentry, Model_SentryT_4 )
					case 2:entity_set_model ( sentry, Model_SentryCT_4 )
				}
			
				entity_set_byte(sentry,EV_BYTE_controller2,120)
				entity_set_byte(sentry,EV_BYTE_controller3,120)
			
				iUpgraderField = UPGRADER_3
			}
		}
	}

	new Float:fMins[3], Float:fMaxs[3]
	fMins[0] = -16.0
	fMins[1] = -16.0
	fMins[2] = 0.0
	fMaxs[0] = 16.0
	fMaxs[1] = 16.0
	fMaxs[2] = 35.0 // 4.0
	entity_set_size ( sentry, fMins, fMaxs )
	emit_sound ( sentry, CHAN_AUTO, "dmsentries/turrset.wav", 1.0, ATTN_NORM, 0, PITCH_NORM )
	SetSentryLevel ( sentry, iLevel )
	entity_set_float ( sentry, EV_FL_health, g_HEALTHS[iLevel] )
	entity_set_float ( entity_get_edict ( sentry, SENTRY_ENT_BASE ), EV_FL_health, 100000.0 )
	SetSentryPeople ( sentry, iUpgraderField, id )
	
	new sName[32]
	get_user_name ( id, sName, charsmax ( sName ) )
	client_print ( GetSentryPeople ( sentry, OWNER ), print_center, "%L",id ,"SG_INFORMER_UP", sName, iLevel + 1 )
	return true
}


public MenuUpgrade(id)
{
	static menu[512], len=0;
	len = formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_NAZ");
	if(get_pcvar_num(g_Cvar_mode_aktiv[0]) == 1)
	{
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_1_ONN", get_pcvar_num(g_Cvar_mode_cost[0]));
	}else{
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_1_OFF");
	} if(get_pcvar_num(g_Cvar_mode_aktiv[1]) == 1)
	{
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_2_ONN", get_pcvar_num(g_Cvar_mode_cost[1]));
	}else{
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_2_OFF");
	} if(get_pcvar_num(g_Cvar_mode_aktiv[2]) == 1)
	{
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_3_ONN", get_pcvar_num(g_Cvar_mode_cost[2]));
	}else{	
		len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_KEY_3_OFF");
	}
	len += formatex(menu[len], charsmax(menu) - len, "%L", id, "SG_MENU_OFF");
	
	//Вывод на показ меню
	show_menu(id, keys, menu, 4, "Menu");
	return PLUGIN_HANDLED;
}
// Функцианальная часть Магазина
public MenuFunc(id, key) 
{
	switch(key)
	{
		case 0: {	
			if(get_pcvar_num(g_Cvar_mode_aktiv[0]) == 1)
			{
				if(get_user_money_s(id) >= get_pcvar_num(g_Cvar_mode_cost[0]))
				{
					if(is_valid_ent(g_SentryId[id])) {
						SentryUpgrade ( id, g_SentryId[id], 1);
						g_SentryMode[g_SentryId[id]] = 1
						set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_mode_cost[0]) )
						ColorChat(id,BLUE,"%L", id, "SG_MODE_1" )
					} 
				}else{
					ColorChat(id,BLUE,"%L", id, "SG_ZAPRET_5",get_pcvar_num(g_Cvar_mode_cost[0]))
				}
			}
		}
		
		case 1: { 
			if(get_pcvar_num(g_Cvar_mode_aktiv[1]) == 1)
			{
				if(get_user_money_s(id) >= get_pcvar_num(g_Cvar_mode_cost[1]))
				{
					if(is_valid_ent(g_SentryId[id])) {
						SentryUpgrade ( id, g_SentryId[id], 1);
						g_SentryMode[g_SentryId[id]] = 2
						set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_mode_cost[1]) )
						ColorChat(id,BLUE,"%L", id, "SG_MODE_2" )
					}
				}else{
					ColorChat(id,BLUE,"%L", id, "SG_ZAPRET_5",get_pcvar_num(g_Cvar_mode_cost[1]))
				}
			}
		}

		case 2: {   
			if(get_pcvar_num(g_Cvar_mode_aktiv[2]) == 1)
			{
				if(get_user_money_s(id) >= get_pcvar_num(g_Cvar_mode_cost[2]))
				{
					if(is_valid_ent(g_SentryId[id])) {
						SentryUpgrade ( id, g_SentryId[id], 1);
						g_SentryMode[g_SentryId[id]] = 3
						set_user_money_s( id, get_user_money_s( id ) - get_pcvar_num(g_Cvar_mode_cost[2]) )
						ColorChat(id,BLUE,"%L", id, "SG_MODE_3" )
					} 
				}else{
					ColorChat(id,BLUE,"%L", id, "SG_ZAPRET_5",get_pcvar_num(g_Cvar_mode_cost[2]))
				}
				
			}
		}
/*
		case 3: { 
			if(szTime == 0)
			{
				if(get_user_money_s(id) >= 2000)
				{
					if(is_valid_ent(g_SentryId[id])) {
						SentryUpgrade ( id, g_SentryId[id], 1);
						g_SentryMode[g_SentryId[id]] = 4
						set_user_money_s( id, get_user_money_s( id ) - 2000 )
						ColorChat(id,BLUE,"^3[^4Информация^3] ^3Вы надили пушку способностью^4 Аура лечения " )
					} 
				}
			}
		} 
*/
		case 9:{
		}
	}
	return PLUGIN_HANDLED;
}

stock EntViewHitPoint ( index, Float:origin[3], Float:hitorigin[3] )
{
	if ( !is_valid_ent ( index ) )
		return 0

	new Float:angle[3], Float:vec[3], Float:f_dest[3]

	entity_get_vector(index, EV_VEC_angles, angle)

	engfunc(EngFunc_AngleVectors, angle, vec, 0, 0)

	f_dest[0] = origin[0] + vec[0] * 9999
	f_dest[1] = origin[1] + vec[1] * 9999
	f_dest[2] = origin[2] + vec[2] * 9999

	return trace_line(index, origin, f_dest, hitorigin)
}

public fw_PlayerSpawn_Post ( id )
{
	if ( !is_user_alive ( id ) )
		return

	g_inBuilding[id] = false

	while ( GetSentryCount ( id ) > 0 )
		sentry_detonate_by_owner ( id, true )

	ammo_hud ( id, 0 )
	sentries_num[id] = 0
}

new Float:taget_tim[999]
public fw_TraceLine_Post ( Float:start[3], Float:end[3], noMonsters, id )
{
	if(taget_tim[id]>get_gametime())
		return FMRES_IGNORED 
		
	taget_tim[id]=get_gametime()+0.4
	
	if ( !is_valid_player ( id ) || !is_user_alive ( id ) )
		return FMRES_IGNORED

	new iHitEnt = get_tr ( TR_pHit )

	if ( iHitEnt <= g_iMaxPlayers )
		return FMRES_IGNORED

	new sClassName[11], sentry
	pev ( iHitEnt, pev_classname, sClassName, charsmax ( sClassName ) )
	if ( equal ( sClassName, "sentry" ) )
	{
		sentry = iHitEnt
	}

	if ( !pev_valid ( sentry ))
		return FMRES_IGNORED
		
	new Float:health = entity_get_float ( sentry, EV_FL_health )

	if ( health <= 0 )
		return FMRES_IGNORED

	new CsTeams:team = GetSentryTeam ( sentry )

	if ( team != get_users_team_zp ( id ) )
		return FMRES_IGNORED

	new level = GetSentryLevel ( sentry )

	static tempStatusBuffer[192], tempStatusBuffer3[192]

	new OwnName[33]
	get_user_name ( GetSentryPeople ( sentry, OWNER ), OwnName, 32 )
	formatex ( tempStatusBuffer, charsmax ( tempStatusBuffer ), "%L",id, "SG_HUD_SENTRY_1", OwnName, floatround(health), level + 1, g_iKillSentry[sentry])

	if(level + 1 > 3){
	if(g_SentryMode[sentry] == 1 ){
		formatex ( tempStatusBuffer3, charsmax ( tempStatusBuffer3 ), "%L",id ,"SG_HUD_MODE_1")
	}else if(g_SentryMode[sentry] == 2){
			formatex ( tempStatusBuffer3, charsmax ( tempStatusBuffer3 ), "%L",id ,"SG_HUD_MODE_2")
	}else if(g_SentryMode[sentry] == 3){
			formatex ( tempStatusBuffer3, charsmax ( tempStatusBuffer3 ), "%L",id ,"SG_HUD_MODE_3")
		}
	}
	
	if( get_users_team_zp( id ) == 1 ){
		set_dhudmessage ( 255, 85, 0, -1.0, 0.35, 0, 0.0, 0.6, 0.0, 0.0 )
	}else if( get_users_team_zp( id ) == 2 ){
		set_dhudmessage ( 0, 85, 255, -1.0, 0.35, 0, 0.0, 0.6, 0.0, 0.0 )
	}
	
	show_dhudmessage(id, tempStatusBuffer)
		
	if(level + 1 == 4){
		show_dhudmessage(id, tempStatusBuffer3)
	}
	new Float:Health
	pev(sentry, pev_health, Health)
	new Float:Max=g_HEALTHS[level]
	if(Health<Max){	
		if(level + 1 < 4){
			show_dhudmessage(id, "%L", id, "SG_REM_1")
		}else{
			show_dhudmessage(id, "%L", id, "SG_REM_2")
		}
			
	}
	return FMRES_IGNORED
}

// прикосновение к пушке игрока
public fw_TouchSentry ( sentry, player )
{
	SentryUpgrade ( player, sentry, 0);
	g_OffSpam[player] = 0;
	
	remove_task(TASK_LEAVE_ID + player)
	set_task(TASK_CHECK_ACCU, "_player_untouch_sentry", player + TASK_LEAVE_ID);
}

public _player_untouch_sentry(pId)
{
	pId -= TASK_LEAVE_ID;
	if(!is_user_alive(pId))
		return;

	g_OffSpam[pId] = 1;
}

ammo_hud(id, sw)
{
	if(is_user_bot(id)||!is_user_alive(id)||!is_user_connected(id)) 
			return

	new s_sprite[33]
	format(s_sprite, 32, "number_%d", sentries_num[id])
	if(sw)
	{
		message_begin( MSG_ONE, gMsgID, {0,0,0}, id )
		write_byte( 1 ) // status
		write_string( s_sprite ) // sprite name
		write_byte( 250 ) // red
		write_byte( 250 ) // green
		write_byte( 250 ) // blue
		message_end()
	}
	else 
	{
		message_begin( MSG_ONE, gMsgID, {0,0,0}, id )
		write_byte( 0 ) // status
		write_string( s_sprite ) // sprite name
		write_byte( 250 ) // red
		write_byte( 250 ) // green
		write_byte( 250 ) // blue
		message_end()
	}
	if(sentries_num[id] <= 0)
	{
		message_begin( MSG_ONE, gMsgID, {0,0,0}, id )
		write_byte( 0 ) // status
		write_string( s_sprite ) // sprite name
		write_byte( 250 ) // red
		write_byte( 250 ) // green
		write_byte( 250 ) // blue
		message_end()
	}	
}

stock ChatColor(const id, const input[], any:...)
{
		new count = 1, players[32]
		static msg[191]
		vformat(msg, 190, input, 3)
	   
		replace_all(msg, 190, "!g", "^4") // Green Color
		replace_all(msg, 190, "!y", "^1") // Default Color
		replace_all(msg, 190, "!team", "^3") // Team Color
		replace_all(msg, 190, "!team2", "^0") // Team2 Color
	   
		if (id) players[0] = id; else get_players(players, count, "ch")
		{
				for (new i = 0; i < count; i++)
				{
						if (is_user_connected(players[i]))
						{
								message_begin(MSG_ONE_UNRELIABLE, get_user_msgid("SayText"), _, players[i])
								write_byte(players[i]);
								write_string(msg);
								message_end();
						}
				}
		}
}

bool:IsInSphere ( id )
{
	if ( !is_user_alive ( id ) )
		return false

	new ent = -1 
	while ( ( ent = engfunc ( EngFunc_FindEntityByString, ent, "classname", "campo_grenade_forze" ) ) > 0 )
	{
		new iOwner = pev ( ent, pev_owner )

		if ( get_users_team_zp ( id ) != get_users_team_zp ( iOwner ) )
			continue

		new Float:fOrigin[3]
		pev ( ent, pev_origin, fOrigin )
		new iPlayer = -1
		while ( ( iPlayer = engfunc ( EngFunc_FindEntityInSphere, iPlayer, fOrigin, 68.0 ) ) != 0 )
		{
			if ( iPlayer == id )
				return true
		}
	}
	return false
}

//
// Launch rocket from 4lvl sentry
//	data[2]
//		0 - sentry id
//		1 - side	// 0 - right, 1 - left
//
public ShootRockets(data[2]){
	new sentry = data[0]

	if ( !pev_valid ( sentry ) )
		return

	new side = data[1]
	
	new Float:rocketOrigin[3],Float:rocketAngles[3]
	
	entity_get_vector(sentry,EV_VEC_angles,rocketAngles)
	engfunc(EngFunc_MakeVectors,rocketAngles)
	
	new Float:vecForward[3],Float:vecRight[3],Float:vecUp[3]
	
	get_global_vector(GL_v_forward,vecForward)
	xs_vec_mul_scalar(vecForward,20.0,vecForward)
	
	get_global_vector(GL_v_right,vecRight)
	xs_vec_mul_scalar(vecRight,side ? 8.0 : -8.0,vecRight) // right or left rocket
	
	get_global_vector(GL_v_up,vecUp)
	xs_vec_mul_scalar(vecUp,30.0,vecUp)
	
	entity_get_vector(sentry,EV_VEC_origin,rocketOrigin)
	xs_vec_add(rocketOrigin,vecForward,rocketOrigin)
	xs_vec_add(rocketOrigin,vecRight,rocketOrigin)
	xs_vec_add(rocketOrigin,vecUp,rocketOrigin)
	
	// shot rocket
	CreateRocket(sentry,rocketOrigin,rocketAngles,GetSentryPeople(sentry,TARGET))
	
	data[1] = 1
	
}

//
// Launch RPG rocket
//	sentry - sentry id
//	origin - rocket origin
//	angles - sentry angles
//	traget - rocket target id
//
CreateRocket(sentry,Float:origin[3],Float:angles[3],target){
	new rocket = create_entity("info_target")
	entity_set_string(rocket,EV_SZ_classname,"rpg_rocket")
	entity_set_int(rocket,EV_INT_movetype,MOVETYPE_FLY)
	entity_set_int(rocket,EV_INT_solid,SOLID_BBOX)
	entity_set_edict(rocket,EV_ENT_owner,sentry)
	entity_set_edict(rocket,EV_ENT_euser4,GetSentryPeople(sentry,OWNER))
	entity_set_size(rocket,Float:{-2.0,-2.0,-2.0},Float:{2.0,2.0,2.0})
	entity_set_origin(rocket,origin)
	
	new Float:targetOrigin[3]
	entity_get_vector(target,EV_VEC_origin,targetOrigin)
	angles[0] = -GetAngleOrigins(origin,targetOrigin)
	entity_set_model(rocket,Model_Rocket)
	entity_set_vector(rocket,EV_VEC_angles,angles)
	
	engfunc(EngFunc_MakeVectors,angles)
	
	new Float:vecVelocity[3]
	get_global_vector(GL_v_forward,vecVelocity)
	xs_vec_mul_scalar(vecVelocity,1000.0,vecVelocity)
	entity_set_vector(rocket,EV_VEC_velocity,vecVelocity)
	
	new red, blue
	
	switch(GetSentryTeam(sentry)){
		case 1:{
			red = 255
			blue = 42
		} case 2:{
			red = 42
			blue = 255
		}
	}
	
	message_begin(MSG_BROADCAST,SVC_TEMPENTITY)
	write_byte(TE_BEAMFOLLOW)
	write_short(rocket)
	write_short(g_sModelIndexMoroz)
	write_byte(5)
	write_byte(3)
	write_byte(red)
	write_byte(42)
	write_byte(blue)
	write_byte(255)
	message_end()
	
	set_task(0.05,"rocket_tracer", 1423 + rocket, _, _, "b" )
	emit_sound(sentry,CHAN_VOICE,Sound_rocet_1,1.0,0.5,0,PITCH_NORM)
	emit_sound(rocket,CHAN_VOICE,Sound_rocet_2,1.0,0.5,0,PITCH_NORM)
}

public rocket_tracer(task_id)
{
	new ent = task_id - 1423
	if(!pev_valid(ent)){
		remove_task(task_id)
		return
	}
	new Float: vecEnd[3]
	entity_get_vector(ent,EV_VEC_origin,vecEnd)
	message_begin_f(MSG_PVS,SVC_TEMPENTITY,vecEnd,0)
	write_byte(TE_SPARKS)
	write_coord_f(vecEnd[0])
	write_coord_f(vecEnd[1])
	write_coord_f(vecEnd[2])
	message_end()
	
}

public fw_RpgTouch(rocket,ent){
	new Float:origin[3],Float:angles[3],Float:vecPlaneNormal[3]
	entity_get_vector(rocket,EV_VEC_origin,origin)
	entity_get_vector(rocket,EV_VEC_angles,angles)
	
	engfunc(EngFunc_MakeVectors,angles)
	get_global_vector(GL_v_forward,angles)
	xs_vec_mul_scalar(angles,9999.0,angles)
	xs_vec_add(origin,angles,angles)
	engfunc(EngFunc_TraceLine,origin,angles,0,rocket,0)
	
	get_tr2(0,TR_vecEndPos,origin)
	get_tr2(0,TR_vecPlaneNormal,vecPlaneNormal)
	
	xs_vec_mul_scalar(vecPlaneNormal,8.0,vecPlaneNormal)
	xs_vec_add(origin,vecPlaneNormal,origin)
	
	message_begin_f(MSG_PVS,SVC_TEMPENTITY,origin,0)
	write_byte(TE_EXPLOSION)
	write_coord_f(origin[0])
	write_coord_f(origin[1])
	write_coord_f(origin[2])
	write_short(g_sModelIndexFireball)
	write_byte(20)
	write_byte(15)
	write_byte(0)
	message_end()
	
	
	shit_radiusdamage(rocket,origin)
	
	emit_sound(rocket,CHAN_VOICE,Sound_rocet_3,1.0,ATTN_NORM,SND_STOP,0)
	
	remove_entity(rocket)
}



// this very bad method
stock shit_radiusdamage(rocket,Float:origin_[3]) {
	new origin[3]
	FVecIVec(origin_, origin)
	
	new attacker = entity_get_edict(rocket,EV_ENT_euser4)
	
	if(!is_user_connected(attacker))
		return


	new Float:playerOrigin[3], Float:distance, Float:flDmgToDo, Float:dmgbase = get_pcvar_float(g_Cvar_mode_rpg[1])
	for (new i = 1; i <= g_iMaxPlayers; i++) {
		if (!is_user_alive(i) || get_user_godmode(i) || get_users_team_zp(i) == get_users_team_zp(attacker)) 
			continue

		entity_get_vector(i, EV_VEC_origin, playerOrigin)
		distance = vector_distance(playerOrigin, origin_)
		if (distance <= get_pcvar_float(g_Cvar_mode_rpg[0])) {
			flDmgToDo = dmgbase - (dmgbase * (distance / get_pcvar_float(g_Cvar_mode_rpg[0])))
			
			// zemletryasenie!!111
			Util_ScreenShake(i,0.5,16.0,16.0)
			rocket_damagetoplayer(rocket,origin_,i,flDmgToDo)
		}
	}
}
// ScreenShake 

stock Util_ScreenShake(id, Float:duration, Float:frequency, Float:amplitude)
{
	static ScreenShake = 0;
	if( !ScreenShake )
	{
		ScreenShake = get_user_msgid("ScreenShake");
	}
	message_begin( id ? MSG_ONE_UNRELIABLE : MSG_BROADCAST, ScreenShake, _, id);
	write_short( FixedUnsigned16( amplitude, 1<<12 ) ); // shake amount
	write_short( FixedUnsigned16( duration, 1<<12 ) ); // shake lasts this long
	write_short( FixedUnsigned16( frequency, 1<<8 ) ); // shake noise frequency
	message_end();
}

// урон игроку
stock rocket_damagetoplayer(rocket, Float:sentryOrigin[3], target, Float:dmg) {
	new sentry = entity_get_edict(rocket,EV_ENT_owner)

	if ( !is_valid_ent ( sentry ) )
		return

	new sentryLevel = GetSentryLevel(sentry)
	
	
	
	new newHealth = get_user_health(target) - floatround(dmg)

	if (newHealth <= 0) {
		new targetFrags = get_user_frags(target) + 1
		new owner = GetSentryPeople(sentry, OWNER)
		
		if(!is_user_connected(owner))
			return
		
		new ownerFrags = get_user_frags(owner) + 1
		set_user_frags(target, targetFrags) // otherwise frags are subtracted from victim for dying (!!)
		set_user_frags(owner, ownerFrags)
		
		new contributors[4]
		contributors[0] = owner
		contributors[1] = GetSentryPeople(sentry, UPGRADER_1)
		contributors[2] = GetSentryPeople(sentry, UPGRADER_2)
		contributors[3] = GetSentryPeople(sentry, UPGRADER_3)
		
		for(new i ; i < sizeof contributors ; i++){
			if(!contributors[i])
				continue
				
			if(!is_user_connected(contributors[i]) || get_users_team_zp(contributors[i]) != get_users_team_zp(contributors[0])){
				switch(i){ // yao face
					case 1: SetSentryPeople(sentry,UPGRADER_1,0)
					case 2: SetSentryPeople(sentry,UPGRADER_2,0)
					case 3: SetSentryPeople(sentry,UPGRADER_3,0)
				}
				
				continue
			}
			
			// izvini 4yvak, no menya nakrilo
			set_user_money_s(contributors[i],
				clamp(
					get_user_money_s(contributors[i]) + (i == 0 ? SENTRYOWNERAWARD : SENTRYASSISTAWARD),
					0,
					9999999
				)
			)
		}

		// ny ebatb kakoy frag
		message_begin(MSG_ALL, g_msgDeathMsg, {0, 0, 0} ,0)
		write_byte(owner)
		write_byte(target)
		write_byte(0)
		write_string("sentry gun")
		message_end()

		scoreinfo_update(owner, ownerFrags, cs_get_user_deaths(owner), int:get_users_team_zp(owner))
		set_msg_block(g_msgDeathMsg, BLOCK_ONCE)
	}

	set_user_health(target, newHealth)

	message_begin(MSG_ONE_UNRELIABLE, g_msgDamage, {0,0,0}, target)
	write_byte(g_DMG[sentryLevel])
	write_byte(g_DMG[sentryLevel])
	write_long(DMG_BLAST)
	write_coord(floatround(sentryOrigin[0]))
	write_coord(floatround(sentryOrigin[1]))
	write_coord(floatround(sentryOrigin[2]))
	message_end()
}

stock FixedUnsigned16( Float:value, scale )
{
	new output;

	output = floatround(value * scale);
	if ( output < 0 )
		output = 0;
	if ( output > 0xFFFF )
		output = 0xFFFF;

	return output;
}

Float:GetAngleOrigins(Float:fOrigin1[3], Float:fOrigin2[3] )
{
	new Float:fVector[3];
	new Float:fAngle[3];
	new Float:fLineAngle;
	
	xs_vec_sub(fOrigin2, fOrigin1, fVector);
	vector_to_angle(fVector, fAngle);
	
	if( fAngle[0] > 90.0 )
		fLineAngle = -(360.0 - fAngle[0]);
	else
		fLineAngle = fAngle[0];
	
	return fLineAngle;
} 


public ShootFreezing(data[])
{
	new sentry = data[0]
	if (pev_valid ( sentry ) )
	{
		//Получаем на кого наведена пушка
		new target = GetSentryPeople(sentry,TARGET)
			
		new Float:freezOrigin[3],Float:freezAngles[3]
		//Считаем точку откуда рисовать луч
		entity_get_vector(sentry,EV_VEC_angles,freezAngles)
		engfunc(EngFunc_MakeVectors,freezAngles)
			
		new Float:vecForward[3],Float:vecRight[3],Float:vecUp[3]
			
		get_global_vector(GL_v_forward,vecForward)
		xs_vec_mul_scalar(vecForward,20.0,vecForward)
			
		get_global_vector(GL_v_right,vecRight)
		//xs_vec_mul_scalar(vecRight,side ? 8.0 : -8.0,vecRight) // right or left rocket
			
		get_global_vector(GL_v_up,vecUp)
		xs_vec_mul_scalar(vecUp,30.0,vecUp)
			
		entity_get_vector(sentry,EV_VEC_origin,freezOrigin)
		xs_vec_add(freezOrigin,vecForward,freezOrigin)
		xs_vec_add(freezOrigin,vecRight,freezOrigin)
		xs_vec_add(freezOrigin,vecUp,freezOrigin)
			
		//set_user_health( target, get_user_health( target ) - 1 )
			
		new Float:targetOrigin[3];
		entity_get_vector(target,EV_VEC_origin,targetOrigin)
			
		new OriginEnd[3],OriginStr[3];
		FVecIVec(freezOrigin,OriginStr)
		FVecIVec(targetOrigin,OriginEnd)
			
			//Еффект луча от пушки до цели.
		message_begin(MSG_BROADCAST, SVC_TEMPENTITY);
		write_byte(TE_BEAMPOINTS);
		write_coord(OriginStr[0]);	 //Стартовая точка x
		write_coord(OriginStr[1]);	 //Стартовая точка y
		write_coord(OriginStr[2] - 12);	 //Стартовая точка z
		write_coord(OriginEnd[0]);	 //Конечная точка x
		write_coord(OriginEnd[1]);	 //Конечная точка y
		write_coord(OriginEnd[2]);	 //Конечная точка z
		write_short(g_sModelIndexFireball2);		 //Индекс спрайта
		write_byte(0);				 //Стартовый кадр
		write_byte(1);				 //Скорость анимации
		write_byte(1);			//Время существования
		write_byte(random_num(10, 50));	 //Толщина луча
		write_byte(random_num(10, 25));	 //Искажение
		write_byte(random_num(0, 255));			//Цвет красный
		write_byte(random_num(0, 255));			//Цвет зеленый
		write_byte(random_num(0, 255));			//Цвет синий
		write_byte(1000);			//Яркость
		write_byte(0);				//...
		message_end();
			
			
			
		emit_sound(sentry,CHAN_VOICE,Sound_tok,1.0,0.5,0,PITCH_NORM)
		emit_sound(sentry,CHAN_VOICE,Sound_tok_2,1.0,0.5,0,PITCH_NORM)
	}
}

new cub_player[33]

public ShootFreezing_cub(data[])
{
	new sentry = data[0]
	if (pev_valid ( sentry ) )
	{
		//Получаем на кого наведена пушка
		new target = GetSentryPeople(sentry,TARGET)
		
		
		if(!(pev(target, pev_flags) & FL_FROZEN))
		{
			entity_set_float(sentry,SENTRY_FREEZ_TIME,get_gametime() +  get_pcvar_float(g_Cvar_mode_led[0])) //Задержка до следущего замораживания.
			
			new Float:freezOrigin[3],Float:freezAngles[3]
			//Считаем точку откуда рисовать луч
			entity_get_vector(sentry,EV_VEC_angles,freezAngles)
			engfunc(EngFunc_MakeVectors,freezAngles)
			
			new Float:vecForward[3],Float:vecRight[3],Float:vecUp[3]
			
			get_global_vector(GL_v_forward,vecForward)
			xs_vec_mul_scalar(vecForward,20.0,vecForward)
			
			get_global_vector(GL_v_right,vecRight)
			//xs_vec_mul_scalar(vecRight,side ? 8.0 : -8.0,vecRight) // right or left rocket
			
			get_global_vector(GL_v_up,vecUp)
			xs_vec_mul_scalar(vecUp,30.0,vecUp)
			
			entity_get_vector(sentry,EV_VEC_origin,freezOrigin)
			xs_vec_add(freezOrigin,vecForward,freezOrigin)
			xs_vec_add(freezOrigin,vecRight,freezOrigin)
			xs_vec_add(freezOrigin,vecUp,freezOrigin)
		
			new Float:targetOrigin[3];
			entity_get_vector(target,EV_VEC_origin,targetOrigin)
			
			new OriginEnd[3],OriginStr[3];
			FVecIVec(freezOrigin,OriginStr)
			FVecIVec(targetOrigin,OriginEnd)
			
			//Еффект луча от пушки до цели.
			message_begin(MSG_BROADCAST, SVC_TEMPENTITY);
			write_byte(TE_BEAMPOINTS);
			write_coord(OriginStr[0]);	 //Стартовая точка x
			write_coord(OriginStr[1]);	 //Стартовая точка y
			write_coord(OriginStr[2] - 12);	 //Стартовая точка z
			write_coord(OriginEnd[0]);	 //Конечная точка x
			write_coord(OriginEnd[1]);	 //Конечная точка y
			write_coord(OriginEnd[2]);	 //Конечная точка z
			write_short(g_sModelIndexMoroz);		 //Индекс спрайта
			write_byte(0);				 //Стартовый кадр
			write_byte(1);				 //Скорость анимации
			write_byte(7);			//Время существования
			write_byte(70);	 //Толщина луча
			write_byte(7);	 //Искажение
			write_byte(42);			//Цвет красный
			write_byte(212);			//Цвет зеленый
			write_byte(255);			//Цвет синий
			write_byte(1000);			//Яркость
			write_byte(0);				//...
			message_end();
			
			//Проверяем положение игрока.
			new bDucking = !!(entity_get_int(target, EV_INT_flags) & FL_DUCKING);
			targetOrigin[2]  -= bDucking ? 27.0 : 36.0; //Считаем координаты в которых устанавливать модель.
			
			new pEnt = create_entity("info_target");
			cub_player[target] = pEnt
			if (is_valid_ent(pEnt))
			{	
				entity_set_model(pEnt, FROZEN_CUBE)
				dllfunc(DLLFunc_Spawn, pEnt);

				entity_set_int( pEnt, DATA_CUBE_OWNER , target );
				entity_set_vector(pEnt, EV_VEC_origin, targetOrigin);

				entity_set_int(pEnt, EV_INT_solid, SOLID_NOT);

				if (bDucking)
					entity_set_size(pEnt, Float:{ -24.0, -24.0, 10.0 }, Float:{ 24.0, 24.0, 68.0 });
				else
					entity_set_size(pEnt, Float:{ -24.0, -24.0, 0.0 }, Float:{ 24.0, 24.0, 78.0 });

				entity_set_float(pEnt, EV_FL_takedamage, DAMAGE_NO);

				entity_set_int(pEnt, EV_INT_skin, (get_users_team_zp(target) == CS_TEAM_CT) ? 1 : 0);
				entity_set_int(pEnt, EV_INT_body, bDucking);

				
				set_pev(target, pev_flags, pev(target, pev_flags) | FL_FROZEN)
				set_task(get_pcvar_float(g_Cvar_mode_led[1]),"UnFreez",pEnt+FREEZ_TASK_ID)
			}
		}
	}
}

public UnFreez(TaskID)
{
	new pEnt = TaskID - FREEZ_TASK_ID;
	if(is_valid_ent(pEnt))
	{
		new iOwner = entity_get_int(pEnt, DATA_CUBE_OWNER);
		remove_entity(pEnt);
		set_pev(iOwner, pev_flags, pev(iOwner, pev_flags) & ~FL_FROZEN)
		cub_player[iOwner] = pust
	}
}

public onDeath(id)
{ 
	new iVictim = read_data(2) 
	if(is_valid_ent(cub_player[iVictim]))
	{
		remove_entity(cub_player[iVictim]);
		set_pev(iVictim, pev_flags, pev(iVictim, pev_flags) & ~FL_FROZEN)
		remove_task( cub_player[iVictim]+FREEZ_TASK_ID );
		cub_player[iVictim] = pust
	}
	return PLUGIN_CONTINUE 
} 

stock set_anim(ent, sequence) 
{
	set_pev(ent, pev_sequence, sequence)
	set_pev(ent, pev_animtime, halflife_time())
	set_pev(ent, pev_framerate, 3.5)
}

stock get_user_money_s(id)
{
	if(get_pcvar_num(is_sentry_ammo) == 0){
		return cs_get_user_money(id)
	}else if(get_pcvar_num(is_sentry_ammo) == 1){
		return zp_get_user_ammo_packs(id)
	}else if(get_pcvar_num(is_sentry_ammo) == 2){
		return zp_cs_get_user_money(id)
	}
	return 0
}

stock set_user_money_s(id, num)
{
	if(get_pcvar_num(is_sentry_ammo) == 0){
		cs_set_user_money(id, num)
	}else if(get_pcvar_num(is_sentry_ammo) == 1){
		zp_set_user_ammo_packs(id, num)
	}else if(get_pcvar_num(is_sentry_ammo) == 2){
		zp_cs_set_user_money(id, num)
	}
}

stock get_users_team_zp(const id){
	if(get_pcvar_num(is_mod_zp) == 1){
		if(cs_get_user_team(id) == 3) return 3
		
		if(zp_get_user_zombie(id)){
			return 1
		}else{
			return 2
		}
	}else{
		return cs_get_user_team(id)
	}

	return 0
}
