#pragma semicolon 1 #include #include #include #undef REQUIRE_PLUGIN #include #define REQUIRE_PLUGIN #pragma newdecls required #define PLUGIN_VERSION "1.0" #define GREETING_TITLE "UNLOZE.com" #define PLACEHOLDER_EVENT "Test Event" #define MAX_NAME_CHARS 64 // Skip greetings rather than push a busy map towards the 2048 edict limit. #define EDICT_HEADROOM 1900 // Stock model on every client; its "forward" attachment sits on ValveBiped.forward, a child of // Bip01_Head1, so it follows the head of any ValveBiped skeleton it bone-merges onto. #define HELPER_MODEL "models/player/ct_urban.mdl" #define HELPER_ATTACHMENT "forward" #define HELPER_CLASS "prop_dynamic" // created as prop_dynamic_override, which spawns as prop_dynamic #define EF_BONEMERGE (1 << 0) #define EF_NOSHADOW (1 << 4) #define EF_NORECEIVESHADOW (1 << 6) #define EF_BONEMERGE_FASTCULL (1 << 7) #define EF_PARENT_ANIMATES (1 << 9) #define MOVEMENT_BUTTONS (IN_FORWARD|IN_BACK|IN_MOVELEFT|IN_MOVERIGHT|IN_JUMP|IN_DUCK) // sm_eventgreeting_anchor: what the text is parented to enum { ANCHOR_HEAD = 0, // "forward" attachment of a bone-merged helper; sways with the head animation ANCHOR_PLAYER, // the player; offset corrected for pitch and eye height every tick ANCHOR_VIEWMODEL // the viewmodel, at the eyes with the view angles; bobs with the gun } ConVar g_cvEventIsOn; ConVar g_cvAnchor; ConVar g_cvDuration; ConVar g_cvOffset; ConVar g_cvSize; ConVar g_cvFont; ConVar g_cvMaxChars; bool g_bEventNotifier; bool g_bWorldTextBroken; // One greeting per player per map bool g_bGreeted[MAXPLAYERS + 1]; int g_iTextRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; int g_iHelperRef[MAXPLAYERS + 1] = {INVALID_ENT_REFERENCE, ...}; float g_flExpireAt[MAXPLAYERS + 1]; // 0 until the player first moves int g_iAnchor[MAXPLAYERS + 1]; float g_flLastPitch[MAXPLAYERS + 1]; float g_flLastEyeHeight[MAXPLAYERS + 1]; // Per entity, read by the transmit hook int g_iEntOwner[2049]; public Plugin myinfo = { name = "EventGreeting", author = "marisakirisame.net", description = "Greets players on their first spawn during events with the active event's name", version = PLUGIN_VERSION, url = "" }; public void OnPluginStart() { // Owned by VIP_Reward. CreateConVar on an existing cvar would add it to this plugin's list, and // AutoExecConfig would then write sv_event_is_on "0" into EventGreeting.cfg, turning event mode // off every map. So only create it when VIP_Reward hasn't (yet), and keep it out of the cfg. g_cvEventIsOn = FindConVar("sv_event_is_on"); if (g_cvEventIsOn == null) g_cvEventIsOn = CreateConVar("sv_event_is_on", "0", "Cvar decides whether event mode is on or not.", FCVAR_DONTRECORD); g_cvEventIsOn.AddChangeHook(OnEventIsOnChanged); // lines are centred with space padding, which is only exact in a monospaced font g_cvFont = CreateConVar("sm_eventgreeting_font", "8", "point_worldtext font (8 = Roboto Mono with outline)", 0, true, 0.0, true, 12.0); g_cvSize = CreateConVar("sm_eventgreeting_size", "3.0", "Text size", 0, true, 0.5); g_cvAnchor = CreateConVar("sm_eventgreeting_anchor", "2", "0 = head attachment of a bone-merged helper (sways with the head animation, 2 edicts), 1 = the player (turns at network rate), 2 = the viewmodel (bobs with the gun)", 0, true, 0.0, true, 2.0); g_cvOffset = CreateConVar("sm_eventgreeting_offset", "64 0 0", "Text position \"x y z\" relative to the anchor (x is forward)"); g_cvDuration = CreateConVar("sm_eventgreeting_duration", "5.0", "Seconds the greeting stays after the player first moves", 0, true, 0.0); g_cvMaxChars = CreateConVar("sm_eventgreeting_max_chars", "32", "Maximum characters of the event name; longer names end in ...", 0, true, 8.0, true, float(MAX_NAME_CHARS)); AutoExecConfig(true, "EventGreeting"); RegAdminCmd("sm_eventgreeting_test", Cmd_Test, ADMFLAG_RCON, "sm_eventgreeting_test [target] - show the greeting now, ignoring sv_event_is_on and earlier greetings"); RegAdminCmd("sm_eventgreeting_debug", Cmd_Debug, ADMFLAG_RCON, "sm_eventgreeting_debug - list live greetings"); HookEvent("player_spawn", Event_PlayerSpawn); HookEvent("player_death", Event_KillGreeting); HookEvent("player_team", Event_KillGreeting); } public void OnPluginEnd() { for (int i = 1; i <= MaxClients; i++) KillGreeting(i); } public void OnAllPluginsLoaded() { g_bEventNotifier = LibraryExists("EventNotifier"); } public void OnLibraryAdded(const char[] name) { if (StrEqual(name, "EventNotifier")) g_bEventNotifier = true; } public void OnLibraryRemoved(const char[] name) { if (StrEqual(name, "EventNotifier")) g_bEventNotifier = false; } public void OnMapStart() { g_bWorldTextBroken = false; PrecacheModel(HELPER_MODEL); // the previous map's entities are gone, so only the bookkeeping needs resetting for (int i = 1; i <= MaxClients; i++) { g_bGreeted[i] = false; g_iTextRef[i] = INVALID_ENT_REFERENCE; g_iHelperRef[i] = INVALID_ENT_REFERENCE; } } public void OnClientConnected(int client) { g_bGreeted[client] = false; } public void OnClientDisconnect(int client) { KillGreeting(client); } void OnEventIsOnChanged(ConVar convar, const char[] oldValue, const char[] newValue) { if (convar.BoolValue) return; for (int i = 1; i <= MaxClients; i++) KillGreeting(i); } //---------------------------------------------------------------------------------------------------- // Spawning //---------------------------------------------------------------------------------------------------- public void Event_PlayerSpawn(Event event, const char[] name, bool dontBroadcast) { if (!g_cvEventIsOn.BoolValue) return; // eye position and team aren't final during the event RequestFrame(Frame_Greet, event.GetInt("userid")); } void Frame_Greet(int userid) { int client = GetClientOfUserId(userid); if (client == 0 || g_bGreeted[client] || IsFakeClient(client) || !g_cvEventIsOn.BoolValue) return; if (!IsPlayerAlive(client) || GetClientTeam(client) < 2) return; char eventName[EVENT_STR_LEN]; if (!FindActiveEventName(eventName, sizeof(eventName))) return; if (ShowGreeting(client, eventName)) g_bGreeted[client] = true; } public void Event_KillGreeting(Event event, const char[] name, bool dontBroadcast) { int client = GetClientOfUserId(event.GetInt("userid")); if (client != 0) KillGreeting(client); } // The active event is one in progress, else the one whose start is nearest to now (past or future). bool FindActiveEventName(char[] buffer, int maxlen) { if (!g_bEventNotifier || !EventNotifier_HasFetched()) return false; int now = GetTime(); int best = -1; int bestDistance; int count = EventNotifier_GetEventCount(); for (int i = 0; i < count; i++) { EventInfo ev; if (!EventNotifier_GetEvent(i, ev, sizeof(ev)) || ev.start == 0) continue; if (ev.end > 0 && now >= ev.start && now < ev.end) { best = i; break; } int distance = now > ev.start ? now - ev.start : ev.start - now; if (best == -1 || distance < bestDistance) { best = i; bestDistance = distance; } } if (best == -1) return false; EventInfo ev; EventNotifier_GetEvent(best, ev, sizeof(ev)); strcopy(buffer, maxlen, ev.name); return true; } bool ShowGreeting(int client, const char[] eventName) { KillGreeting(client); if (g_bWorldTextBroken || GetEntityCount() >= EDICT_HEADROOM) return false; char text[2 * (MAX_NAME_CHARS + 8)]; if (!FormatGreeting(eventName, text, sizeof(text))) return false; int anchor = g_cvAnchor.IntValue; int parent = client; int helper = -1; if (anchor == ANCHOR_HEAD) { helper = SpawnHelper(client); if (helper == -1) return false; parent = helper; } else if (anchor == ANCHOR_VIEWMODEL) { int viewmodel = GetEntPropEnt(client, Prop_Send, "m_hViewModel", 0); if (viewmodel != -1) parent = viewmodel; else anchor = ANCHOR_PLAYER; } int ent = SpawnWorldText(client, parent, anchor, text); if (ent == -1) { if (helper != -1) AcceptEntityInput(helper, "Kill"); return false; } g_iHelperRef[client] = helper != -1 ? EntIndexToEntRef(helper) : INVALID_ENT_REFERENCE; g_iTextRef[client] = EntIndexToEntRef(ent); g_flExpireAt[client] = 0.0; return true; } // Invisible copy of the player's skeleton; the text hangs off its head attachment, so the client // keeps it in front of the face it draws without the server moving it. int SpawnHelper(int client) { int ent = CreateEntityByName("prop_dynamic_override"); if (ent == -1) return -1; DispatchKeyValue(ent, "model", HELPER_MODEL); DispatchKeyValue(ent, "solid", "0"); DispatchKeyValue(ent, "DisableBoneFollowers", "1"); DispatchKeyValue(ent, "disableshadows", "1"); DispatchKeyValue(ent, "disablereceiveshadows", "1"); if (!DispatchSpawn(ent)) { AcceptEntityInput(ent, "Kill"); return -1; } // RENDER_NONE rather than EF_NODRAW: EF_NODRAW stops the entity being sent at all, and the // client needs it to place the text. SetEntityRenderMode(ent, RENDER_NONE); // CBaseEntity::FollowEntity() recipe (see Leader3's glow shell): the client only bone-merges // with EF_BONEMERGE, a move parent and MOVETYPE_NONE. float origin[3], angles[3]; GetClientAbsOrigin(client, origin); GetClientAbsAngles(client, angles); TeleportEntity(ent, origin, angles, NULL_VECTOR); SetVariantString("!activator"); AcceptEntityInput(ent, "SetParent", client, ent); SetEntityMoveType(ent, MOVETYPE_NONE); SetEntProp(ent, Prop_Send, "m_fEffects", EF_BONEMERGE|EF_BONEMERGE_FASTCULL|EF_NOSHADOW|EF_NORECEIVESHADOW|EF_PARENT_ANIMATES); g_iEntOwner[ent] = client; SDKHook(ent, SDKHook_SetTransmit, Hook_OwnerOnlyTransmit); return ent; } int SpawnWorldText(int client, int parent, int anchor, const char[] text) { int ent = CreateEntityByName("point_worldtext"); if (ent == -1) { g_bWorldTextBroken = true; LogMessage("point_worldtext could not be created; event greetings are off for this map."); return -1; } char font[4], size[16]; g_cvFont.GetString(font, sizeof(font)); g_cvSize.GetString(size, sizeof(size)); DispatchKeyValue(ent, "message", text); DispatchKeyValue(ent, "font", font); DispatchKeyValue(ent, "textsize", size); DispatchKeyValue(ent, "color", "255 255 255 255"); DispatchKeyValue(ent, "orientation", "1"); DispatchSpawn(ent); float eyes[3]; GetClientEyePosition(client, eyes); TeleportEntity(ent, eyes, NULL_VECTOR, NULL_VECTOR); SetVariantString("!activator"); AcceptEntityInput(ent, "SetParent", parent, ent); if (anchor == ANCHOR_HEAD) { SetVariantString(HELPER_ATTACHMENT); AcceptEntityInput(ent, "SetParentAttachment", ent, ent); } g_iAnchor[client] = anchor; SetTextOffset(client, ent); g_iEntOwner[ent] = client; SDKHook(ent, SDKHook_SetTransmit, Hook_OwnerOnlyTransmit); return ent; } // Sets the text's local origin (it is parented, so TeleportEntity sets the local origin). // The client rotates children of the local player by the full view angles about the FEET, so for // ANCHOR_PLAYER the eye height is added in the rotated frame: the world up vector in that frame is // (-sin pitch, 0, cos pitch). The pitch comes from the server, so this is redone as it changes. void SetTextOffset(int client, int ent) { float local[3]; GetOffset(local); if (g_iAnchor[client] == ANCHOR_PLAYER) { float angles[3]; GetClientEyeAngles(client, angles); float eyeHeight = GetEntPropFloat(client, Prop_Send, "m_vecViewOffset[2]"); float pitch = DegToRad(angles[0]); local[0] -= eyeHeight * Sine(pitch); local[2] += eyeHeight * Cosine(pitch); g_flLastPitch[client] = angles[0]; g_flLastEyeHeight[client] = eyeHeight; } TeleportEntity(ent, local, NULL_VECTOR, NULL_VECTOR); } bool PlayerOffsetChanged(int client) { float angles[3]; GetClientEyeAngles(client, angles); float eyeHeight = GetEntPropFloat(client, Prop_Send, "m_vecViewOffset[2]"); return FloatAbs(angles[0] - g_flLastPitch[client]) > 0.1 || FloatAbs(eyeHeight - g_flLastEyeHeight[client]) > 0.1; } void GetOffset(float local[3]) { char value[64], parts[3][16]; g_cvOffset.GetString(value, sizeof(value)); int count = ExplodeString(value, " ", parts, sizeof(parts), sizeof(parts[])); for (int i = 0; i < 3; i++) local[i] = i < count ? StringToFloat(parts[i]) : 0.0; } public Action Hook_OwnerOnlyTransmit(int ent, int client) { return client == g_iEntOwner[ent] ? Plugin_Continue : Plugin_Handled; } //---------------------------------------------------------------------------------------------------- // Expiry and cleanup //---------------------------------------------------------------------------------------------------- public void OnPlayerRunCmdPost(int client, int buttons) { if (g_iTextRef[client] == INVALID_ENT_REFERENCE || g_flExpireAt[client] != 0.0) return; if (buttons & MOVEMENT_BUTTONS) g_flExpireAt[client] = GetGameTime() + g_cvDuration.FloatValue; } public void OnGameFrame() { float now = GetGameTime(); for (int client = 1; client <= MaxClients; client++) { if (g_iTextRef[client] == INVALID_ENT_REFERENCE) continue; if (LiveEntRef(g_iTextRef[client]) == -1 || (g_iHelperRef[client] != INVALID_ENT_REFERENCE && LiveEntRef(g_iHelperRef[client], HELPER_CLASS) == -1) || (g_flExpireAt[client] != 0.0 && now >= g_flExpireAt[client]) || !IsClientInGame(client) || !IsPlayerAlive(client)) { // also catches entities the round restart removed KillGreeting(client); continue; } if (g_iAnchor[client] == ANCHOR_PLAYER && PlayerOffsetChanged(client)) SetTextOffset(client, EntRefToEntIndex(g_iTextRef[client])); } } void KillGreeting(int client) { KillEntRef(g_iTextRef[client]); KillEntRef(g_iHelperRef[client], HELPER_CLASS); g_iTextRef[client] = INVALID_ENT_REFERENCE; g_iHelperRef[client] = INVALID_ENT_REFERENCE; } void KillEntRef(int ref, const char[] expectedClass = "point_worldtext") { int ent = LiveEntRef(ref, expectedClass); if (ent != -1) AcceptEntityInput(ent, "Kill"); } // Resolves an entity reference, returning -1 unless it is still a live edict of the expected class. int LiveEntRef(int ref, const char[] expectedClass = "point_worldtext") { if (ref == INVALID_ENT_REFERENCE) return -1; int ent = EntRefToEntIndex(ref); if (ent == INVALID_ENT_REFERENCE || !IsValidEdict(ent)) return -1; char classname[32]; GetEdictClassname(ent, classname, sizeof(classname)); return StrEqual(classname, expectedClass) ? ent : -1; } //---------------------------------------------------------------------------------------------------- // Text: point_worldtext only draws printable ASCII, so anything else is dropped from the event name. // Both lines are space-padded to the same length so they centre in a monospaced font. //---------------------------------------------------------------------------------------------------- bool FormatGreeting(const char[] eventName, char[] output, int maxlen) { char name[MAX_NAME_CHARS + 4]; int maxChars = g_cvMaxChars.IntValue; int len = 0; bool truncated = false; for (int i = 0; eventName[i] != '\0'; i++) { if (eventName[i] < ' ' || eventName[i] > '~') continue; // no leading or doubled spaces left behind by dropped characters if (eventName[i] == ' ' && (len == 0 || name[len - 1] == ' ')) continue; if (len >= maxChars) { truncated = true; break; } name[len++] = eventName[i]; } while (len > 0 && name[len - 1] == ' ') len--; name[len] = '\0'; if (len == 0) return false; if (truncated) StrCat(name, sizeof(name), "..."); char title[MAX_NAME_CHARS + 4], line[MAX_NAME_CHARS + 4]; int width = strlen(name) > strlen(GREETING_TITLE) ? strlen(name) : strlen(GREETING_TITLE); PadLine(GREETING_TITLE, width, title, sizeof(title)); PadLine(name, width, line, sizeof(line)); Format(output, maxlen, "%s\n%s", title, line); return true; } void PadLine(const char[] text, int width, char[] output, int maxlen) { int pad = width - strlen(text); int left = pad / 2; output[0] = '\0'; for (int c = 0; c < left; c++) StrCat(output, maxlen, " "); StrCat(output, maxlen, text); for (int c = left; c < pad; c++) StrCat(output, maxlen, " "); } //---------------------------------------------------------------------------------------------------- // Commands //---------------------------------------------------------------------------------------------------- public Action Cmd_Test(int client, int args) { int target = client; if (args >= 1) { char arg[64]; GetCmdArg(1, arg, sizeof(arg)); target = FindTarget(client, arg, false, false); if (target == -1) return Plugin_Handled; } if (target == 0 || !IsPlayerAlive(target)) { ReplyToCommand(client, "[EventGreeting] The target must be an alive player."); return Plugin_Handled; } char eventName[EVENT_STR_LEN]; if (FindActiveEventName(eventName, sizeof(eventName))) ReplyToCommand(client, "[EventGreeting] Active event: %s", eventName); else { strcopy(eventName, sizeof(eventName), PLACEHOLDER_EVENT); ReplyToCommand(client, "[EventGreeting] No active event (EventNotifier %s), using \"%s\".", g_bEventNotifier ? "has no events" : "not loaded", eventName); } char text[2 * (MAX_NAME_CHARS + 8)]; if (FormatGreeting(eventName, text, sizeof(text))) { ReplaceString(text, sizeof(text), "\n", "|\n|"); ReplyToCommand(client, "|%s|", text); } if (ShowGreeting(target, eventName)) ReplyToCommand(client, "[EventGreeting] Shown to %N.", target); else ReplyToCommand(client, "[EventGreeting] Could not show the greeting (edicts, worldtext or empty name)."); return Plugin_Handled; } public Action Cmd_Debug(int client, int args) { ReplyToCommand(client, "[EventGreeting] sv_event_is_on %d, EventNotifier %s, entities %d", g_cvEventIsOn.IntValue, g_bEventNotifier ? "loaded" : "missing", GetEntityCount()); float now = GetGameTime(); bool shown = false; for (int i = 1; i <= MaxClients; i++) { if (g_iTextRef[i] == INVALID_ENT_REFERENCE) continue; char state[32]; if (g_flExpireAt[i] == 0.0) strcopy(state, sizeof(state), "waiting for movement"); else FormatEx(state, sizeof(state), "%.1fs left", g_flExpireAt[i] - now); ReplyToCommand(client, " %N: text %d, helper %d, %s", i, LiveEntRef(g_iTextRef[i]), LiveEntRef(g_iHelperRef[i], HELPER_CLASS), state); shown = true; } if (!shown) ReplyToCommand(client, "[EventGreeting] No live greetings."); return Plugin_Handled; }