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

#define message_begin_f(%0,%1,%2,%3)	engfunc(EngFunc_MessageBegin,%0,%1,%2,%3)
#define write_coord_f(%0)		engfunc(EngFunc_WriteCoord,%0)

#define PEV_NEXT 0.5
#define PLUGIN_NUM		332
#define VIP_FLAG ADMIN_LEVEL_A

#define Sprite_son "sprites/nova/robot/sleep_2.spr"

new g_mdl_OFFLINE, g_mdl_CT, g_mdl_T, g_mdl_IPHON
new MODEL_OFFLINE[90], MODEL_CT[90], MODEL_T[90], MODEL_IPHON[90]



#define ACTIVE pev_iuser1
#define TYPE_SHOOT pev_iuser2
#define STATE pev_iuser3
#define ROCKETS_COUNT pev_iuser4

#define DMG_BULLET				(1<<1)	// shot
#define DMG_BLAST				(1<<6)	// explosive blast damage


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|MENU_KEY_0
new g_Entity_robo
new g_ent[33]
new g_szConfigFile[128];
new g_iCvar[20]

new g_MenuOpen[33] 

new g_UronKill[300]


new g_sprite_son

new g_robo_next[500]
new g_robo_gun[500]

new g_msgDamage
new g_msgDeathMsg
new g_msgScoreInfo


new expSpr

new g_player_robot[33] = 0

public plugin_init()
{
	register_clcmd("amx_spawn_robot", "clcmd_open_menu")
	register_dictionary("nv_robot.txt");
	register_menu("RoboMenu", keys, "robo_menu")
	register_menu("TurretMenu", keys, "turret_menu")
	register_forward(FM_CmdStart,"fm_cmdstart");
	
	register_touch("RobotTurret", "player", "touch_player")
	
	register_think("RobotTurret", "think_turret")
	
	RegisterHam(Ham_TakeDamage, "func_breakable", "ham_takedamage", 0)
	
	
	g_msgDamage = get_user_msgid("Damage")
	g_msgDeathMsg = get_user_msgid("DeathMsg")
	g_msgScoreInfo = get_user_msgid("ScoreInfo")
	
	g_iCvar[0]=register_cvar("r_health_1", "1000")
	g_iCvar[1]=register_cvar("r_health_2", "2000")
	g_iCvar[2]=register_cvar("r_health_3", "5000")
	g_iCvar[3]=register_cvar("r_time_capture", "10")
	g_iCvar[4]=register_cvar("r_reward", "500")
	g_iCvar[5]=register_cvar("r_cost_up", "1500")
	g_iCvar[6]=register_cvar("r_num_ply", "3")
	g_iCvar[7]=register_cvar("r_distanze", "250.0")
	g_iCvar[8]=register_cvar("r_dmg", "5")
	g_iCvar[9]=register_cvar("r_min_player", "10")
	g_iCvar[10]=register_cvar("r_dmg_nag", "150")
	g_iCvar[11]=register_cvar("r_rew_phone", "1")
	g_iCvar[12]=register_cvar("r_sprite", "1")
	g_iCvar[13]=register_cvar("r_avto_death", "0.5")
	g_iCvar[14]=register_cvar("r_avto_d_max", "100")
	g_iCvar[15]=register_cvar("r_dis_rew", "150.0")
	
}

public plugin_cfg()
{
	g_Entity_robo = engfunc(EngFunc_AllocString, "func_breakable")
	
	load_flags()
	
	new file[128]; get_localinfo("amxx_configsdir",file,63)
	format(file, 127, "%s/nova/robot_turret.cfg", file)
	if(file_exists(file)) server_cmd("exec %s", file), server_exec()
}

new Float:buttons_is[33]

public fm_cmdstart(id, uc_handle, seed) {
	if(buttons_is[id]>get_gametime()) return
	if(!is_user_alive(id)) return
	new buttons = get_uc(uc_handle,UC_Buttons)

	if(buttons & IN_USE){
		new ent, body
		get_user_aiming(id, ent, body, floatround(get_pcvar_float(g_iCvar[15])) - 25)
		
		static ClassName[32]
		pev(ent, pev_classname, ClassName, charsmax(ClassName))
		if (equal(ClassName, "RobotTurret"))
		{
			buttons_is[id]=get_gametime()+1.0
			if(pev(ent, ACTIVE)){
				g_ent[id]=ent
				if(fm_cs_get_user_team(id)!=pev(ent, pev_body)) return
				return
			}
	
			if(pev(ent, ROCKETS_COUNT)) return
	
	
			if(get_playersnum() < get_pcvar_num(g_iCvar[9])){
				set_dhudmessage(200,20, 20, -1.0, 0.60, 0, 0.0, 1.0, 0.01, 0.01)
				show_dhudmessage(id, "%L", id, "R_MIN_PLAYER")
			}else{
				if(g_player_robot[id] + 1 > get_pcvar_num(g_iCvar[6])){
					ColorChat( id,BLUE, "%L", id, "R_MAX_PLAYER" ,get_pcvar_num(g_iCvar[6]) )
					return
				}else{  
					set_pev(ent, ROCKETS_COUNT, get_pcvar_num(g_iCvar[3]))
					set_dhudmessage(0,255, 0, -1.0, 0.7, 0, 0.0, 1.0, 0.01, 0.01)
					show_dhudmessage(id, "%L", id, "R_CAPTURE_START", pev(ent, ROCKETS_COUNT))
				}
			}  
			new info[2]
			info[0] = ent
			info[1] = id
	
			set_task(1.0, "flag_refresh", ent+88554, info, 2, "b")
		}
	}
}

public client_connect(id)
{
	g_MenuOpen[id] = 0 
	g_player_robot[id] = 0
}

public load_flags()
{
	new szMapName[32]
	get_mapname(szMapName, 31)
	strtolower(szMapName)
	
	formatex(g_szConfigFile, 127, "addons/amxmodx/configs/robots_m")
	
	if( !dir_exists(g_szConfigFile)) 
	{
		mkdir(g_szConfigFile)
		format(g_szConfigFile, 127, "%s/%s.txt", g_szConfigFile, szMapName )
		return
	}
	
	format(g_szConfigFile, 127, "%s/%s.txt", g_szConfigFile, szMapName)
	if(!file_exists(g_szConfigFile)) 
	{
		fopen(g_szConfigFile, "at")
		return
	}
	
	new iFile = fopen( g_szConfigFile, "rt" )
	if(!iFile) return
	
	new x[16], y[16], z[16], szData[charsmax(x) + charsmax(y) + charsmax(z)]
	
	new Float:vOrigin[3]
	
	while(!feof(iFile)) 
	{
		fgets(iFile, szData, charsmax(szData))
		trim(szData)
		
		if(!szData[0]) continue;
		
		parse(szData, x, 15, y, 15, z, 15)
		
		vOrigin[0] = str_to_float(x)
		vOrigin[1] = str_to_float(y)
		vOrigin[2] = str_to_float(z)
		
		set_robot(vOrigin)
	}
	
	fclose( iFile )
}

public plugin_precache()
{
	g_mdl_OFFLINE = 0
	g_mdl_CT = 0
	g_mdl_T = 0
	g_mdl_IPHON = 0
	
	new iFile = fopen("addons/amxmodx/configs/nova/robot_turret.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_r_phone")){	
				g_mdl_IPHON = 1
				formatex(MODEL_IPHON, charsmax(MODEL_IPHON), "%s", Model);
			}			
			if(equal(Imeil, "mdl_r_offline")){	
				g_mdl_OFFLINE = 1
				formatex(MODEL_OFFLINE, charsmax(MODEL_OFFLINE), "%s", Model);
			}
			if(equal(Imeil, "mdl_r_ct")){	
				g_mdl_CT = 1
				formatex(MODEL_CT, charsmax(MODEL_CT), "%s", Model);
			}
			if(equal(Imeil, "mdl_r_tt")){	
				g_mdl_T = 1
				formatex(MODEL_T, charsmax(MODEL_T), "%s", Model);
			}
		}
	}
	if(g_mdl_OFFLINE == 0){
		formatex(MODEL_OFFLINE, charsmax(MODEL_OFFLINE), "models/rg_capture_sleep.mdl");
	}
	if(g_mdl_CT == 0){
		formatex(MODEL_CT, charsmax(MODEL_CT), "models/rg_capture_ct.mdl");
	}
	if(g_mdl_T == 0){
		formatex(MODEL_T, charsmax(MODEL_T), "models/rg_capture_t.mdl");
	}
	if(g_mdl_IPHON == 0){
		formatex(MODEL_IPHON, charsmax(MODEL_IPHON), "models/iphon.mdl");
	}
	
	
	precache_model(MODEL_OFFLINE)
	precache_model(MODEL_CT)
	precache_model(MODEL_T)
	
	precache_model(MODEL_IPHON)
	
	
	precache_sound("hassault/hw_spindown.wav")
	precache_sound("dmsentries/fire.wav")
	precache_sound("nova/zaxwat.wav")
	
	precache_sound("test/rg_build_1.wav")
	
	g_sprite_son = precache_model(Sprite_son)
	expSpr = precache_model("sprites/zerogxplode.spr")
	
}

public MenuOpen_zbros(id)
{
	g_MenuOpen[id] = 0
}

public clcmd_open_update(id)
{
	new money = cs_get_user_money(id)
	new menu[512], iLen
	new ent=g_ent[id]
	
	if(pev(ent, TYPE_SHOOT)>=2)return
	
	
	g_MenuOpen[id] = 1
	
	set_task( 1.0 ,"MenuOpen_zbros")
	
	iLen = formatex(menu[iLen], charsmax(menu) - iLen, "\yУлучшение робота^n\yТвои Деньги: \r%d$^n^n",money)
	
	if(pev(ent, TYPE_SHOOT)>=1 || cs_get_user_money(id) < get_pcvar_num(g_iCvar[5]))
		iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y2\r]\d Уровень [2] (Ракетный залп) \r[Нужно \y%d$ \r]",get_pcvar_num(g_iCvar[5]))
	else iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y2\r]\w Уровень \r[\w2\r] \r(\yРакетный залп\r) \y%d$",get_pcvar_num(g_iCvar[5]))
	
	
	if(get_user_flags(id) & VIP_FLAG)
	{
		if(pev(ent, TYPE_SHOOT)>=2 || cs_get_user_money(id) < get_pcvar_num(g_iCvar[5]))
			iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y3\r]\d Уровень [3] (Лазер) \r[Нужно \y%d$ \r],get_pcvar_num(g_iCvar[5])")
		else iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y3\r]\w Уровень \r[\w3\r] \r(\yЛазер\r) \y%d$", get_pcvar_num(g_iCvar[5]))
	}
	else
	{
		iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y3\r]\d Уровень [3] (Лазер) \r[Только VIP]")
	}
	
	iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n^n\y[\r0\y] \r[\wВыход\r]")
	
	show_menu(id, keys, menu, -1, "TurretMenu")
}

public turret_menu(id, key)
{
	if (key>2)return
	new ent=g_ent[id]

	if(pev(ent, TYPE_SHOOT)>=key)return
	
	if(cs_get_user_money(id)<get_pcvar_num(g_iCvar[5]))return
	
	if(key == 1)
	{
		cs_set_user_money(id, cs_get_user_money(id)-get_pcvar_num(g_iCvar[5]))
		
		set_pev(ent, TYPE_SHOOT, key)
		set_pev(ent, pev_health, get_pcvar_float(g_iCvar[key]))
		set_anim(ent, 1)
		set_pev(ent, pev_controller_0, 127)
		set_pev(ent, pev_controller_1, 127)
		set_pev(ent, pev_euser1, 0)
		set_pev(ent, pev_nextthink, get_gametime()+2.5)
		emit_sound(ent, CHAN_WEAPON, "test/rg_build_1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
	}
	
	if(key == 2) 
	{ 
		if(get_user_flags(id) & VIP_FLAG) 
		{ 
			cs_set_user_money(id, cs_get_user_money(id)-get_pcvar_num(g_iCvar[5]))
			set_pev(ent, TYPE_SHOOT, key)
	
			set_pev(ent, pev_health, get_pcvar_float(g_iCvar[key]))
			set_anim(ent, 1)
			set_pev(ent, pev_controller_0, 127)
			set_pev(ent, pev_controller_1, 127)
			set_pev(ent, pev_euser1, 0)
			set_pev(ent, pev_nextthink, get_gametime()+2.5)
			emit_sound(ent, CHAN_WEAPON, "test/rg_build_1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
		} 
		else 
		{	
			ColorChat( id,BLUE, "^3[^4Робот^3] Доступоно только^4 Админ/VIP!" )
			return
		}
	}
}

public clcmd_open_menu(id)
{
	if(!(get_user_flags(id) & ADMIN_RCON)) return

	new menu[512], iLen
	
	iLen = formatex(menu[iLen], charsmax(menu) - iLen, "\yУстановка роботов^n^n")	 
	iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y1\r]\w Поставить робота")
	/*iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y3\r]\w Удалить всех роботов")*/
	iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n\r[\y4\r]\w Удалить всех роботов")   
	iLen += formatex(menu[iLen], charsmax(menu) - iLen, "^n^n\r[\y0\r]\w Выход")
	
	show_menu(id, keys, menu, -1, "RoboMenu")
}

public robo_menu(id, key)
{
	switch(key)
	{
		case 0:
		{
			clcmd_open_menu(id)
			new Float:playerOrigin[3]
			entity_get_vector(id, EV_VEC_origin, playerOrigin)
			
			new Float:vNewOrigin[3]
			new Float:vTraceDirection[3]
			new Float:vTraceEnd[3]
			new Float:vTraceResult[3]
			velocity_by_aim(id, 64, vTraceDirection)
			vTraceEnd[0] = vTraceDirection[0] + playerOrigin[0]
			vTraceEnd[1] = vTraceDirection[1] + playerOrigin[1]
			vTraceEnd[2] = vTraceDirection[2] + playerOrigin[2]
			trace_line(id, playerOrigin, vTraceEnd, vTraceResult)
			vNewOrigin[0] = vTraceResult[0]
			vNewOrigin[1] = vTraceResult[1]
			vNewOrigin[2] = playerOrigin[2]
			
			if (point_contents(vNewOrigin) != CONTENTS_EMPTY || TraceCheckCollides(vNewOrigin, 24.0)) return
			
			new oloent=set_robot(vNewOrigin)
			Save_Flags(oloent)
		}
		case 2:
		{
		/*
			new eId, iBody;
			get_user_aiming(id, eId, iBody);
			
			new szClassName[15];
			entity_get_string(eId, EV_SZ_classname, szClassName, charsmax(szClassName));
			
			new Float:vOrigin[3]
			
			if(is_valid_ent(eId) && equal(szClassName, "RobotTurret"))
			{
				entity_get_origin(eId, vOrigin)	
			}
			
			new iFile = fopen( g_szConfigFile, "rt" )
			if(!iFile) return
			
			new x[16], y[16], z[16], szData[charsmax(x) + charsmax(y) + charsmax(z)]
			
			
			while(!feof(iFile)) 
			{
				fgets(iFile, szData, charsmax(szData))
				trim(szData)
				
				if(!szData[0]) continue;
				
				x = str_to_num(vOrigin[0])
				y = str_to_num(vOrigin[2])
				z = str_to_num(vOrigin[1])
				
				
			}
			fclose( iFile )
		*/
		}
		case 3:
		{
			clcmd_open_menu(id)
			if (file_exists(g_szConfigFile))
			delete_file(g_szConfigFile)
			new ent
			while((ent = find_ent_by_class(ent,"RobotTurret")) != 0)
			{
				if(is_valid_ent(ent))
				{
					remove_entity(ent)
				}
			}
		}

	}
}

Save_Flags(ent)
{
	new iFile = fopen(g_szConfigFile, "at")
	
	if(!iFile) return
	
	new Float:vOrigin[3]
	pev(ent, pev_origin, vOrigin)

	fprintf(iFile, "%f %f %f^n", vOrigin[0], vOrigin[1], vOrigin[2])
	fclose(iFile)
}

public set_robot(const Float:vNewOrigin[3])
{
	new i_Ent = engfunc(EngFunc_CreateNamedEntity, g_Entity_robo)
	if(!i_Ent) return 0

	engfunc(EngFunc_SetModel, i_Ent, MODEL_OFFLINE)
	
	entity_set_origin(i_Ent, vNewOrigin)
	
	set_pev(i_Ent, pev_solid, SOLID_BBOX)
	set_pev(i_Ent, pev_movetype, MOVETYPE_TOSS)

	engfunc(EngFunc_SetSize, i_Ent, Float:{ -24.0, -24.0, -0.0 }, Float:{ 24.0, 24.0, 40.0 })
	
	set_pev(i_Ent, pev_classname, "RobotTurret")
	
	set_pdata_int(i_Ent, 36, 6, 4)
	
	set_pev(i_Ent, ACTIVE, 0)
	set_pev(i_Ent, TYPE_SHOOT, 0)
	set_pev(i_Ent, pev_health, 100.0)
	set_pev(i_Ent, pev_takedamage, DAMAGE_NO)	
	
	set_pev(i_Ent, pev_controller_0, 127)
	set_pev(i_Ent, pev_controller_1, 127)
	
	set_pev(i_Ent, pev_deadflag, DEAD_NO)
	
	set_pev(i_Ent, pev_nextthink, get_gametime()+ PEV_NEXT ) 
	
	set_anim(i_Ent, 0)
	
	return i_Ent
}

public touch_player(ent, id)
{
}

public flag_refresh(const info[])
{	
	if(get_playersnum() < get_pcvar_num(g_iCvar[9]))
	{
		return
	}
	
	new ent=info[0]
	new id=info[1]
	
	if(!is_user_connected(id))
	{
		set_pev(ent, ROCKETS_COUNT, 0)
		remove_task(ent+88554)	
		return
	}
	
	new Float:flOrigin[3], Float:flOrigin2[3]
	pev(id, pev_origin, flOrigin)
	pev(ent, pev_origin, flOrigin2)
		
	new Float:flDistance = get_distance_f(flOrigin, flOrigin2) 
	
	if(flDistance>get_pcvar_float(g_iCvar[15])||!is_user_alive(id)){
		set_pev(ent, ROCKETS_COUNT, 0)
		remove_task(ent+88554)	
		set_dhudmessage(255,255,255, -1.0, 0.7, 0, 0.0, 1.1, 0.0, 0.0)
		show_dhudmessage(id, "%L", id, "R_CAPTURE_END")
		return
	}
	
	set_pev(ent, ROCKETS_COUNT, pev(ent, ROCKETS_COUNT)-1)
	
	set_dhudmessage(255,255,255, -1.0, 0.7, 0, 0.0, 1.1, 0.0, 0.0)
	show_dhudmessage(id, "%L", id, "R_CAPTURE", pev(ent, ROCKETS_COUNT))
	
	new plrClip, plrAmmo
	new plrWeapId
	
	set_pev(id, pev_viewmodel2, MODEL_IPHON )
	
	plrWeapId = get_user_weapon(id, plrClip , plrAmmo)
	
	if(get_pcvar_num(g_iCvar[11]) == 1)
	{
		if( plrWeapId != CSW_KNIFE)
		{
			engclient_cmd(id,"weapon_knife")
			set_pev(id, pev_viewmodel2, MODEL_IPHON )
		}
	}

	if(!pev(ent, ROCKETS_COUNT))
	{
		g_player_robot[id] = g_player_robot[id] + 1
		remove_task(ent+88554)	
		
		
		if(fm_cs_get_user_team(id)==1) engfunc(EngFunc_SetModel, ent, MODEL_T)	
		else engfunc(EngFunc_SetModel, ent, MODEL_CT)	
		engfunc(EngFunc_SetSize, ent, Float:{ -24.0, -24.0, -0.0 }, Float:{ 24.0, 24.0, 40.0 })
	
		set_anim(ent, 2)
		set_pev(ent, ACTIVE, 1)
		set_pev(ent, pev_controller_0, 127)
		set_pev(ent, pev_controller_1, 127)
		set_pev(ent, pev_takedamage, DAMAGE_YES)
		set_pev(ent, pev_fuser4, 0)
		set_pev(ent, pev_health, get_pcvar_float(g_iCvar[0]))
		set_pev(ent, pev_euser2, id)
		
		g_UronKill[ent] = 0
		g_robo_gun[ent] = 0
		
		emit_sound(ent, CHAN_WEAPON, "test/rg_build_1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
		set_pev(ent, pev_body, fm_cs_get_user_team(id))
		
	}
}

public client_putinserver(id)
{
	set_task(1.0, "Task_Informer", id+666)
}

public Task_Informer(taskid)
{
	new id=taskid-666
	
	set_task(1.0, "Task_Informer", taskid)
 
	if(!is_user_alive(id))return
	
	new target, body
	get_user_aiming(id, target, body, 9999)
	
	static ClassName[32]
	pev(target, pev_classname, ClassName, charsmax(ClassName))
	if (equal(ClassName, "RobotTurret")) 
	{
		
		if(pev(target, ACTIVE)==0){
		
			if(get_playersnum() < get_pcvar_num(g_iCvar[9]))
			{
				set_dhudmessage(200,20, 20, -1.0, 0.60, 0, 0.0, 1.0, 0.01, 0.01)
				show_dhudmessage(id, "%L", id, "R_MIN_PLAYER")
			}
		
			else if(pev(target, pev_deadflag)==DEAD_DYING){
				set_dhudmessage(200,20, 20, -1.0, 0.60, 0, 0.0, 1.0, 0.01, 0.01)
				show_dhudmessage(id, "%L", id, "R_STATUS_DEATH")
			}
			
			else if(pev(target, ROCKETS_COUNT)){
				set_dhudmessage(200, 200, 20, -1.0, 0.60, 0, 0.0, 1.0, 0.01, 0.01)
				show_dhudmessage(id, "%L", id, "R_STATUS_CAPTURE")
			}else{
				if(get_entity_distance(id,target) <= 128){
					set_dhudmessage(25, 25, 255, -1.0, -1.0, 0, 0.0, 1.0, 0.01, 0.01)
					show_dhudmessage(id, "%L", id, "R_STATUS_E")
				}else{
					set_dhudmessage(0, 255, 0, -1.0, 0.60, 0, 0.0, 1.0, 0.01, 0.01)
					show_dhudmessage(id, "%L", id, "R_STATUS_EXP")
				}
			}
			return
		}
		
		if(fm_cs_get_user_team(id)!=pev(target, pev_body)) return


		
		new Float:Health
		pev(target, pev_health, Health)
		new Name[32]
		get_user_name(pev(target, pev_euser2),Name,31)
		
		set_dhudmessage(0, 212, 255, -1.0, -1.0, 0, 0.0, 1.0, 0.01, 0.01)
		show_dhudmessage(id, "%L", id, "R_STATUS_INF", Name, g_UronKill[target], floatround(Health))
	}
}



stock fm_cs_get_user_team(id)
{
	if (pev_valid(id) != 2) return 0
	
	return get_pdata_int(id, 114, 5)
}

public client_disconnect( id )
{
	new iEnt
	while( ( iEnt = find_ent_by_class( iEnt, "RobotTurret") ) )
	{
		if(pev(iEnt, pev_euser2) == id)
		{
			set_anim(iEnt, 4)
			set_pev(iEnt, pev_deadflag, DEAD_DYING)	 
			set_pev(iEnt, pev_takedamage, DAMAGE_NO)			
			set_pev(iEnt, pev_movetype, MOVETYPE_TOSS)		  
			set_pev(iEnt, ACTIVE, 0)		
			set_pev(iEnt, TYPE_SHOOT, 0)		 
			set_pev(iEnt, pev_health, get_pcvar_float(g_iCvar[0]))		
			set_pev(iEnt, pev_euser1, 0)		
			set_pev(iEnt, pev_nextthink, get_gametime()+ PEV_NEXT)		 
			
			new Float:entorigin[3]
			pev( iEnt, pev_origin, entorigin )
			message_begin_f(MSG_PVS,SVC_TEMPENTITY,entorigin,0)
			write_byte(TE_EXPLOSION)
			write_coord_f(entorigin[0])
			write_coord_f(entorigin[1])
			write_coord_f(entorigin[2])
			write_short(expSpr)
			write_byte(20)
			write_byte(15)
			write_byte(0)
			message_end()
		}
	}

}

public ham_takedamage(victim, weapon, attacker, Float:damage, damagetype) 
{
	if(!pev_valid(victim)) return HAM_IGNORED
	
	static ClassName[32]
	pev(victim, pev_classname, ClassName, charsmax(ClassName))

	if (equal(ClassName, "RobotTurret")) 
	{
		if(!is_user_connected(attacker)||(fm_cs_get_user_team(attacker)==pev(victim, pev_body)))
			return HAM_SUPERCEDE
		
		new Float:g_Health
		pev(victim, pev_health, g_Health)
		
		if (g_Health <= damage) 
		{
			set_anim(victim, 4)
			
			set_pev(victim, pev_deadflag, DEAD_DYING)
			
			set_pev(victim, pev_takedamage, DAMAGE_NO)	
			
			set_pev(victim, pev_movetype, MOVETYPE_TOSS)
			
			set_pev(victim, ACTIVE, 0)
			
			set_pev(victim, TYPE_SHOOT, 0)
			
			set_pev(victim, pev_health, get_pcvar_float(g_iCvar[0]))
			
			set_pev(victim, pev_euser1, 0)
			
			set_pev(victim, pev_nextthink, get_gametime()+ PEV_NEXT) 
			
			emit_sound(victim, CHAN_WEAPON, "hassault/hw_spindown.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
			
			cs_set_user_money(attacker, cs_get_user_money(attacker)+get_pcvar_num(g_iCvar[4]))
			
			ColorChat( attacker,BLUE, "%L", attacker, "R_KILL", get_pcvar_num(g_iCvar[4]))
			
			g_player_robot[pev(victim, pev_euser2)] = g_player_robot[pev(victim, pev_euser2)]  - 1
			
			new Float:entorigin[3]
			pev( victim, pev_origin, entorigin )
			message_begin_f(MSG_PVS,SVC_TEMPENTITY,entorigin,0)
			write_byte(TE_EXPLOSION)
			write_coord_f(entorigin[0])
			write_coord_f(entorigin[1])
			write_coord_f(entorigin[2])
			write_short(expSpr)
			write_byte(20)
			write_byte(15)
			write_byte(0)
			message_end()

			return HAM_SUPERCEDE
		}
	}
	return HAM_IGNORED
}

public think_turret(ent)
{

		if(pev(ent, pev_deadflag)==DEAD_DYING)
		{
			engfunc(EngFunc_SetModel, ent, MODEL_OFFLINE)	
			engfunc(EngFunc_SetSize, ent, Float:{ -24.0, -24.0, -0.0 }, Float:{ 24.0, 24.0, 40.0 })
		
			set_anim(ent, 0)
			set_pev(ent, ACTIVE, 0)
			set_pev(ent, pev_controller_0, 127)
			set_pev(ent, pev_controller_1, 127)
			
			set_pev(ent, pev_deadflag, DEAD_NO)
			
			set_pev(ent, pev_nextthink, get_gametime()+ PEV_NEXT) 
		
			return
		}

		if(!pev(ent, ACTIVE))
		{
			set_pev(ent, pev_nextthink, get_gametime()+ PEV_NEXT)   
			if(get_pcvar_num(g_iCvar[12]) == 1)
			{
				new Float:entorigin[3]
				pev( ent, pev_origin, entorigin )
				
				new start_[3]
				FVecIVec(entorigin, start_)

				message_begin(MSG_BROADCAST, SVC_TEMPENTITY) 
				write_byte(TE_SPRITE)//говорим что хотим создать, в данном случае спрайт
				write_coord(start_[0])//х - координата
				write_coord(start_[1])//у - координата
				write_coord(start_[2] + 70)//z - координата
				write_short(g_sprite_son)// id спрайта
				write_byte(2) //масштаб
				write_byte(200)//яркость
				message_end()
			}
		}
		
		if(!pev(ent, ACTIVE))return
		
		new closestTarget = 0, Float:closestDistance, Float:distance, Float:closestOrigin[3], Float:playerOrigin[3]
		new Float:sentryOrigin[3], Float:hitOrigin[3], hitent
		entity_get_vector(ent, EV_VEC_origin, sentryOrigin)
		
		new Float:HealthT
		pev(ent, pev_health, HealthT)
		if(HealthT > get_pcvar_num(g_iCvar[14]))
		{
			HealthT-=get_pcvar_float(g_iCvar[13])
			set_pev(ent, pev_health, HealthT)
		}

		if(pev(ent, STATE))
		{
			if(pev(ent, pev_euser1))
			{
				new target=pev(ent, pev_euser1)
				
				if(IsInSphere ( target )){
					set_pev(ent, pev_euser1, 0)
					set_pev(ent, pev_nextthink, get_gametime()+ PEV_NEXT)
					return
				}
				new Float:targetOrigin[3]
				entity_get_vector(target, EV_VEC_origin, targetOrigin)
				
				
				new Float:fAngle[3]
				entity_get_vector ( ent, EV_VEC_angles, fAngle )
				new Float:x = targetOrigin[0] - sentryOrigin[0]
				new Float:z = targetOrigin[1] - sentryOrigin[1]

				new Float:fRadians = floatatan ( z/x, radian )
				fAngle[1] = fRadians * (180.0 / 3.141592654)
				if ( targetOrigin[0] < sentryOrigin[0] )
				fAngle[1] -= 180.0

				
				entity_set_float ( ent, EV_FL_fuser1, fAngle[1] )
				entity_set_vector ( ent, EV_VEC_angles, fAngle )
				
				new Float:RADIUS = 180.0
				new Float:degreeByte = RADIUS/256.0
				
				new Float:tilt = 127.0+(degreeByte*fAngle[1])
	
				new Float:h = (targetOrigin[2] - 25 ) - sentryOrigin[2]
				new Float:b = vector_distance(sentryOrigin, targetOrigin)
				fRadians = floatatan (h/b, radian)
				fAngle[0] = fRadians * (180.0 / 3.141592654)
	
				RADIUS = 360.0
				degreeByte = RADIUS/256.0
				tilt = 127.0-degreeByte * fAngle[0]
				
				new Float:fDistance
				fDistance = get_distance_f(targetOrigin, sentryOrigin)
				new Float:fSpeed = fDistance / 100 
		
				new Float:new_sentryOrigin[3]
				
				new_sentryOrigin[0] = (targetOrigin[0] - sentryOrigin[0]) /fSpeed
				new_sentryOrigin[1] = (targetOrigin[1] - sentryOrigin[1]) /fSpeed
				new_sentryOrigin[2] = ((targetOrigin[2] - 25) - sentryOrigin[2]) /fSpeed
				
				if(fDistance >= get_pcvar_float(g_iCvar[7]))
				{
					entity_set_vector(ent, EV_VEC_velocity, new_sentryOrigin)
					if(g_robo_next[ent] == 0) 
					{
						set_anim(ent, 3) 
						g_robo_next[ent] = 1
					}
				}
				if (entity_get_int(target, EV_INT_flags) & FL_DUCKING) targetOrigin[2] += 18.0

			
				
				
				if(is_user_alive(target)) {
					new hitent = trace_line(ent, sentryOrigin, targetOrigin, hitOrigin)
					if(hitent==target){
				
					
					switch(pev(ent, TYPE_SHOOT))
					{
						case 0:
						{
							new Float:TimeF
							pev(ent, pev_fuser1, TimeF)
							if(TimeF>get_gametime()){
							}
							else{
								set_pev(ent, pev_fuser1, get_gametime()+0.2)
								set_pev(ent, pev_iuser3, pev(ent, pev_iuser3)+1)
								
								if(fDistance <= get_pcvar_float(g_iCvar[7]))
								{
									set_pev(ent, pev_controller_0, floatround(tilt)) 
									set_pev(ent, pev_movetype, MOVETYPE_NONE)
								
									set_anim(ent, 9)	
									g_robo_next[ent] = 0								
									new Float:Health
									pev(target, pev_health, Health)

									sentry_damagetoplayer ( ent, sentryOrigin, target )
									
									emit_sound(ent, CHAN_WEAPON, "dmsentries/fire.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
									g_robo_gun[ent] = 1
									tracer(sentryOrigin, targetOrigin)
									if(Health <= 5) 
									{ 
										emit_sound(ent, CHAN_WEAPON, "hassault/hw_spindown.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
										set_pev(ent, pev_controller_0, 127)
									} 
									else 
									{
									}
								}
								else
								{
									set_pev(ent, pev_movetype, MOVETYPE_FLYMISSILE)
								}
								
							}
							set_pev(ent, pev_nextthink, get_gametime()+0.1)	
						}
						case 1:
						{
						}
						case 2:
						{	
						}
					}
					return
				}
				}
			}
			
		}



		for (new i = 1; i <= 32; i++) 
		{
			if (!is_user_connected(i) || !is_user_alive(i) || pev(i, pev_takedamage)== DAMAGE_NO || pev(ent, pev_body)== fm_cs_get_user_team(i) || IsInSphere(i)) continue
		
			entity_get_vector(i, EV_VEC_origin, playerOrigin)
		
			if (entity_get_int(i, EV_INT_flags) & FL_DUCKING) playerOrigin[2] -= 25.0
	
			hitent = trace_line(ent, sentryOrigin, playerOrigin, hitOrigin)
		
			if (hitent == i) 
			{
				distance = vector_distance(sentryOrigin, playerOrigin)
				closestOrigin = playerOrigin
		
				if (distance < closestDistance || closestTarget == 0) 
				{
					closestTarget = i
					closestDistance = distance
				}
			}
		}
		
		if (closestTarget) {
		
			emit_sound(ent, CHAN_WEAPON, "nova/zaxwat.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
			new Float:fDistance
			fDistance = get_distance_f(closestOrigin, sentryOrigin)
			new Float:fSpeed = fDistance / 100 
		
			new Float:new_sentryOrigin[3]
		
			new_sentryOrigin[0] = (closestOrigin[0] - sentryOrigin[0]) /fSpeed
			new_sentryOrigin[1] = (closestOrigin[1] - sentryOrigin[1]) /fSpeed
			new_sentryOrigin[2] = (closestOrigin[2] - sentryOrigin[2]) /fSpeed
		
			g_robo_gun[ent] = 0
			if(fDistance >= get_pcvar_float(g_iCvar[7]))
			{
				g_robo_next[ent] = 1
				set_anim(ent, 3)
			}
		
			entity_set_vector(ent, EV_VEC_velocity, new_sentryOrigin)
		
			set_pev(ent, STATE, 1)
			
			new Float:fAngle[3]
			entity_get_vector ( ent, EV_VEC_angles, fAngle )
			new Float:x = closestOrigin[0] - sentryOrigin[0]
			new Float:z = closestOrigin[1] - sentryOrigin[1]

			new Float:fRadians = floatatan ( z/x, radian )
			fAngle[1] = fRadians * (180.0 / 3.141592654)
			if ( closestOrigin[0] < sentryOrigin[0] )
			fAngle[1] -= 180.0

			entity_set_float ( ent, EV_FL_fuser1, fAngle[1] )
			entity_set_vector ( ent, EV_VEC_angles, fAngle )
			
			set_pev(ent, pev_euser1, closestTarget)
			
			set_pev(ent, pev_nextthink, get_gametime()+0.7)
				
			switch(pev(ent, TYPE_SHOOT)){
				case 0: 
				{
				}
				case 1:
				{
				}
				case 2: 
				{
				}
			}
		}
		else if(pev(ent, STATE)){
			set_pev(ent, pev_nextthink, get_gametime()+0.7)
			set_pev(ent, STATE, 0)
			
			switch(pev(ent, TYPE_SHOOT)){
				case 0:	
				{
					if(g_robo_gun[ent] == 1)
					{
						emit_sound(ent, CHAN_WEAPON, "hassault/hw_spindown.wav", 1.0, ATTN_NORM, 0, PITCH_NORM)
						g_robo_gun[ent] = 0
					}
					set_pev(ent, pev_movetype, MOVETYPE_TOSS)
					set_pev(ent, pev_controller_0, 127)
				}
				case 1:
				{
				}
				case 2:
				{
				}
			}
		}
		else {
			if(pev(ent, pev_sequence)!=2)set_anim(ent, 2)
			set_pev(ent, pev_nextthink, get_gametime()+0.25)
		}
}


tracer(Float:start[3], Float:end[3]) {
	new start_[3], end_[3]
	FVecIVec(start, start_)
	
	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] + 45)
	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] + 45)
	write_coord(end_[0])
	write_coord(end_[1])
	write_coord(end_[2])
	message_end()
	

}

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

bool:TraceCheckCollides(Float:origin[3], const Float:BOUNDS)
{
	new Float:traceEnds[8][3], Float:traceHit[3], hitEnt
	
	traceEnds[0][0] = origin[0] - BOUNDS
	traceEnds[0][1] = origin[1] - BOUNDS
	traceEnds[0][2] = origin[2] - BOUNDS
	
	traceEnds[3][0] = origin[0] + BOUNDS
	traceEnds[3][1] = origin[1] + BOUNDS
	traceEnds[3][2] = origin[2] + BOUNDS
	
	traceEnds[2][0] = origin[0] - BOUNDS
	traceEnds[2][1] = origin[1] + BOUNDS
	traceEnds[2][2] = origin[2] + BOUNDS
	
	traceEnds[4][0] = origin[0] + BOUNDS
	traceEnds[4][1] = origin[1] - BOUNDS
	traceEnds[4][2] = origin[2] - BOUNDS
	
	traceEnds[1][0] = origin[0] - BOUNDS
	traceEnds[1][1] = origin[1] - BOUNDS
	traceEnds[1][2] = origin[2] + BOUNDS
	
	traceEnds[5][0] = origin[0] + BOUNDS
	traceEnds[5][1] = origin[1] + BOUNDS
	traceEnds[5][2] = origin[2] - BOUNDS
	
	traceEnds[6][0] = origin[0] + BOUNDS
	traceEnds[6][1] = origin[1] - BOUNDS
	traceEnds[6][2] = origin[2] + BOUNDS
	
	traceEnds[7][0] = origin[0] - BOUNDS
	traceEnds[7][1] = origin[1] + BOUNDS
	traceEnds[7][2] = origin[2] - BOUNDS
	
	for (new i = 0; i < 8; i++) 
	{
		if (point_contents(traceEnds[i]) != CONTENTS_EMPTY) return true
		hitEnt = trace_line(0, origin, traceEnds[i], traceHit)
		if (hitEnt != 0) return true
		for (new j = 0; j < 3; j++) if (traceEnds[i][j] != traceHit[j]) return true
	}
	return false
}

stock sentry_damagetoplayer(sentry, Float:sentryOrigin[3], target) {
	new newHealth 
	
	newHealth = get_user_health(target) - get_pcvar_num(g_iCvar[8])

	
	if ( 0 < newHealth <= 5) {
		new targetFrags = get_user_frags(target) + 1
		new owner = pev(sentry, pev_euser2)
		
		if(!is_user_connected(owner))
			return
		
		new ownerFrags = get_user_frags(owner) + 1
		set_user_frags(target, targetFrags) 
		set_user_frags(owner, ownerFrags)

		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()
		
		g_UronKill[sentry] = g_UronKill[sentry] + 1
		
		cs_set_user_money(owner, cs_get_user_money(owner) + get_pcvar_num(g_iCvar[10]))
		
		
		scoreinfo_update(owner, ownerFrags, cs_get_user_deaths(owner), int:cs_get_user_team(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(5)
	write_byte(5)
	write_long(DMG_BULLET)
	write_coord(floatround(sentryOrigin[0]))
	write_coord(floatround(sentryOrigin[1]))
	write_coord(floatround(sentryOrigin[2]))
	message_end()
}

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()
}

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 ( cs_get_user_team ( id ) != cs_get_user_team ( 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
}