diff --git a/docs/scoreboard-protocol.md b/docs/scoreboard-protocol.md new file mode 100644 index 00000000..cdcf896a --- /dev/null +++ b/docs/scoreboard-protocol.md @@ -0,0 +1,2813 @@ +# Scoreboard and HUD extension protocol + +Status: Draft 3, not released. Protocol version 1. Covers the BugfixedHL client and server, +`bugfixedapi_amxx` and the GunGame plugin. + +Draft 3 adds the element kinds `Board`, `Feed` and `Box`, the `Event` message, color slots, effects +common to every kind, the ring form of a `Meter`, the track of a `Strip` and sprite files as icons. +`HudV1` is not released, so all of it belongs to `HudV1` and needs no new caps bit (3.1). + +This document describes how a BugfixedHL server sends to BugfixedHL clients a custom scoreboard +layout, extra values for players, teams and the whole game, and HUD elements defined by server +plugins. The client knows no game mode: a mode such as GunGame builds its scoreboard and HUD from +generic parts through plugin natives. The first consumer is the GunGame plugin (9.3). + +## 1. Goals + +- A server plugin can add columns to the scoreboard, hide some standard columns, move the others + and fill cells for players, teams and the whole game. +- A server plugin can put HUD elements anywhere on the screen: text lines, icons, meters, icon + strips, boards of rows, feeds of event lines and backdrops behind a group of elements. It + chooses the position, alignment, color and font of each element, when it is shown, and its + texts. Texts show cell values and places computed by the client. +- Texts are client localization tokens or the plugin's own texts, sent to every player in his + language. +- The client contains no logic of a game mode. +- Full backward compatibility in both directions: + - old clients (older BugfixedHL, Valve, AG, OpenAG) on a new server see the standard scoreboard + and HUD and never receive the new message; + - new clients on an old server (older BugfixedHL, AG, Valve) see the standard scoreboard and HUD. +- The protocol can grow without breaking clients that only know version 1. + +Out of scope: demo playback, HLTV, AG and Valve server DLLs. + +The data model is the Source engine `player_resource` idea, but it is not a networked entity. +`entity_state_t` has a fixed set of numeric fields and no strings, an entity reaches a client only +when it has a model and is in the client's PVS, and it can't be addressed to one client. +User messages carry strings, are reliable and can be sent to a single client. + +## 2. Overview + +``` +plugin (AMXX) ── natives ──▶ bugfixedapi_amxx ── IBugfixedServer ──▶ hl.so: scoreboard and HUD state + │ + "BhlScore" user message, MSG_ONE, + only to clients with ScoreboardV1 + ▼ + client.dll: store ──▶ ScorePanel, hud_scores, + HUD elements (HudServerPanel) +``` + +The server keeps one state for everybody plus per-player overrides of texts and visibility, and +sends every client its own view of it. The client evaluates texts every frame from the store, for +the player it looks at. Events are the exception: one-shot lines that the server queues per client +and the client evaluates once, on arrival (4.3, 5.6). + +| Term | Meaning | +|------------|--------------------------------------------------------------------------------------------| +| Schema | `Config` plus the list of columns | +| Target | Owner of a value: the whole game, a player or a team | +| Cell | One value, addressed by target and column | +| List | A named array of values that belongs to the whole game | +| Element | A HUD item defined by the server: `Text`, `Icon`, `Meter`, `Strip`, `Board`, `Feed`, `Box` | +| Template | Text of an element with placeholders, evaluated by the client (8.10) | +| Variant | One of up to 8 templates of an element, chosen by a value | +| Color slot | A color of an element for a variant, the warning or the accent bar (8.5) | +| Event | A line for a `Feed` element, sent once and never kept as state (4.3) | +| Viewer | The client that draws the HUD | +| Subject | The player whose data an element shows: the viewer or the observed player | +| Caps | Bitmask of client features, reported by the client in `_bhl` | + +## 3. Client capabilities + +### 3.1 Format + +The client reports its features in the cvar and userinfo key `_bhl`. The value is a bitmask +written as lowercase hex without a prefix, at most 8 digits: `1`, `3`, `1f`. + +The server accepts only 1–8 hex digits of either case, without a sign, spaces or `0x`, and parses +them with `strtoul(value, nullptr, 16)`. Any other value, an empty one included, means `0`. Unknown +bits are ignored. + +| Bit | Mask | Name | Meaning | +|------|-------|----------------|-----------------------------------------------------------------| +| 0 | `0x1` | `ScoreboardV1` | Understands `BhlScore` protocol version 1 and receives its data | +| 1 | `0x2` | `HudV1` | Draws HUD elements; the plugin drops its own HUD texts | +| 2–31 | — | reserved | Clients send 0, servers ignore | + +`HudV1` is only set together with `ScoreboardV1`, because elements read the store. The server +doesn't look at `HudV1` when it sends: every client with `ScoreboardV1` gets the HUD data too. The +bit tells plugins which players need their own HUD texts. The server clears `HudV1` when +`ScoreboardV1` is not set or the client is a bot or an HLTV proxy, so a plugin never drops its texts +for a client that gets no data. `bhl_get_client_caps()` returns this normalized value. + +Bits are never reused or redefined after release. An incompatible protocol change gets a new bit +(`ScoreboardV2`), and the server sends the new format only to clients that have that bit. Before +release, bit 1 and `Config` changed meaning; draft 1 builds are not compatible (11). Draft 3 +extends `HudV1` before its release (new kinds, params, color slots, the `Event` op, built-in +values and sprite files) without a new bit; draft 2 builds are not supported either (11). + +`_bhl` doesn't replace `aghl_supports`. The MOTD flags stay where they are. + +### 3.2 Client side + +- `ConVar _bhl` has only `FCVAR_USERINFO`. + - No `FCVAR_ARCHIVE` or `FCVAR_BHL_ARCHIVE`: the value is computed, it must not be saved to configs. + - No `FCVAR_PRIVILEGED`: the engine answers a cvar query for such cvars with `CVAR is privileged`, + which would break the server fallback from 3.3. +- The cvar is registered with the caps of the build as its default value (`3`), so the key is in + userinfo from the first connect. +- One owner function, `CHud::UpdateCapsUserinfo()`, computes the caps from the build + features and client settings and writes `_bhl`. It runs: + - from `CHud::Frame` on any frame where the caps or `_bhl` differ from the written ones (`m_iCaps` + starts at -1): after the configs have been executed and when a related client setting changes; + - on every `VidInit`. + + A value typed by the user is overwritten by the next call. +- One frame after a write the client compares `gEngfuncs.LocalPlayerInfo_ValueForKey("_bhl")` with + the expected value: + - on mismatch it runs `setinfo _bhl `; + - if the key is still wrong on the next check, it prints one console message (most likely the + userinfo is full). The server can still detect the client with the cvar query from 3.3. +- Client settings: + + | Cvar | Default | Flags | Meaning | + |-------------------------|---------|---------------------|------------------------------------------------------| + | `hud_scoreboard_custom` | 1 | `FCVAR_ARCHIVE` | Show the custom scoreboard when the server sends one | + | `hud_server_elements` | 1 | `FCVAR_BHL_ARCHIVE` | Draw HUD elements defined by the server | + + - `ScoreboardV1` is set while either cvar is 1, `HudV1` while `hud_server_elements` is 1. + - `hud_scoreboard_custom 0` alone: the client still receives the data and draws elements, and + shows the standard scoreboard. + - `hud_server_elements 0` alone: `HudV1` is cleared. The client draws no screen elements (the + banner rows stay, 6.8) and ignores requests to hide standard HUD parts (8.12). The plugin shows + its own HUD texts again. Nothing is sent again. + - Both 0: both bits are cleared and the server stops sending. When the client clears + `ScoreboardV1` in `_bhl`, it clears its store as on `Reset`. Setting either cvar back to 1 + brings a full sync. + - While `ScoreboardV1` is cleared, the client ignores `BhlScore`. After it sets the bit again, it + ignores every message except `Reset` until a `Reset` or `VidInit`, so changes meant for the old + store are never applied to the empty one. + +### 3.3 Server side + +For every client the server keeps `caps` and the source they came from: + +| Source | Set when | +|------------|---------------------------------------------------------------| +| `Unknown` | On connect, before anything is known | +| `Userinfo` | `_bhl` is present in userinfo | +| `Query` | The cvar query answered; errors give `caps = 0` | +| `None` | No key, and a query is impossible: bot, HLTV, p47, LAN client | + +1. `ClientConnect` and `ClientUserInfoChanged` read `_bhl` from userinfo. If the key is present, + it is parsed and the source becomes `Userinfo`. Userinfo always wins: a query answer that + arrives later doesn't overwrite it. If the key disappears from userinfo, the source goes back + to `Unknown` and the caps stay as they are until the query of step 2 gives new ones; a client + past `InitHUD` is queried at once. +2. In `InitHUD`, if the source is `Unknown` and either the extension is active (5.1) or + `sv_bhl_query_vars` is 1, the server calls `QueryClientCvarValue2(_bhl)` with a new + `REQUESTID_CAPS`. It applies the same p47 and LAN checks as the existing `aghl_*` queries and + waits while the SteamID is pending. If the extension becomes active later on the map, clients + that are still `Unknown` are queried at that moment. + While the source is `Query` and the extension is active, the server queries `_bhl` again every + 10 s, so a changed client setting reaches it. +3. An answer that doesn't parse (`Bad CVAR request`, `CVAR is privileged`, empty) means `0`. +4. Every change of `caps` fires the plugin forward `bhl_client_caps_changed(id)`. + - `ScoreboardV1` appeared after `InitHUD`: the client gets a full sync (5.3). + - `ScoreboardV1` disappeared: the server stops sending to that client and doesn't send `Reset`. + - Only `HudV1` changed: nothing is sent; the forward lets the plugin switch its own HUD texts. + +Each layer covers a different case: + +| Layer | Covers | +|-------------|---------------------------------------------------------------------| +| Cvar mirror | The normal case: no extra traffic, known before `InitHUD` | +| `setinfo` | The cvar was not mirrored into userinfo for any reason | +| Cvar query | Userinfo is full (256 bytes), so neither path above can add the key | + +The server command `bhl_caps` prints slot, name, caps and source for every connected client. + +Known limitation: with the source `Query` the server sees a changed setting only with the next +answer, up to 10 s later. A client that switches both cvars off and back on between two answers +clears its store and waits for a `Reset` (3.2), but the server never saw `ScoreboardV1` disappear +and sends only changes. The client shows the standard scoreboard and no elements until the next +map or a reconnect. + +## 4. Message `BhlScore` + +### 4.1 Transport + +- The server registers `REG_USER_MSG("BhlScore", -1)`: variable size, payload up to 192 bytes. +- The message is sent only with `MSG_ONE` (reliable) and only to clients that have + `ScoreboardV1` and passed `InitHUD`. It is never sent with `MSG_ALL`, `MSG_BROADCAST` or + `MSG_ONE_UNRELIABLE`, and never to bots or HLTV proxies. + - Old clients never receive it, so it doesn't matter how their engine handles unknown messages. + - An old server never registers it, so the client hook never fires. + - Every message is built for one client, so per-player texts and visibility cost no extra + format: the server sends each client its own values. +- One message carries one operation. The first byte is the opcode, the rest is its payload. + The client ignores messages with unknown opcodes, which lets new opcodes be added safely. +- `Reset`, `Config`, `Column`, `Element`, `Template` and `HudState` are read field by field, and + trailing bytes after the known fields are ignored. Later versions may append fields to them, as + draft 3 appends the color block to `Element`. `Values`, `List` and `Event` have no room for + trailing fields and are extended through new value types or new opcodes. + +### 4.2 Data types + +All integers are little-endian, as written by `WRITE_*` and read by `READ_*`. + +| Type | Bytes | Write / read | Range | +|----------|-------|--------------------------------|-----------------------| +| `byte` | 1 | `WRITE_BYTE` / `READ_BYTE` | 0 … 255 | +| `short` | 2 | `WRITE_SHORT` / `READ_SHORT` | −32768 … 32767 | +| `word` | 2 | `WRITE_SHORT` / `READ_WORD` | 0 … 65535 | +| `long` | 4 | `WRITE_LONG` / `READ_LONG` | −2³¹ … 2³¹−1 | +| `string` | n + 1 | `WRITE_STRING` / `READ_STRING` | UTF-8, NUL-terminated | + +Strings: + +- A client token is `#` followed by `[A-Za-z_][A-Za-z0-9_]*`. A Column title, the Config title and + tag, and the text of a `Text` or `Icon` value (in cells and list items) that is exactly a token + is resolved by VGUI2 on the client. If the token is missing, the client shows it without the + leading `#`. Any other string is shown as it is: `#1` stays `#1`. Templates follow 8.10. +- Plugins can only use tokens shipped with the client in + `ui/resource/language/bugfixedhl_*.utf8.txt`. The client ships generic tokens for columns and HUD + texts, see section 10. +- Color codes (`^` and a digit) are not interpreted in version 1. The client strips them from every + string except `select`, `value` and `list` of an `Element` and the text of a `Template`, where `^` + starts a ref (8.10); the template parser drops them from literals and word forms. +- The server truncates strings to the limits from 4.7 on a UTF-8 character boundary; templates are + never cut (9.2). The client truncates strings again if they are still too long, on a UTF-8 + character boundary. + +### 4.3 Opcodes + +| Op | Name | Payload | +|--------|------------|------------------------------------------------| +| `0x00` | `Reset` | None | +| `0x01` | `Config` | Hidden standard columns, title, tag | +| `0x02` | `Column` | One column definition | +| `0x03` | `Values` | Cells of one target | +| `0x04` | `List` | Items of one list | +| `0x05` | `Element` | One HUD element definition, or a removal | +| `0x06` | `Template` | One template variant of an element | +| `0x07` | `HudState` | Visible elements and hidden standard HUD parts | +| `0x08` | `Event` | One line of a `Feed` element; not state | +| other | reserved | Ignored by the client | + +#### `Reset` (`0x00`) + +No fields: the message is the opcode alone. Trailing bytes are ignored (4.1), so later versions +may append fields. + +The client drops the schema, all cells, lists, elements and templates, sets the HUD state to "no +element visible, no standard part hidden" and returns to the standard scoreboard. + +#### `Config` (`0x01`) + +| Field | Type | Notes | +|---------|----------|------------------------------------------------------| +| `flags` | `word` | See below | +| `title` | `string` | Up to 63 bytes; replaces the server name if not `""` | +| `tag` | `string` | Up to 15 bytes; a badge after the server name: `FFA` | + +| Bit | Name | Meaning | +|------|---------------|-------------------------| +| 0 | `HideFrags` | Hide the Frags column | +| 1 | `HideDeaths` | Hide the Deaths column | +| 2 | `HideEff` | Hide the Eff column | +| 3 | `HideSteamID` | Hide the SteamID column | +| 4–15 | reserved | Sent as 0, ignored | + +The server can't hide Avatar, Name and Ping. Avatars follow the player's +`hud_scoreboard_showavatars`. + +The first `Config` after a `Reset` (or after `VidInit`) turns the custom scoreboard on. +A repeated `Config` replaces the previous one. HUD elements don't need a `Config`: a plugin that +only wants HUD elements leaves the standard scoreboard in place. A `Config` without a whole `flags` +is ignored; a missing `title` or `tag` is `""`. + +#### `Column` (`0x02`) + +| Field | Type | Notes | +|-----------|----------|----------------------------------------------------------------------------------| +| `id` | `byte` | 0–31 | +| `display` | `byte` | How cells are drawn, see below | +| `flags` | `word` | See below | +| `width` | `byte` | Proportional units as in `ScorePanel.res`; `0` is the default | +| `sort` | `byte` | `0`: not a sort key; bits 0–6: priority, 1 first; bit 7: ascending | +| `key` | `string` | Up to 15 bytes of `[a-z0-9_]`, unique: `level`, `weapon` | +| `title` | `string` | Up to 31 bytes, text or `#token`; `""` for a built-in column keeps its own title | +| `host` | `byte` | `Badge` only: id of the column the badge follows; `0xFF` otherwise or if unknown | + +A `Column` with an existing `id` replaces that column's definition; its cells are kept. +Columns are shown in ascending `id` order. The server assigns ids, plugins address columns +by `key`. Templates and elements also refer to columns by `key` (8.10), so they don't depend on ids. +The server keeps `host` as a key and resolves it when it builds the message (5.1). + +The client ignores a `Column` with an `id` of 32 or more, and one that ends before `key` or whose +`key` has no NUL. A missing `title` is `""`, a missing `host` is `0xFF`. `Builtin` and `Badge` +columns are never sort keys; keys with the same priority are ordered by `id`. + +Display kinds: + +| Value | Name | Draws | +|-------|-----------|------------------------------------------------------------------------------------| +| 0 | `Text` | Any cell as text | +| 1 | `Icon` | `Icon` cells as sprite and text; other cells as text | +| 2 | `Meter` | `Progress` cells as dots or a bar with a `cur/max` counter (6.6); others as text | +| 3 | `Builtin` | A standard column, chosen by `key`; cells are ignored | +| 4 | `Steps` | `Progress` cells as `cur/max` with a strip of `max` steps below (6.6) | +| 5 | `Badge` | Not a column of its own: cells are drawn as badges after the cells of `host` (6.7) | +| other | — | Same as `Text` | + +Default widths for `width = 0`: `Text` 60, `Icon` 100, `Meter` 90, `Steps` 60. A `Builtin` column +keeps the width of its standard column. A `Badge` column takes no width. + +Built-in columns: + +| `key` | Column | Notes | +|-----------|---------|---------------------------------------------------------| +| `rank` | `#` | Place, computed by the client (6.4); always drawn first | +| `frags` | Frags | | +| `deaths` | Deaths | | +| `eff` | Eff | Also follows `hud_scoreboard_showeff` | +| `steamid` | SteamID | Also follows `hud_scoreboard_showsteamid` | +| `ping` | Ping | | +| other | — | The client ignores the column; the server accepts it | + +A `Builtin` column moves a standard column to its own position. Standard columns that the schema +doesn't mention keep their default places. `Hide*` flags win over a `Builtin` column. The client +ignores a `Hidden` `Builtin` column: the standard column keeps its default place, and a hidden +`rank` gives no place column. + +Column flags: + +| Bits | Name | Meaning | +|------|------------|--------------------------------------------------------------| +| 0 | `Hidden` | Data only: not drawn, still used for sorting and by elements | +| 1–2 | `Align` | 0 left, 1 center, 2 right; 3 is treated as left | +| 3 | `Primary` | The main score: `hud_scores` shows it instead of frags | +| 4 | `MarkLast` | `Steps`: the last step has its own color (6.6) | +| 5–15 | reserved | Sent as 0, ignored | + +A `Hidden` column can carry values for the whole game only, for example a game phase. The server +sends `sort = 0` and clears `Primary` for a `Badge` column. `Hidden` on a `Badge` column hides its +badges. + +#### `Values` (`0x03`) + +The payload is one target and its cells, which run to the end of the message: + +``` +Values := op:byte(0x03) target:byte Cell+ +Cell := column:byte Value +Value := type:byte len:byte payload:byte{len} +``` + +Targets: + +| Value | Target | +|---------------|------------------------------------------------------| +| `0x00` | The whole game | +| `0x01`–`0x40` | Player 1–64 | +| `0x81`–`0xC0` | Team 1–64, numbered like `teamnumber` in `ScoreInfo` | +| other | Reserved: the client ignores the message | + +Cell fields: + +- `column` is the column id. `0xFF` together with type `None` clears all cells of the target. +- `type` is the value type, see below. +- `len` is the payload length. The client always moves on by `len` bytes, so it can skip + types it doesn't know. + +Value types: + +| Value | Name | `len` | Payload | +|-------|------------|---------|--------------------------------------------------------| +| 0 | `None` | 0 | Nothing: clears the cell | +| 1 | `Int` | 1, 2, 4 | Signed integer, `len` bytes | +| 2 | `Text` | 1–32 | `string` | +| 3 | `Icon` | 2–64 | `string sprite`, `string text` | +| 4 | `Progress` | 2 or 4 | `cur`, `max`: two `byte` for `len` 2, two `word` for 4 | +| 5 | `Clock` | 5 | `long ms`, `byte flags`: bit 0 runs, bit 1 counts down | +| other | — | any | Unknown type: the cell is cleared | + +- A known type with a wrong `len` or a broken payload clears the cell. +- If the message ends in the middle of a cell, the client keeps the cells it has already applied + and drops the rest. +- Cells of columns that don't exist yet are stored and shown when the column arrives. +- `Icon.sprite` is a sprite name from `hud.txt`, the same names the kill feed uses (`d_9mmAR`), + or the path of a sprite file: `sprites/.spr`, at most 31 bytes of `[A-Za-z0-9_./-]` + without `..` (`IsSpriteFilePath`). The server sends both as they are; a plugin precaches its file + with `precache_generic` in `plugin_precache`, so clients download it. The client loads a file on + first use and draws its first frame whole (6.6). If the client doesn't have the sprite, it draws + only `text`. For standard HL weapon sprites the client shows its own weapon name instead of + `text` (10.3). +- `Progress` with `max = 0` is drawn as `cur`. +- `Clock` is a time the client runs itself, for timers that change every frame. On arrival the + client stores its own time `t0`. A stopped clock is `ms`; a running one is `ms + (now − t0)`, or + `ms − (now − t0)` when it counts down, and stops at 0. Its number is the current value in whole + seconds, rounded up when it has the "counts down" flag (running or stopped) and down otherwise; + `time2` (8.10) shows the milliseconds. + +Sort keys: `Int` uses the value, `Progress` uses `cur`, `Clock` its number, `Text` and `Icon` +compare text case-insensitively. Empty cells go after filled ones. + +#### `List` (`0x04`) + +A list is a named array of values that belongs to the whole game, for example the weapons of all +GunGame levels. + +``` +List := op:byte(0x04) id:byte total:byte start:byte key:string Value* +``` + +| Field | Type | Notes | +|---------|----------|----------------------------------------------------------| +| `id` | `byte` | 0–7, assigned by the server | +| `total` | `byte` | Number of items, 0–64; the client resizes the list to it | +| `start` | `byte` | Index of the first item in this message | +| `key` | `string` | Up to 15 bytes of `[a-z0-9_]`, unique: `levels` | +| items | `Value*` | Items `start`, `start + 1`, … up to the end of message | + +- A long list is split into several messages with different `start`. +- Items at `total` or beyond are dropped. An item of an unknown type is stored as empty. +- `total = 0` removes the list. +- Items added by a resize are always sent, as `None` if they were not set. + +#### `Element` (`0x05`) + +``` +Element := op:byte(0x05) id:byte kind:byte + flags:word x:short y:short align:byte place:byte parent:byte gap:byte + color:byte{4} font:byte select:string value:string list:string + count:byte Param{count} colors:byte ColorSlot{colors} +Param := id:byte value:short +ColorSlot := slot:byte r:byte g:byte b:byte a:byte +``` + +| Field | Type | Notes | +|-------------|----------------|------------------------------------------------------------------------------------------------------------| +| `id` | `byte` | 0–31, assigned by the server | +| `kind` | `byte` | See below; `None` and unknown values remove the element | +| `flags` | `word` | See below | +| `x` | `short` | Horizontal position in 1/8192 of the screen width; `-8192` (−1.0) is the center (8.4) | +| `y` | `short` | Vertical position, the same way | +| `align` | `byte` | Anchors: bits 0–1 horizontal, bits 2–3 vertical, see below | +| `place` | `byte` | What the position is relative to, see below | +| `parent` | `byte` | Element id for the parent places; `0xFF` otherwise or if the parent doesn't exist | +| `gap` | `byte` | Proportional units: distance to the parent, the margin on the numbers row (8.4), the padding of a `Box` | +| `color` | `byte` × 4 | r, g, b, a. With `HudColor` only `a` is used | +| `font` | `byte` | Font id (8.5); unknown ids mean 0 | +| `select` | `string` | A ref whose number picks the `Text` variant (8.10), `""` for variant 0, or the own row of a list `Board` | +| `value` | `string` | The bound ref: `{@value}`, the progress of a `Meter`, the icon of an `Icon`, the position of a `Strip`, … | +| `list` | `string` | `Strip`: key of the list with the icons; `Board`: key of the list of rows; `""` otherwise | +| `count` | `byte` | Number of params, 0–32 | +| `Param` | `byte` `short` | Param id and value (8.7–8.9, 8.13–8.16); unknown ids and params of other kinds are ignored, values clamped | +| `colors` | `byte` | Number of color slots, 0–10 | +| `ColorSlot` | `byte` × 5 | Slot 0–9 and r, g, b, a (8.5); the client skips slots of 10 and above | + +Kinds: + +| Value | Name | Draws | +|-------|---------|--------------------------------------------------------------------| +| 0 | `None` | Nothing: removes the element | +| 1 | `Text` | One line of text (8.6) | +| 2 | `Meter` | Dots, a bar or a ring of dots with a counter (8.7) | +| 3 | `Strip` | A row of cells with icons, optionally with the other players (8.8) | +| 4 | `Icon` | A sprite with a text after it (8.9) | +| 5 | `Board` | Rows of the scoreboard order or of a list (8.14) | +| 6 | `Feed` | Lines of `Event` messages (8.15) | +| 7 | `Box` | A backdrop behind the group of its parent (8.16) | +| other | — | Removes the element | + +- hl.so converts a screen fraction `f` from the plugin to `(int)floor(f · 8192 + 0.5)`, clamped to + −32768…32767. `x = −8192` exactly is the center. This is the fixed point of `TE_TEXTMESSAGE`, + which `set_hudmessage` also uses, but rounded instead of truncated: 0.025 is 205, not 204. +- A ref in `select` and `value` is a column key or a built-in value such as `@state` (8.11), + optionally with the prefix `^` and one of the formats `cur`, `max` and `left` (8.10): + `level:left`. The longest valid ref has 21 bytes: `^`, a key of 15 bytes and `:left`. With a + format the value is an `Int`: a `Meter` or an `Icon` bound to it has no content, a `Strip` uses + it as the position. `list` is a list key. +- The server keeps `parent` as a key and resolves it when it builds the message (5.1). +- With kind `None` the message ends after `kind`. + +Anchors: + +| Bits | Anchor | 0 | 1 | 2 | 3 | +|------|------------|------|------|--------|--------| +| 0–1 | Horizontal | auto | left | center | right | +| 2–3 | Vertical | auto | top | middle | bottom | + +Places: + +| Value | Name | Position | +|-------|----------------|-------------------------------------------------------------------------| +| 0 | `Screen` | `x`, `y` and the anchors | +| 1 | `Parent` | Below or above element `parent`; `x` and the horizontal anchor as usual | +| 2 | `NumbersRow` | On the row of the HL health, armor and ammo numbers; `x` as usual | +| 3 | `BannerTop` | Scoreboard banner, on the server name row (6.8) | +| 4 | `BannerBottom` | Scoreboard banner, on the map name row (6.8) | +| 5 | `ParentLeft` | Left of element `parent`, centered vertically on it | +| 6 | `ParentRight` | Right of element `parent`, centered vertically on it | +| other | — | Same as `Screen` | + +`Parent`, `ParentLeft` and `ParentRight` are the parent places (8.4). + +Flags: + +| Bit | Name | Meaning | +|------|----------------|--------------------------------------------------------------------------------------| +| 0 | `HudColor` | rgb follows `hud_color`; on a banner row, the scheme color of the row (6.8) | +| 1 | `Subject` | Needs a subject (8.2): hidden when there is none | +| 2 | `NoScoreboard` | Hidden while the scoreboard is open | +| 3 | `Leader` | The subject is the first row of the scoreboard order instead of the viewer's subject | +| 4–15 | reserved | Sent as 0, ignored | + +- The client ignores an `Element` with an id of 32 or more, and one that ends before `font`. A + missing string, or one without a NUL, means `""`. All `count` params are read while at least 3 + bytes remain, unknown ids and params of other kinds included, so the color block after them is + found; missing params take their defaults. A missing `colors` means 0, and slots are read while + at least 5 bytes remain. +- The server writes params in ascending id order. Params added in draft 3 have ids from 32 on, so + they follow all older ones. The color block always follows the params, with `colors` 0 when no + slot is set. +- A definition for an existing id replaces it. An `Element` never changes templates: the client + drops the templates of an id only on a removal (kind `None` or an unknown kind, for that id) and + on `Reset`. When the server drops the texts of an element, it sends a removal right before the + new definition (5.2). +- The largest message is a `Strip`, the kind with the most params, with every param and every + color slot: 18 fixed bytes, strings of 22, 22 and 16 bytes, 1 + 17 × 3 bytes of params and + 1 + 10 × 5 bytes of colors, 181 bytes. The server still refuses a change that would make an + `Element` longer than 192 bytes (9.2). + +#### `Template` (`0x06`) + +``` +Template := op:byte(0x06) id:byte variant:byte text:string +``` + +| Field | Type | Notes | +|-----------|----------|------------------------------------------------------------| +| `id` | `byte` | Element id | +| `variant` | `byte` | 0–7 | +| `text` | `string` | Template (8.10), up to 188 bytes; `""` removes the variant | + +- The client ignores a `Template` for an undefined element, a variant of 8 or more, and a text + without a NUL. The server always sends `Element` first. +- The server sends the text the plugin set for this player, or the default text (5.4). The client + doesn't know which one it got. +- The largest message is 192 bytes. + +#### `HudState` (`0x07`) + +``` +HudState := op:byte(0x07) visible:long hide:word +``` + +| Field | Type | Notes | +|-----------|--------|--------------------------------------------------------| +| `visible` | `long` | Bit per element id: the plugin shows the element (8.3) | +| `hide` | `word` | Standard HUD parts to hide (8.12) | + +The message is absolute: it replaces the previous state. After `Reset` and `VidInit` both fields +are 0. The server sends `HudState` after element definitions and templates (5.2), so elements +never appear before their texts. + +- `visible` is an unsigned 32-bit mask. Bits of undefined ids are stored and apply when the + element arrives. +- A `HudState` shorter than 5 bytes is ignored; a missing `hide` means 0. + +#### `Event` (`0x08`) + +``` +Event := op:byte(0x08) id:byte variant:byte life:word count:byte Value{count} +``` + +| Field | Type | Notes | +|-----------|---------|-------------------------------------------------------------------------| +| `id` | `byte` | Element id of a `Feed` | +| `variant` | `byte` | Template variant of the line, 0–7 | +| `life` | `word` | How long the line is shown, ms; 0 is the `life_ms` param of the element | +| `count` | `byte` | Number of args; the client reads at most 5 | +| `Value` | `Value` | Args in the encoding of `Values`: `type`, `len`, payload | + +- An event is not state. The client ignores it unless element `id` exists, is a `Feed` and has a + template for `variant`. It evaluates that template once, on arrival, for the subject of the + element (8.2) with the args as `@a`–`@d` and `@icon` (8.11), and keeps the result as a line + stamped with its own time (8.15). +- The first arg of type `Icon` is also the icon of the line. An arg of an unknown type, with a wrong + `len` or a broken payload keeps its position as an empty value. An `Event` with a short header, + or one that ends before its first `min(count, 5)` args are read, is ignored. +- A line whose template evaluates to nothing (a missing value, 8.10) and that has no icon sprite is + dropped. +- Lines change no serial and are never replayed by a full sync. They are dropped with their element + (a removal, `Reset`, `VidInit`, the loss of `ScoreboardV1`). The client keeps 32 lines over all + elements; a new line replaces the oldest one. +- An event takes 6 bytes plus `2 + len` per arg. The natives send at most 4 `Int` args and an + `Icon`, at most 96 bytes. The server sends events last (5.2, 5.6). + +### 4.4 Example: one GunGame row + +Player 5 is on level 12 of 24 with the MP5 and has 1 of 3 kills. Column ids: `level` 1, +`weapon` 2, `progress` 3. + +``` +03 op Values +05 target: player 5 +01 04 02 0c 18 level: Progress, len 2, cur 12, max 24 +02 03 0c 64 5f 39 6d 6d 41 52 00 weapon: Icon, len 12, sprite "d_9mmAR" + 4d 50 35 00 text "MP5" +03 04 02 01 03 progress: Progress, len 2, cur 1, max 3 +``` + +The message takes 27 bytes. With the `kills` and hidden `score` cells (8–10 more bytes) it takes +35–37 bytes. Every target gets its own message, so a full sync of 32 players sends 32 `Values` +messages. + +### 4.5 Example: one element + +The place line of GunGame: a `Text` element at the top center, large font, `hud_color`. Its +variant is chosen by the `phase` cell, and `{@value}` in its templates is the `phase_left` cell. + +``` +05 op Element +00 01 id 0, kind Text +07 00 flags: HudColor, Subject, NoScoreboard +00 e0 x = -8192: center +cd 00 y = 205: 0.025 · 8192 = 204.8, rounded +00 00 align: auto anchors; place: Screen +ff 00 no parent, gap 0 +00 00 00 ff color: rgb ignored (HudColor), alpha 255 +01 font: HudServerLarge +70 68 61 73 65 00 select "phase" +70 68 61 73 65 5f 6c 65 66 74 00 value "phase_left" +00 list "" +00 no params +00 no color slots +``` + +The message takes 38 bytes. GunGame also sets four params of 8.13 on this element (9.3), so its +`count` is 4 and 12 bytes of params follow. Variant 0 with a client token takes 18: + +``` +06 00 00 op Template, element 0, variant 0 +23 42 48 4c 5f 48 55 44 5f 50 6c 61 63 65 00 "#BHL_HUD_Place" +``` + +### 4.6 Sizes for GunGame + +| Message | Bytes | +|--------------------------------------------|-------------------------------| +| `Reset` | 1 | +| `Config` | ~8 | +| `Column` × 9 | ~14–34 | +| `List` `levels`, 24 levels | 2 × ≤ 192 | +| `Values`, 32 players | 32 × 33–51 | +| `Element` × 10 | 26–50, ~370 in all | +| `Template` × 17, plugin texts in Russian | 18–115, ~850 in all | +| `HudState` | 7 | +| Level-up of one player | ~32, +17 when `final` changes | +| `Event` of a level change, to each `HudV1` | 6–~40 | +| Kill without level-up | ~17 | +| Warmup second | ~7 | +| Warmup start or end | ~190 | + +At the start and the end of the warmup the GunGame plugin sends the `level`, `weapon`, `progress`, +`kills` and `score` columns again, changes the visible elements and the `flash_ms` of `gg_place` +(9.3). The banner needs no traffic until the win: its rows are chosen by the leader's `level` cell +(9.3). + +### 4.7 Limits + +| What | Limit | +|-----------------------------------|------------------------------------------------| +| Message payload | 192 bytes | +| Columns | 32 (ids 0–31) | +| Lists | 8 (ids 0–7) | +| List items | 64 | +| Column and list `key` | 15 bytes | +| Column title | 31 bytes | +| Config title | 63 bytes | +| Config tag | 15 bytes | +| `Text` value | 31 bytes | +| `Icon` sprite and text | 31 bytes each | +| Dots in a scoreboard `Meter` | `max ≤ 10` | +| Elements | 32 (ids 0–31) | +| Element key (server only) | 15 bytes of `[a-z0-9_]` | +| Ref in `select` and `value` | 21 bytes (4.3) | +| Params per element | 32 (ids 0–63); at most 17 exist for one kind | +| Color slots per element | 10 (slots 0–9) | +| Variants per element | 8 | +| Template | 188 bytes | +| Placeholders per template | 16 | +| Evaluated text | 255 UTF-16 units | +| `Board` rows | 16 by `rows`, plus the separator and own row | +| `Board` text columns | 4 | +| `Feed` lines shown | 8 by `lines` | +| `Feed` lines kept by the client | 32 over all elements | +| Args of an `Event` | 5 read; the natives send 4 `Int` and an `Icon` | +| Events queued per client (server) | 8, the oldest is dropped | +| Sprite files per game (client) | 32 different paths | + +String limits are in bytes, without the terminating NUL. + +## 5. Server behaviour + +### 5.1 State + +One object in `hl.so`, `CScoreboardExt`, holds the config, the columns, the lists, the cells of +the whole game, every player and every team, the HUD elements with their default templates and +visibility, the hidden standard HUD parts, and the per-player overrides of templates and +visibility (5.4). For each client it also keeps `caps`, their source, a `ready` flag (set after +`InitHUD`), pending `Reset`, header, elements and templates, the sent HUD state, and sets of dirty +cells and list items. Apart from this sync state it keeps a queue of events for each client (5.6). + +- Column masks have 32 bits, one per column id. The mask of all columns is built without + `1u << 32`, which is undefined in C++. The params of an element have a 64-bit mask + (ids 0–63), its color slots a mask of 10 bits. +- Element parents and badge hosts are stored as keys and resolved to ids when a message is built, + `0xFF` when the key doesn't exist. Adding, removing or re-adding an element or a column marks + pending every element or badge column that names it. + +The extension is active from the first `Config`, element or hidden standard part until the plugin +resets it or the map changes. While it is inactive, a client gets only `Reset`. + +All plugins share this one state. Columns, lists and elements of different plugins live side by +side when their keys differ, so a plugin prefixes its keys (`gg_`). `bhl_sb_reset()` clears the +whole state, of every plugin. + +### 5.2 Sending + +Plugins only change the state and mark the changes pending for every ready client. In +`StartFrame` the server walks the ready clients that have `ScoreboardV1` and sends: + +1. `Reset`, if one is pending; +2. `Config`, if it is pending, and every pending `Column`; +3. the dirty list items packed into `List` messages; +4. the dirty cells, one `Values` message per target (more when its cells don't fit in 192 bytes); +5. every pending `Element`: definitions and removals; +6. every pending `Template`, with the text for this client; +7. `HudState`, if it differs from what the client has, with the visibility for this client; +8. the queued events of this client, in order (5.6). + +A client gets at most about 512 bytes per 0.1 s, so the rate stays about 5 KB/s at any server +fps. When they are used up, nothing more is sent to it until the 0.1 s is over. Small updates go +out in the frame they happen while the budget lasts. Several changes of one cell, element, +template or visibility in one frame produce one message. A setter that writes the value already +stored marks nothing, but a write for player 0 still drops the overrides (5.4). A running `Clock` +runs from the call, so setting it again restarts it even with the same values. It is sent with the +time it has run since then, a countdown stopping at 0, so a client that gets it later, after the +budget or in a full sync, shows the same time. + +A new element gets the lowest free id that no client still has anything of (the old element, its +visibility bit, a child placed at it); only when every free id is held is the lowest free id +reused. When the server drops the texts of an element (removal, kind change), a client that has +the element gets `Element` kind `None` for that id right before the new definition, both in one +frame or neither; then only non-empty variants are sent. A variant whose text is removed is sent as +`""`, and only to a client that holds that variant. Templates of an id with no element are not +sent. So a new element never shows old variants. A removal goes only to a client that has the +element, and `HudState` only to a client whose visibility or hidden parts differ from what it has. + +### 5.3 Full sync + +A full sync is `Reset`, the header, every list item, every non-empty cell, every element, every +template this client should have and `HudState`, marked pending for that client. Events are not +part of it: a full sync neither clears the event queue nor replays sent events (5.6). It starts: + +- about 0.5 s after `InitHUD` of a client with `ScoreboardV1` (while the extension is inactive + only `Reset` is sent); +- when `ScoreboardV1` appears after `InitHUD`; +- for every ready client, when a plugin turns the extension on in the middle of a map (a client + that is still in its 0.5 s wait after `InitHUD` keeps it). + +`InitHUD` already sends `ScoreInfo` and `TeamInfo` for every player and the MOTD. The engine +moves a client's reliable buffer (about 4 KB on HLDS) out only after the previous reliable message +is acknowledged, so the sync is paced by time, not by frames, to avoid `Reliable channel +overflowed`: it starts after the `InitHUD` burst and drains at about 5 KB/s. With 32 players a +GunGame sync is about 3.3 KB and takes about 0.7 s. + +### 5.4 Per-player texts and visibility + +Templates and element visibility have a default and optional overrides for single players: + +- A write for player 0 sets the default and drops the overrides of the same template variant, or + of the same visibility bit, for every player: the last write wins. It always drops them, even + when the default doesn't change. Only clients whose effective value changed get a message. +- A write for player N sets an override for that client only. An override equal to the default + is dropped. +- Each client gets its override if it has one, otherwise the default. +- Overrides are cleared when the player slot is cleared (connect, disconnect), when the element is + removed, on reset and on map change. A kind change clears the text overrides of the element and + keeps the visibility ones (9.2). +- The overrides are kept apart from the per-client sync state, because a full sync resets that + state. + +The hidden standard HUD parts have no overrides. + +### 5.5 Events + +| Event | Server | +|-----------------------------|-------------------------------------------------------------------------------------------| +| Map change | State and event queues are cleared; the plugin sets everything again | +| Plugin resets the extension | `Reset` to every ready client; event queues are cleared; the extension is off | +| Plugin removes an element | `Element` with kind `None`, for each removed element the client has | +| Player disconnects | Slot cells, overrides and event queue are cleared; `0xFF`/`None` for the slot to everyone | +| Player changes team | Nothing: placement comes from `TeamInfo` and `ScoreInfo` | +| Client loses `ScoreboardV1` | Nothing more is sent to that client | + +A client dropped before it spawned (while it loads the map or downloads) counts as a disconnect +too; the server notices it in the next frame. + +### 5.6 Event queue + +`HudEvent` (`bhl_hud_event`, 9.2) doesn't change the state. It builds one `Event` and puts it into +the queues of the clients that get it, at the moment of the call: + +- player 0: every client that is ready, has `ScoreboardV1` and `HudV1`; player N: that client only, + if so. A client that gets these caps or becomes ready later never gets the event. +- Each client has a queue of 8 events, kept apart from its sync state. When it is full, the oldest + event is dropped. +- The event names its element by key. The key is looked up when the event is sent, after + `HudState` (5.2), within the same budget. The first event of the queue waits, and the events + after it with it, while that element doesn't exist, is not a `Feed` or was not sent to this + client yet (for example during its full sync). +- An event older than its life is dropped unsent: `life`, or for 0 the `life_ms` param the plugin + set on the element, else its default from `PARAM_INFO` (5000 ms). +- The queues are cleared on map change, on `bhl_sb_reset()` and when the slot is cleared (connect, + disconnect). A full sync neither clears nor replays them. +- The server refuses an event longer than 192 bytes; with the natives' arguments it never is. + +## 6. Client behaviour: scoreboard + +### 6.1 Store + +The store, `CScoreboardData`, holds the schema, cells, lists, elements, templates and the HUD +state. It is cleared on `VidInit`, on `Reset` and when the client clears `ScoreboardV1` in `_bhl` +(3.2). A player's cells are cleared when the slot becomes empty, even if the server didn't say so. + +### 6.2 Activation + +The custom scoreboard is shown when a `Config` arrived after the last `Reset` or `VidInit` and +`hud_scoreboard_custom` is 1. Otherwise the standard scoreboard is shown; incoming data is still +stored and HUD elements still use it. + +### 6.3 Layout + +- Column order: `rank`, Avatar, Name, then SteamID, Eff, Frags and Deaths at their default places + unless the schema moves them, then custom and `Builtin` columns by `id`, then Ping unless moved. + Hidden standard columns, `Hidden` custom columns and `Badge` columns are left out. +- The panel keeps the size, place, frame and header of the standard scoreboard (`ScorePanel.res`). +- Name takes all free width. If the other columns need more, Name shrinks down to 100 units + (`column_name_min`), then down to 80 units; columns that still don't fit are dropped from the + end. +- While a `Steps` column is visible, rows are taller so the strip fits under the text. +- The content of a custom cell (and the title of a custom column) leaves `cell_margin` (6 units) + free at its right, so a strip or a long text doesn't touch the next column. +- Team section headers show team cells in the same columns as text only, without icons, dots or + strips: `Icon` as its name, `Progress` as `cur/max`. A `Meter` column with `max ≤ 10` stays + empty, like dots without a counter. Badges of team cells follow their host cell as in player + rows (6.7). Team frags and deaths follow the `Hide*` flags. + +### 6.4 Sorting and places + +- Players inside a section and the teams are sorted by the sort keys in priority order. Ties fall + back to the standard order (frags descending, deaths ascending), then to the player index or the + team number, ascending. Teams are sorted by team cells; a team without cells keeps the standard + order. +- Team frags and deaths come from `TeamScore`; until the server sends one, they are the sums over + the team's players, as in the standard scoreboard. +- Participants are connected players that are not spectators; bots count. +- The number of a player or a team is its first-key `Int`, `Progress.cur` or `Clock` seconds. + Without sort keys it is its frags, and larger is better. +- The place in the `rank` column depends only on the first sort key: 1 + the number of entities + whose first-key cell sorts strictly before, compared as the column sorts, so equal values share a + place (`1, 1, 3`). An entity with an empty first-key cell has no place. Further keys only order + the rows. Without sort keys equal frags share a place. +- Team mode: with sort keys, at least one team with participants has a non-empty first-key team + cell; without sort keys, at least one participant is in a team. In team mode the ranked entities + are the teams with participants, the first row is the first of them in team order, and the + ranked entity of any player is his team. Otherwise the ranked entities are the participants, the + first row is the first participant in player order, and the ranked entity of a player is the + player. +- With team sections the place is shown in the team header and counted among teams; player rows + leave `rank` empty. Without teams the place is shown in player rows. +- The store computes the order, so HUD elements with `Leader` (8.2) and `^` refs (8.10) work with + the standard scoreboard too. + +### 6.5 `hud_scores` + +With an active schema, `hud_scores` uses the first `Primary` column (lowest `id`) that isn't +`Hidden`, `Builtin` or `Badge`. It shows that column as text instead of frags and sorts the same +way as the scoreboard. Without such a column it doesn't change. + +### 6.6 Drawing + +- `Icon`: the sprite from `hud.txt` or a sprite file, scaled to the row height with its aspect + ratio kept and tinted with `cell_icon_color` (orange like the dots by default). The text follows + to the right. The icon is drawn additively, like the HUD: with OpenGL through TriangleAPI, which + sets its own blending (VGUI2 stops blending once a row has drawn text). The software renderer + gets a VGUI2 texture that the client reads from the sprite file and scales to the drawn size + itself; its pixels brighter than 48 are opaque and the rest transparent, because it is drawn + without blending. HUD element icons are drawn the same way. With OpenGL `CHudRenderer` leaves + blending off after a sprite, so `HudServerPanel` sets `kRenderTransTexture` again after each of + its sprites: the shapes it draws later in the same pass (a `Box`, a `Board` plate) stay blended. +- Sprite files (4.3) are loaded the first time a value names them. The client reads and checks the + file itself (an HL sprite whose first frame is a single frame of at most 1024 × 1024) and only + then calls `SPR_Load`, so a missing or broken file never reaches the engine, which would stop + with an error. The whole first frame is drawn. Paths are matched without case; up to 32 + different paths per game get an index, more are not drawn. A failure is remembered until the + next `VidInit`, after which every file is loaded again on its next use. +- `Meter` keeps the dot look of the scoreboard, which is not the HUD `Meter` (8.7). Dots are discs + of `cell_dot_size` with `cell_dot_gap` between them, smaller when the column or the row is too + small for 10 of them: + - `max ≤ 10`: `cur` dots in `cell_filled_color` and `max − cur` dim ones in `cell_empty_color`, + without a counter; + - `max > 10`: a rounded bar of the same length as 10 dots in `cell_empty_color`, filled to + `cur / max` (at least one dot) in `cell_filled_color`, with the `cur/max` counter to the right. +- `Steps`: `cur/max` as text; below it a strip of `max` segments. Segments before `cur` are + filled, segment `cur` is highlighted, the rest are dimmed. With `MarkLast` a dimmed last segment + uses `cell_last_color`. When the column has less than 2 pixels per segment, the strip is one bar + filled to `cur / max`. +- `Progress` in a `Text` column: `cur/max`. +- `Clock` in any column: written with `time` (8.10). A running clock is refreshed at least once a + second while the scoreboard is open. +- Plugin strings (the title, column titles, cells, badges and banner rows) are drawn as they are: + `&` is an ordinary character, not a VGUI2 hotkey mark. + +### 6.7 Badges + +- A non-empty cell of a `Badge` column is drawn as a badge after the content of the cell of + column `host`, with the look of the tag badge (`badge_font`, `badge_bgcolor`, `badge_fgcolor`). + This holds in player rows with player cells and in team headers with team cells, so in GunGame + teamplay the `final` badge follows the team's weapon. +- The badge text is the cell drawn as text: a `#token` is localized. +- A badge is drawn even when the host cell is empty. In a narrow column the text of the host cell + is cut first; badges that still don't fit are left out. +- No badge is drawn when the `Badge` column is `Hidden`, or when `host` is missing, hidden, + `Builtin` or a `Badge` column, or is cut off by the layout. Several badges after one cell are + drawn in `id` order. + +### 6.8 Banner + +The custom scoreboard has a banner in its header, left of the player count, on the rows of the +server name and the map name. Its two rows are `Text` elements placed `BannerTop` and +`BannerBottom`. The plugin decides what a row says and when, through templates, `select` and +visibility; the client knows no game mode. + +- A row shows the lowest-id `Text` element with that place that is visible in `HudState` and whose + text is not empty. +- `Subject` and `Leader` apply as on the screen (8.2). A row with `Leader` is not drawn when there + are no participants. `x`, `y`, `align`, `gap`, `font` and `NoScoreboard` are ignored. + `hud_server_elements` and the other rules from 8.3 don't apply: the banner belongs to the + scoreboard. +- `Icon`, `Meter` and `Strip` elements with a banner place are not drawn. +- The banner is drawn when at least one of its rows is drawn. +- Look: a box (`banner_bgcolor` 255 64 32 48) with an accent bar on the left + (`banner_accent_color` 255 160 0 255, `banner_accent_wide` 2, `banner_padding` 1). The rows use + the fonts of the server name and the map name labels. With `HudColor` the top row uses + `banner_accent_color` and the bottom row the header text color; otherwise rows use the element + color. +- Layout: + - the right edge is at the left edge of the player count text, minus the spacing and the padding; + - rows are cut so that the map name and a third of the server name stay visible; + - the server name is narrowed so that the name and the tag end before the banner; + - the banner is laid out again whenever the evaluated text of a row changes, and on every change + of the header (server name, map name, player count, tag). + +## 7. Client behaviour: standard scoreboard + +Without an active schema the scoreboard is the same as now. The place column appears only when a +schema adds the built-in `rank` column. With a schema the scoreboard keeps the standard look: size, +place, header, fonts, column titles and row highlights. + +## 8. HUD elements + +### 8.1 Model + +The client draws elements in one full-screen VGUI2 panel, `HudServerPanel` (`CHudServerPanel`). +An element has: + +- a kind: `Text`, `Icon`, `Meter`, `Strip`, `Board`, `Feed` or `Box`; +- a place and a position (8.4), a color, color slots and a font (8.5); +- flags (4.3); +- refs to the data it shows: `select`, `value` and `list`; +- kind parameters and the params of every kind (8.13), with defaults in `HudServerPanel` of + `HudLayoutBase.res` that users can override in `HudLayout.res` (a param sent by the server wins); +- up to 8 template variants; +- a visibility bit set by the plugin. + +Elements are drawn in two passes. The first pass draws every `Box` (8.16), then, in id order, the +shapes and sprites of all other elements (`Meter` dots, bars and rings, `Strip` cells, item icons +and track discs, `Icon` sprites, `Board` plates, fill bars and icons, `Feed` icons). The second pass +draws, in id order, all texts (`Text` elements, `Meter` counters, `Icon` texts, `Strip` item texts, +scroll markers and track counts, `Board` rows, `Feed` lines). A text is therefore always drawn above +any shape or sprite, and a `Box` below all of them, whatever the ids. + +The client has no conditions and no game logic: the plugin shows and hides elements, and a choice +that depends on the subject comes from a value through `select` or from the missing-value rule +(8.10). Texts are evaluated every frame, so a changed cell needs no HUD traffic. + +### 8.2 Subject + +| Viewer | Subject | +|----------------------------------------------------------------------------------|----------------------------------| +| Not observing (`g_iUser1 = OBS_NONE`) | The local player | +| Spectator in `OBS_CHASE_LOCKED`, `OBS_CHASE_FREE`, `OBS_IN_EYE`, `OBS_MAP_CHASE` | The observed player (`g_iUser2`) | +| Spectator in `OBS_ROAMING` or `OBS_MAP_FREE` | None | + +- The subject must be connected and not a spectator. A dead player is still a subject. +- With `Leader` the subject is the first row (6.4): a team in team mode, otherwise a player. + Without participants there is no subject. +- The ranked entity (8.11) of a player subject is his team in team mode (6.4), otherwise the + player. A team subject is its own ranked entity. In team mode a player without a team is not + ranked: `@place`, `@state`, `@behind`, `@score` and the rival values are missing. +- Without a subject, refs read global cells only and built-in values that need a subject are + missing. + +### 8.3 Visibility + +An element on the screen (places `Screen`, `NumbersRow` and the parent places) is drawn when all of +these hold: + +1. `hud_server_elements` is 1. +2. `hud_draw` is above 0, there is no intermission and no `HIDEHUD_ALL`. +3. Its bit is set in `HudState.visible`. +4. With `Subject` there is a subject; with `Leader` there are participants. +5. With `NoScoreboard` the scoreboard is closed. +6. It is placed (8.4). +7. It has content: a `Text` evaluates to a non-empty text; an `Icon` has an `Icon` value and either + a sprite the client has or a non-empty text (8.9); a `Meter` value is `Progress` with `max > 0`; + a `Strip` has `count > 0` and a numeric position; a `Board` has at least one row (8.14); a + `Feed` has a live line (8.15); the group of a `Box` draws something (8.16). +8. With `hold_ms`, the hold since it appeared or changed has not run out (8.13). + +An element with `fade_ms` that stops being drawn because of rules 3–8 fades out, drawn as it was +in its last frame (8.13). Rules 1 and 2, a removal and a kind change hide it at once. + +Banner rows follow 6.8. + +Visibility belongs to the viewer, not to the subject: a spectator sees the elements the plugin +shows to him, with the data of the observed player. + +### 8.4 Placement + +``` +P(v) = (int)(v · H / 480) proportional units, vgui2::scheme()->GetProportionalScaledValue +fx = x / 8192 fy = y / 8192 +W, H screen size; w, h: size of the element's box +``` + +Horizontal position, for places `Screen`, `Parent` and `NumbersRow`: + +| `x` | Reference point | Auto anchor | +|-------------|-----------------------|-------------| +| `−8192` | `W / 2` | center | +| other `< 0` | `(int)((1 + fx) · W)` | right edge | +| `≥ 0` | `(int)(fx · W)` | left edge | + +An explicit anchor puts the left edge, the center or the right edge of the box on the reference +point. These rules are the rules of `set_hudmessage`. + +Vertical position: + +- `Screen`: the same rules with `y`, `fy` and `H`; the auto anchors are middle, bottom edge and top + edge. +- `Parent`: the vertical anchor picks the side. Auto, top and middle put the child below the + parent: `top = parent bottom + P(gap)`. Bottom puts it above: `bottom = parent top − P(gap)`. + `y` is ignored. +- `ParentLeft`: the right edge of the box is at `parent left − P(gap)`. `ParentRight`: the left + edge is at `parent right + P(gap)`. The box is centered vertically on the parent; `x`, `y` and + the anchors are ignored. +- `NumbersRow`: + - `rowH = gHUD.m_iFontHeight` (it follows `hud_scale`), `rowTop = H − rowH − rowH / 2`; + - the side zones are `[0, 15 · digitW + P(gap))` and `(W − 15 · digitW − P(gap), W]`, where + `digitW` is the width of the `number_0` sprite, and `free` is the width between them; + - with `hud_custom 1` the left zone ends at the right edge of the health and battery panels plus + `P(gap)`, the right zone starts at the left edge of the ammo panel minus `P(gap)`, and `rowTop` + and `rowH` are the top and the height of these panels together. These zones are not + symmetric: a centered box crosses the nearer zone before it fills `free`, so a long `Strip` + is lifted above the row; + - normally the box is centered on the row: `top = rowTop + (rowH − h) / 2`; + - a `Strip` first shrinks to `free` (8.8); a box that then intersects a side zone where it is + drawn (after it is moved inside the screen) is lifted: `bottom = rowTop − P(gap)`. + +Every box is then moved inside the screen, like `set_hudmessage` does. + +Order and fallbacks: + +- Elements are laid out parents first, so a child uses the box of its parent after the parent was + moved inside the screen. +- A parent's box counts even when the parent is not drawn: an empty `Text` box has the height of + its font. Children don't move when a parent's text is empty or hidden. +- An element is unplaced when its parent is undefined, has a banner place, is a `Box`, is the + element itself, is part of a cycle or is unplaced. A `Box` without a parent place is unplaced + too. An unplaced element is not drawn and has no box. +- A `Box` takes its box from its group (8.16): `x`, `y`, the anchors and the rules of its place + don't apply to it, and `gap` is its padding. + +Sizes and gaps are proportional units of a 640×480 screen, `P()`, like `.res` files. They don't +follow `hud_scale`. Positions are screen fractions, so `y = 0.025` (205) gives the same pixel as +`P(12)` at the common screen heights. + +### 8.5 Color and fonts + +- Color: with `HudColor` the rgb comes from `hud_color` (`HudPart::Common`), otherwise from the + message. +- Color slots (4.3) are set by `bhl_hud_slot_color` (9.2). A slot color is used as it is, r, g, b + and a, also by an element with `HudColor`, and replaces the whole color while it applies: + + | Slot | Name | Applies | + |------|----------|-------------------------------------------------------------------------------| + | 0–7 | Variants | While that variant is drawn (see below) | + | 8 | `Warn` | While `warn_at` holds (8.13); without the slot `255 64 32 255` | + | 9 | `Accent` | The accent bar of a `Box` (8.16); without the slot the `hud_color` rgb at 255 | + | 10+ | — | Skipped by the client | + + The drawn variant is the one `select` picks for a `Text`, always 0 for an `Icon` and a `Meter`, + and the variant of each row of a `Board` and of each line of a `Feed`, which then have their own + colors. A `Strip` and a `Box` use no variant slots. +- Order: the element color (or `hud_color`), the variant slot, the warn color, then the flash + toward white (8.13). While warning, `Board` rows and `Feed` lines use the warn color too, not + their variant slots. +- Alpha: `part · a / 255 · GetHudTransparency() · fade · pulse`, where `part` is 255 or the alpha + of a `Meter`, `Strip` or `Board` part or of a `Feed` line, `a` is the alpha of the color in use, + and `fade` and `pulse` come from `fade_ms` and `warn_pulse_ms` (8.13), 1 without them. +- Fonts are a fixed set of entries in `ClientSchemeBase.res`. Users can change them in + `ClientScheme.res`. + + | Id | Font | Look | Tall at yres 480 / 600 / 768 / 1024 / 1200+ | + |----|------------------|-------------|---------------------------------------------| + | 0 | `HudServerText` | Verdana 600 | 12 / 13 / 14 / 20 / 24 | + | 1 | `HudServerLarge` | Verdana 800 | 16 / 18 / 20 / 28 / 34 | + | 2 | `HudServerSmall` | Verdana 600 | 10 / 11 / 12 / 16 / 18 | + | 3 | `HudServerHuge` | Verdana 800 | 24 / 28 / 32 / 44 / 52 | + +- Text is drawn through the VGUI2 surface, so Cyrillic and scaling work. + +### 8.6 `Text` + +- One line: the evaluated template of the chosen variant (8.10). Line breaks are drawn as spaces. +- The box is the text width × the font height, with width 0 for an empty text. +- No kind params; the params of every kind apply (8.13). The slot of the chosen variant colors the + line (8.5). + +### 8.7 `Meter` + +`value` must be a `Progress` with `max > 0`; `cur` is clamped to `[0, max]`. + +| Id | Param | Default | Range | Meaning | +|----|---------------|---------|-------|-----------------------------------------------------------------------| +| 1 | `dots` | 10 | 0–32 | `max ≤ dots`: dots; otherwise a bar. 0: always a bar | +| 2 | `dot_size` | 7 | 2–64 | Diameter of a dot, height of the bar | +| 3 | `dot_gap` | 3 | 0–64 | Distance between dots | +| 4 | `bar_wide` | 0 | 0–640 | Length of the bar; 0 is the length of `dots` dots, or 10 for 0 dots | +| 5 | `counter` | 1 | 0–2 | Counter: 0 never, 1 with the bar, 2 always | +| 6 | `counter_gap` | 6 | 0–64 | Distance between the box and the counter | +| 7 | `alpha_empty` | 80 | 0–255 | Empty part of the bar | +| 40 | `form` | 0 | 0–1 | 0: dots or a bar in a line; 1: a ring of dots with the counter inside | + +- After scaling a dot is `dot = max(2, P(dot_size))`. +- Dots: `max` dots of `dot` with `P(dot_gap)` between them. Dots before `cur` are filled + anti-aliased discs, the rest are rings with a width of 1/6 of the diameter, all at alpha 255. +- Bar: a rounded bar (half-disc caps) at `alpha_empty`. When `cur > 0`, a fill of width + `max(w · cur / max, dot)` at alpha 255. +- The box is the row of dots or the bar. Without a `Progress` value with `max > 0` the box is + 0 × `dot` and nothing is drawn. The counter stands outside the box, so the anchor keeps the box + in place when the form changes. +- Ring (`form` 1), with `d = dot` and `g = P(dot_gap)`: + - `n = max` dots when `max ≤ dots`, otherwise `dots`, or 10 for `dots` 0; + - `filled = cur` when `n = max`, otherwise `cur · n / max` rounded half up; + - the box is `D × D` with `D = max(3 · d, ceil(n · (d + g) / π) + d)`; + - dot `i` has its center at the angle `−90° + 360° · i / n` (dot 0 on top, then clockwise) on a + circle of radius `(D − d) / 2` around the center of the box, rounded to whole pixels; + - the first `filled` dots are discs, the rest rings, as in a line of dots, all at alpha 255; + `bar_wide` and `alpha_empty` are not used. +- Counter: + - the text is variant 0, or `{@value:cur} / {@value:max}` when the element has no variant 0; + variants 1–7 are never used; + - `counter` 1 shows it with the bar, and in the ring form whenever `n ≠ max`; + - it uses the element font and is centered vertically on the box; + - its left edge is at `box right + P(counter_gap)`; when the resolved horizontal anchor of the + box is the right edge (an explicit right anchor, an auto anchor with a right-edge reference + point (8.4) or the place `ParentLeft`), its right edge is at `box left − P(counter_gap)`; + - in the ring form it is centered in the ring instead, and `counter_gap` is not used. +- Slot 0 colors the dots, the bar, the ring and the counter (8.5). + +### 8.8 `Strip` + +| Id | Param | Default | Range | Meaning | +|----|---------------------|---------|---------------|----------------------------------------------------| +| 10 | `cell_wide` | 30 | 1–255 | Width of a cell | +| 11 | `cell_min_wide` | 14 | 1–`cell_wide` | Cells shrink down to this width | +| 12 | `cell_tall` | 15 | 1–255 | Height of a cell | +| 13 | `cell_gap` | 3 | 0–64 | Distance between cells | +| 14 | `icon_padding` | 2 | 0–64 | Padding of the icon inside a cell | +| 15 | `max_wide` | 300 | 0–4096 | Width limit; 0 is the screen width | +| 16 | `alpha_passed` | 112 | 0–255 | Cells before the current one | +| 17 | `alpha_current` | 48 | 0–255 | Current cell | +| 18 | `alpha_future` | 24 | 0–255 | Cells after the current one | +| 19 | `alpha_icon_future` | 80 | 0–255 | Icons and texts of the cells after the current one | +| 20 | `frame` | 1 | 0–1 | 1: the current cell has a 1 px frame at 255 | +| 41 | `track` | 0 | 0–1 | 1: markers of the other players above their cells | + +Inputs: + +- `count` is the number of items of `list`, or the `max` of the `value` `Progress` without a list + (also when no list has that key); at most 64. +- The position is the `value`: `Progress.cur` or another number (8.10), 1-based. + `cur = clamp(position − 1, 0, count − 1)`. +- Items: + - an `Icon` item draws its sprite from `hud.txt` or a sprite file (4.3, 6.6), cached until the + store changes; a sprite the client doesn't have leaves the cell empty; + - any other item is drawn as text (8.10) centered in its cell, in the element font; + - an empty item, or a cell without a list, is an empty cell. + +Layout: + +``` +gap = P(cell_gap) +cmin = max(1, P(cell_min_wide)); cmax = max(cmin, P(cell_wide)) +mw = P(max_wide), or W when max_wide is 0 +free = place NumbersRow ? the width between the side zones (8.4) : infinite +minWide = count · cmin + (count − 1) · gap +lifted = place NumbersRow && minWide > free && free < mw +maxWide = lifted ? mw : min(mw, free) +cell = clamp((maxWide − (count − 1) · gap) / count, cmin, cmax) +shown = count; first = 0 +if minWide > maxWide: + marker = width of "‹" in the element font + gap + shown = clamp((maxWide − 2 · marker + gap) / max(cmin + gap, 1), 1, count) + first = clamp(cur − shown / 2, 0, count − shown) +box = shown · cell + (shown − 1) · gap × P(cell_tall) +``` + +With `count = 0` these formulas are not used: the box is 0 × `P(cell_tall)` and nothing is drawn. + +Drawing: + +- Cells are filled rectangles: `i < cur` at `alpha_passed`, `i = cur` at `alpha_current`, the rest + at `alpha_future`. With `frame` 1 the current cell has a 1 px frame at 255. +- An icon fits inside `cell − 2 · P(icon_padding)` with its aspect ratio kept and is centered. Icons + and texts are drawn at 255, or at `alpha_icon_future` after the current cell. +- When cells are hidden at an end, `‹` stands left of the box or `›` right of it, at `gap`, in the + element font, centered vertically on the cells. + +Track (`track` 1): + +- For every participant (6.4) other than the subject player, the client reads the `value` ref of + the strip for that player, as the position is read for the subject, and counts the players on + each cell: `clamp(position, 1, count) − 1`. A player without a number is not counted. With a team + subject (`Leader` in team mode) every participant counts. +- Above every shown cell with `n > 0` players stands a marker, centered on the cell, its bottom + `P(2)` above the top of the cell: `n` discs of `max(2, P(4))` with `P(2)` between them for `n` 1 + and 2, the text `×n` in the element font for 3 and more. Markers use the element color at 255. +- Like the counter of a `Meter`, the markers stand outside the box: the box and the layout don't + change. +- The counts are computed every frame. + +### 8.9 `Icon` + +| Id | Param | Default | Range | Meaning | +|----|-------------|---------|-------|---------------------------------------------------------| +| 30 | `icon_tall` | 0 | 0–255 | Height of the icon; 0 is the height of the element font | +| 31 | `icon_gap` | 2 | 0–64 | Distance between the icon and the text | + +- `value` must be an `Icon` cell. Its sprite from `hud.txt` or sprite file (4.3) is scaled to + `P(icon_tall)` or the font height with its aspect ratio kept, tinted with the element color, or + slot 0 (8.5), and drawn like the icons of the scoreboard (6.6). +- Variant 0, if the element has it, is drawn after the icon at `P(icon_gap)`, in the element font, + centered vertically on the icon: `{@value}` writes the name of the icon (8.10). Without variant 0 + only the icon is drawn. +- If the client doesn't have the sprite, only the text is drawn. +- The box holds the icon, the gap and the text in a row and is as tall as the higher of the icon + and the font. The gap counts only when both the icon and the text are drawn. Without an `Icon` + value the element has no content, not even its text, and the box is 0 × the font height. + +### 8.10 Templates + +A template is a text with placeholders. The client evaluates it every frame for the element's +subject. The rows of a `Board` are evaluated for the subject of each row (8.14), and the line of +an `Event` once, on arrival (4.3). + +``` +template := ( literal | "{{" | "}}" | placeholder )* +literal := any character except "{" and "}", or a lone "}" +placeholder := "{" ref [ "?" ] ( ":" format )* ( "|" form )* "}" +ref := [ "^" ] ( key | "@" name ) +key := [a-z0-9_]{1,15} +name := [a-z]{1,14} +format := [a-z0-9]+ +form := any characters except "{", "}" and "|"; "#" is the number, "##" a literal "#" +``` + +Parsing: + +- A `{` that doesn't start a placeholder of this form is literal: `{}`, `{ @place }`, `{Имя}`. + After a `{` without a closing `}` the rest of the template is literal. +- A template that is exactly a client token (4.2) is looked up once, when it arrives, and its + localized text is evaluated as a template. The localized text is never looked up as a token + again. A missing token is shown as its name without `#`. +- Known formats are `cur`, `max`, `left`, `time`, `time2`, `name`, `team` and a number. An unknown + format or built-in value makes the value missing. New built-in values and formats need a new caps + bit, so a plugin can tell which clients understand them. The built-in values that draft 3 adds + (8.11) come before the release of `HudV1` and need none. +- A placeholder takes at most one of `cur`, `max` and `left`, at most one of `time`, `time2`, + `name`, `team` and word forms, and at most one cut, a number from 1 to 255. A repeated or + conflicting format, a cut out of range or more than 16 placeholders is a parse error: the + variant draws nothing. +- The client parses a template once when it arrives. + +Refs: + +| Ref | Value | +|-----------------------|--------------------------------------------------------------------------| +| `key` | Cell of the column with this key | +| `@value` | The element's `value` ref | +| `@place`, `@rival`, … | Other built-in values (8.11) | +| `@item`, `@a`, … | Values of a `Board` row or of an event (8.11); missing elsewhere | +| `^ref` | The ref read for the first row (6.4) instead of the subject: `{^weapon}` | + +A cell is looked up in the subject's player cells, then in the cells of the subject's team (his +team number from `ScoreInfo`, in team mode or not), then in the global cells. A team subject +starts with its team cells. Without a subject only global cells are read. A `^` ref reads the +cells and built-in values of the first row, `{^@name}` is the leader's name, and it is missing +when there are no participants. + +Values are written as: + +| Value | Text | +|-------------|----------------------------------------------------------------| +| `Int` | The number | +| `Text` | The text; a client token is localized | +| `Icon` | The weapon name for standard HL sprites (10.3), else the text | +| `Progress` | `cur/max`, or `cur` when `max = 0` | +| `Clock` | As with `time` | +| Player name | The display name, never looked up as a token | +| Team name | As the team header shows it: a `#` name VGUI2 has is localized | + +Names are written by `@name`, `@rival` and the `name` and `team` formats, always without color +codes. + +Formats: + +| Format | Result | +|---------|-----------------------------------------------------------------------------------------------| +| `cur` | `Progress.cur` | +| `max` | `Progress.max` | +| `left` | `max(max − cur, 0)` of a `Progress` | +| `time` | A number of seconds as `m:ss`, from one hour as `h:mm:ss`, below 0 as `0:00` | +| `time2` | Milliseconds as `m:ss.cc` the same way: an `Int`, `Progress.cur` or the current `Clock` value | +| `name` | A number as the name of player N | +| `team` | A number as the name of team N (numbered as in `ScoreInfo`) | +| N | Cut to N code points; `…` is added only when the text was cut | + +The formats apply in this order, whatever order they are written in: `cur`, `max` or `left`, then +word forms or `time`, `time2`, `name` or `team`, then the cut. A number is an `Int`, a +`Progress.cur` or the number of a `Clock` (4.3). `time2` rounds down to hundredths, or up for a +`Clock` that counts down. + +Word forms `{ref|form1|form2|form3}` write one form chosen by the number; `#` in a form is replaced +by the number with its sign, while the rule uses its absolute value (10.2). The number of forms +selects the rule. With `@pass` = 3, `{@pass} {@pass|kill|kills}` and `{@pass|# kill|# kills}` +both give `3 kills`. + +Missing values: + +- An unknown key, an unknown built-in value or format, an empty cell, a missing built-in value, a + format that doesn't fit the value, word forms on a value that is not a number, `name` for a slot + without a player or `team` for a team without players make the value missing. +- A missing value makes the whole template empty, and a `Text` element draws nothing. So + `PLACE {@place} / {@total}` disappears instead of showing `PLACE / 8`. +- `{ref?}` writes a missing value as `""` instead. + +Robustness: + +- The result is cut to 255 UTF-16 units. Line breaks in it become spaces, on the screen and in the + banner alike. A TAB of the template is kept: it separates the columns of a `Board` row (8.14). A + TAB inside a value, such as a player name, becomes a space. +- Cell texts and localized cell tokens are never evaluated as templates, so player names and plugin + values can't inject placeholders. A literal brace is written `{{` or `}}`. A plugin that formats + a server string, such as a map or config name, into a template escapes it with + `bhl_hud_escape()` (9.2). + +Variants: + +- `Text`: `select` `""` picks variant 0. Otherwise the number of the `select` ref picks variant + 0–7, for example `@state` or `level:left`. A missing value, a number out of range or a variant + without a template draws nothing. +- `Icon`: variant 0 is the text after the icon (8.9). +- `Meter`: variant 0 is the counter (8.7); variants 1–7 are not used. +- `Board`: variant 0 is a row, variant 1 the own row when the element has it (8.14); variants 2–7 + are not used. +- `Feed`: each event names the variant of its line (4.3). +- `Strip` and `Box`: templates are not used. + +### 8.11 Built-in values + +The ranking follows the `rank` column (6.4): + +- the ranked entities are the participants, or in team mode (6.4) the teams with participants; +- the number of an entity is defined in 6.4; entities without a number are not ranked; +- with a first key that is not a number (`Text`, `Icon`) nothing is ranked, although the `rank` + column still shows places; +- `sign` is −1 for an ascending key, else 1; better means a larger `number · sign`; +- rivals are the other ranked entities. + +| Name | Value | Missing when | +|-----------|---------------------------------------------------------------------------------------------------|------------------------------------------------| +| `@place` | 1 + the number of entities strictly better; equal numbers share (`1, 1, 3`) | No subject, or its ranked entity isn't ranked | +| `@total` | Number of entities, with or without a number | Never | +| `@state` | 0 no rivals, 1 a rival ahead, 2 tied for the first place, 3 leading | Same as `@place` | +| `@rival` | Name of the nearest rival ahead, the one with the smallest gap | `@state` is not 1 | +| `@gap` | `(rival − own) · sign`, above 0 | `@state` is not 1 | +| `@pass` | `@gap + 1`: what the subject needs to pass the rival | `@state` is not 1 | +| `@lead` | Smallest `(own − rival) · sign` over the rivals, 0 or more | `@state` is not 2 or 3 | +| `@behind` | `(best − own) · sign`, where `best` is the best number; 0 when the subject shares the first place | Same as `@place` | +| `@score` | The number of the subject's ranked entity | No subject, or its ranked entity has no number | +| `@frags` | Frags from `ScoreInfo`, or the team frags (6.4) for a team subject | No subject | +| `@deaths` | Deaths, the same way | No subject | +| `@name` | Name of the subject: the player, or the team for a team subject | No subject | +| `@value` | The element's `value` | No `value` or an empty cell | + +- Among rivals with the same gap, `@rival` is the one that comes last in the scoreboard order, the + row right above the subject. +- `@value` is resolved one level only. A `value` ref that is itself `@value`, with or without `^` + or a format, is missing everywhere: in templates, in `select` and as the value a `Meter`, an + `Icon` or a `Strip` draws. The server accepts such a ref. +- Built-in values are computed once per frame for each subject. + +These built-in values exist only while the client evaluates a `Board` row or an event. Everywhere +else, in `select` and `value` and with `^`, they are missing: + +| Name | Value | Where | +|------------------------|-------------------------------------------------------------------------------------------|----------------------| +| `@index` | Number of the row in the board, 1-based | `Board` rows | +| `@item` | The list item of the row, written like a cell value | `Board` in list mode | +| `@value` | The item at the row's index of the list that the `value` key names, with the ref format | `Board` in list mode | +| `@a`, `@b`, `@c`, `@d` | Args 0–3 of the event by position, written like cell values: `{@a:name}` is a player name | Event lines | +| `@icon` | The first `Icon` arg, written like an `Icon` cell: the weapon name or its text | Event lines | + +- In a ranking `Board` `@value` is the element's `value` read for the row subject, as usual. In a + list `Board` with a `value` key, `@value` reads that key as a list key; a missing list or item + makes it missing. A built-in `value` ref (`@…`) keeps its usual meaning. +- Formats apply to these values as to any other: `{@a:name}`, `{@item:20}`, `{@value:left}`. + +A deathmatch line needs no columns, because without sort keys the ranking uses frags. One `Text` +element with `select @state`: + +| Variant | Template | +|---------|---------------------------------------------------------------------| +| 0 | `Waiting for opponents` | +| 1 | `Leader {^@name:20}: {^@score} · {@behind\|# frag\|# frags} behind` | +| 2 | `Tied for the lead` | +| 3 | `Lead: {@lead\|# frag\|# frags}` | + +### 8.12 Standard HUD parts + +| Bit | Name | Hides | +|------|----------------|-----------------------------------------------------------------------| +| 0 | `Timer` | `hud_timer` modes 1–3 | +| 1 | `NextMap` | The `hud_nextmap` line | +| 2 | `CustomTimers` | The display of `customtimer` timers; the sound at the end still plays | +| 3 | `Speedometer` | `hud_speedometer` in its bottom position, not below the crosshair | +| 4 | `JumpSpeed` | `hud_jumpspeed` in its bottom position, not below the crosshair | +| 5–15 | reserved | Sent as 0, ignored | + +- The bits come in `HudState.hide` and are honoured while `hud_server_elements` is 1. +- `NextMap` doesn't cover the AG `Nextmap` message, which shows the next map for 10 s when + `hud_nextmap` is neither 1 nor 2. +- A bottom speedometer keeps its place above a bottom `hud_jumpspeed` even while `JumpSpeed` hides + it. +- The client never moves standard HUD parts for elements. A plugin avoids overlaps by placing its + elements or by hiding parts. The status bar (names of aimed players) is never hidden; with + `hud_centerid 1` it can cross a lifted `NumbersRow` element. + +### 8.13 Params of every kind + +| Id | Param | Default | Range | Meaning | +|----|-----------------|---------|---------|--------------------------------------------------------------------| +| 32 | `flash_ms` | 0 | 0–5000 | The color flashes toward white when the content changes | +| 33 | `fade_ms` | 0 | 0–5000 | The element fades in and out | +| 34 | `hold_ms` | 0 | 0–30000 | Drawn this long after it appears or changes; 0: always | +| 35 | `warn_at` | 0 | 0–32767 | The warn color while the number of `value` is at most this; 0: off | +| 36 | `warn_pulse_ms` | 0 | 0–5000 | Period of the alpha pulse while warning; 0: no pulse | + +Every kind takes them, and their defaults leave an element as it was. The client keeps the state +of the effects per element id between frames; a removal or a kind change resets it. Times are the +client's. + +The content of an element, for `flash_ms` and `hold_ms`, is what it draws: + +| Kind | Content | +|---------------|----------------------------------------------| +| `Text` | The chosen variant and the evaluated text | +| `Icon` | The sprite and the text | +| `Meter` | `cur`, `max` and the counter text when drawn | +| `Strip` | The current cell and `count` | +| `Board` | The texts of all rows | +| `Feed`, `Box` | Nothing: their content never changes | + +A template with a running `Clock` (`time`, `time2`) changes its text every second or every frame, +so a plugin doesn't combine such a text with `flash_ms` or `hold_ms`. + +- `flash_ms`: when the content changes while the element is drawn and its subject stays, its rgb + goes toward white and back: `c + (255 − c) · k` with `k = 1 − t / flash_ms`, `t` since the + change. The variant colors of `Board` rows flash too. There is no flash when the element + appears, when its subject changes (a spectator switches players), for a change while it was not + drawn, and for the content after a `Reset` (so after a full sync) or `VidInit`. +- `fade_ms`: the alpha factor of the element goes from 0 to 1 over `fade_ms` when it starts being + drawn, and from 1 to 0 when it stops; a reversal continues from the current factor. While it + fades out, the element is drawn as it was in its last drawn frame; a `Strip` keeps its geometry + but draws its current list items, icons and track markers. Rules 1 and 2 of 8.3, the removal of + the element and a kind change cut it at once. +- `hold_ms`: after the element appears (it starts to pass rules 3–7 of 8.3, or its subject changes) + or its content changes, it is drawn for `hold_ms`, then it counts as hidden (rule 8) and fades out + with `fade_ms`. The next change of its content, or a new appearance, shows it again. +- `warn_at`: while the element passes rules 3–7 and the number of its `value` for its subject (an + `Int`, `Progress.cur` or the seconds of a `Clock`) is at most `warn_at`, the element warns: its + color is slot 8, or `255 64 32 255` without it (8.5). A missing value or one that is not a number + doesn't warn. +- `warn_pulse_ms`: while warning, the alpha is multiplied by `0.55 + 0.45 · cos(2π · t / + warn_pulse_ms)`, `t` since the warning started. + +### 8.14 `Board` + +| Id | Param | Default | Range | Meaning | +|----|-------------------|---------|-------|-------------------------------------------------------------------------------| +| 44 | `rows` | 3 | 1–16 | Number of rows | +| 45 | `board_mode` | 0 | 0–2 | 0: the first rows; 1: also the own row after them; 2: rows around the own row | +| 46 | `row_gap` | 2 | 0–64 | Distance between rows | +| 47 | `column_gap` | 8 | 0–64 | Distance between columns | +| 48 | `fill_alpha` | 0 | 0–255 | Bar behind a row by its value; 0: none | +| 49 | `highlight_alpha` | 48 | 0–255 | Plate behind the own row; 0: none | + +Sources: + +- Ranking, `list` `""`: the rows are the ranked entities (6.4) in the scoreboard order, the + participants or in team mode the teams with participants. The subject of a row is its entity. + The own row is the row of the ranked entity of the element's subject (8.2). +- List, `list` names a list: the rows are its items, and the subject of every row is the element's + subject. The own row is row `n`, 1-based, where `n` is the number of the `select` ref for the + element's subject. A missing list has no rows. +- Without a subject there is no own row. + +Rows, with `N = rows`: + +- `board_mode` 0: the first `N` rows. +- `board_mode` 1: the first `N` rows and, when the own row is not among them, a separator row `…` + and the own row after them, so up to `N + 2` lines. +- `board_mode` 2: `N` rows around the own row, `first = clamp(own − N / 2, 0, count − N)`; the first + `N` rows without an own row. + +Row text: + +- The template is variant 1 for the own row when the element has variant 1, otherwise variant 0. + It is evaluated for the subject of the row with `@index` and, in list mode, `@item` and `@value` + (8.11). +- The text is split at TAB characters into at most 4 columns; further TABs become spaces. +- Each column is as wide as its widest text over the drawn rows, and columns are `P(column_gap)` + apart. A column whose non-empty texts over the drawn rows have only digits, spaces and + `+ - . , / : %` is right-aligned, any other is left-aligned. +- A row uses the element color or the slot of its variant (8.5). The separator `…` stands in the + first column, in the color of variant 0. + +Icons: + +- Ranking: the row's `value`, read for the row subject, when it is an `Icon`. List: the item when + it is an `Icon`. +- An icon is as tall as the font, with its aspect ratio kept, and centered in an icon column right + before the last text column. That column is as wide as the widest icon and is followed by + `P(column_gap)`; without icons there is none. A sprite the client doesn't have leaves its place + empty. Icons are tinted with the row color. + +Fill and highlight: + +- With `fill_alpha > 0` a row gets a bar from its left edge, `f` of the row width, at `fill_alpha` + in the element color. The value of a row is its `value` read for the row subject, or in list mode + with a `value` key its `@value`. `f` is `cur / max` of a `Progress`, or for an `Int` the value + divided by the largest `Int` over the drawn rows; a value of 0 or less, or of another type, gives + no bar. +- With `highlight_alpha > 0` the own row gets a plate of the row size at `highlight_alpha` in the + element color, under the fill bar. + +Box: rows are as tall as the font and `P(row_gap)` apart; the box is as wide as the columns, the +icon column and the gaps, and `n · tall + (n − 1) · P(row_gap)` high for `n` lines. A board without +rows has no content. + +### 8.15 `Feed` + +| Id | Param | Default | Range | Meaning | +|----|----------------|---------|-----------|------------------------------------------------------------| +| 52 | `lines` | 4 | 1–8 | Lines shown at most with `queue` 0 | +| 53 | `life_ms` | 5000 | 100–30000 | Life of a line whose event gives 0 | +| 54 | `line_fade_ms` | 400 | 0–5000 | A line fades in and out over this time | +| 55 | `queue` | 0 | 0–1 | 0: the newest lines on top; 1: one line at a time in order | +| 56 | `line_gap` | 2 | 0–64 | Distance between lines | + +- The lines come only from `Event` messages (4.3). A line arrives at the client time of its event + and lives for the event's `life`, or `life_ms` for 0. The age of a line runs while the element is + hidden. +- `queue` 0: the live lines (`age < life`), newest first, at most `lines`. +- `queue` 1, an announcer: the lines in arrival order, each from `start = max(arrival, end of the + previous line)` to `end = start + life`; the line whose interval holds now is shown alone. +- Alpha of a line: `min(1, t / fade, (life − t) / fade)` with `fade = line_fade_ms` and `t` the + time since the arrival (`queue` 0) or the start (`queue` 1): it fades in at the beginning and out + at the end of its life. +- A line is its icon (the sprite of the event's first `Icon` arg), as tall as the font with its + aspect ratio kept, then `P(4)` when both are drawn, then its text in the element font. The line + uses the element color or the slot of its variant (8.5), the icon too. +- The box is as wide as the widest shown line and `n · tall + (n − 1) · P(line_gap)` high. Lines are + stacked from the top of the box, the newest first, and each is aligned in the box by the resolved + horizontal anchor: left, center or right. The box is placed by its anchors as usual: with a top + anchor older lines move down when a line arrives, with a bottom anchor the box grows upward. +- A feed has content while it shows a line, so it draws nothing between events. + +### 8.16 `Box` + +| Id | Param | Default | Range | Meaning | +|----|---------------|---------|-------|---------------------------------------------------| +| 60 | `accent_wide` | 0 | 0–64 | Width of the accent bar on the left edge; 0: none | +| 61 | `radius` | 0 | 0–32 | Radius of the corners | + +- A `Box` names the root of a group as its parent, with a parent place (`Parent`, `ParentLeft` or + `ParentRight`); without one it is unplaced. `x`, `y`, the anchors and the rules of the place are + ignored. No element can be placed at a `Box`, and a `Box` is never a parent (8.4). +- The group: the drawn elements whose parent chain reaches the root, the root included and `Box` + elements excluded; elements that fade out count. +- The box is the union of their boxes and of what they draw outside them (the counter of a `Meter`, + the scroll and track markers of a `Strip`), padded by `P(gap)` on every side. +- The `Box` is drawn when it passes the rules of 8.3, its content being a non-empty union. +- Before any other shape (8.1) it draws a filled rectangle with corners of radius + `min(P(radius), w / 2, h / 2)`, line by line like the rounded boxes of the scoreboard, in the + element color; then, with `accent_wide > 0`, the left `P(accent_wide)` pixels of the same shape + in the slot 9 color, or the `hud_color` rgb at alpha 255 without it. +- Its alpha follows its own effects (8.13) and is multiplied by the largest fade factor of the + group, so the box fades with its elements. +- A new element follows `hud_color` at alpha 255 (9.2): a plugin gives a `Box` its own color, + usually a dark translucent one. + +## 9. Plugin API + +### 9.1 Server interface + +`IBugfixedServer` gets minor version 4. Version 1.3 appended two methods: + +- `GetClientCaps(int idx)` returns the caps of a client; +- `GetScoreboard()` returns `bhl::IScoreboardExt *`, a separate interface whose methods take + column, list and element keys, never ids. New methods are appended to it the same way. + +Version 1.4 appends `HudSetSlotColor` and `HudEvent` to the end of `IScoreboardExt`. Draft 1 builds +report 1.2 with an older `IScoreboardExt`, and calling it with the new layout would crash the +server; draft 2 builds report 1.3 without the two new methods, and calling them would call missing +vtable slots. So the module requires 1.4 for every scoreboard and HUD native. + +`IScoreboardExt` is not released, so `SetConfig` changes in place, and `SetClock`, `AddBadge` and +the HUD methods follow the list methods: + +```cpp +virtual void SetConfig(unsigned int hideFlags, const char *title, const char *tag) = 0; + +// ... columns, cells and lists as before ... + +virtual void SetClock(int target, const char *key, int ms, unsigned int flags) = 0; + +//! host may name a column that is added later +virtual bool AddBadge(const char *key, const char *host) = 0; + +//! Adds an element, or changes kind, position, font, anchors and flags of an existing one. +//! x and y follow set_hudmessage. A kind change drops templates, refs, params and slot colors. +//! Bit 0 of flags is ignored: the color mode comes from HudSetColor. +virtual bool HudAdd(const char *key, int kind, float x, float y, int font, int align, unsigned int flags) = 0; + +//! parent may name an element that is added later +virtual bool HudSetPlace(const char *key, int place, const char *parent, int gap) = 0; + +//! r < 0: follow hud_color +virtual bool HudSetColor(const char *key, int r, int g, int b, int a) = 0; + +//! false, and nothing changes, when the Element message would exceed 192 bytes +virtual bool HudBind(const char *key, const char *value, const char *list, const char *select) = 0; + +//! A param of the element's kind or of every kind (8.13); false as HudBind +virtual bool HudSetParam(const char *key, int param, int value) = 0; + +//! player 0: the default, drops the per-player texts of the variant; otherwise that player only. +//! false for a text longer than 188 bytes, which is never cut. +virtual bool HudSetText(int player, const char *key, int variant, const char *text) = 0; + +//! player 0: the default, drops the per-player visibility; otherwise that player only +virtual bool HudShow(int player, const char *key, bool show) = 0; + +//! "" removes every element +virtual void HudRemove(const char *key) = 0; + +//! Sets or clears only the given parts +virtual void HudHideStd(unsigned int parts, bool hide) = 0; + +// Added in 1.4 + +//! slot 0-9; r < 0 clears the slot. Components are clamped to 0-255. false as HudBind. +virtual bool HudSetSlotColor(const char *key, int slot, int r, int g, int b, int a) = 0; + +//! A line for a Feed element (5.6). player 0: every client with HudV1 now. lifeMs is clamped to +//! 0-65535, 0 for the element's life_ms. argCount 0-4 Int args; the icon, when its sprite or text +//! is not empty, is appended as an Icon arg, both cut to 31 bytes. +virtual bool HudEvent(int player, const char *key, int variant, int lifeMs, const int *args, int argCount, const char *iconSprite, const char *iconText) = 0; +``` + +`bugfixedapi_amxx` checks the interface version per feature instead of refusing the whole API. +On a server older than 1.4 the existing natives keep working, `bhl_sb_available()` returns false, +`bhl_get_client_caps()` returns 0 and the other `bhl_sb_*` and `bhl_hud_*` natives do nothing; the +first of them called on a map logs one error. + +### 9.2 Natives + +```pawn +enum BhlClientCaps +{ + BHL_CAPS_NONE = 0, + BHL_CAPS_SCOREBOARD_V1 = (1 << 0), + BHL_CAPS_HUD_V1 = (1 << 1) +}; + +enum BhlSbDisplay +{ + BHL_SB_TEXT = 0, + BHL_SB_ICON = 1, + BHL_SB_METER = 2, + BHL_SB_BUILTIN = 3, + BHL_SB_STEPS = 4, + BHL_SB_BADGE = 5 // added by bhl_sb_add_badge only +}; + +enum BhlSbHide +{ + BHL_SB_HIDE_NONE = 0, + BHL_SB_HIDE_FRAGS = (1 << 0), + BHL_SB_HIDE_DEATHS = (1 << 1), + BHL_SB_HIDE_EFF = (1 << 2), + BHL_SB_HIDE_STEAMID = (1 << 3) +}; + +enum BhlSbColumnFlags +{ + BHL_SB_COL_NONE = 0, + BHL_SB_COL_HIDDEN = (1 << 0), + BHL_SB_COL_CENTER = (1 << 1), + BHL_SB_COL_RIGHT = (2 << 1), + BHL_SB_COL_PRIMARY = (1 << 3), + BHL_SB_COL_MARK_LAST = (1 << 4) +}; + +enum BhlSbTarget +{ + BHL_SB_INVALID = -1, + BHL_SB_GLOBAL = 0 +}; + +#define BHL_SB_SORT_ASC 0x80 + +enum BhlSbClock +{ + BHL_SB_CLOCK_STOP = 0, + BHL_SB_CLOCK_RUN = (1 << 0), + BHL_SB_CLOCK_DOWN = (1 << 1) +}; + +enum BhlHudKind +{ + BHL_HUD_TEXT = 1, + BHL_HUD_METER = 2, + BHL_HUD_STRIP = 3, + BHL_HUD_ICON = 4, + BHL_HUD_BOARD = 5, // rows of the scoreboard order or of a list + BHL_HUD_FEED = 6, // lines of bhl_hud_event + BHL_HUD_BOX = 7 // backdrop of a group, placed with a parent place at the root of the group +}; + +enum BhlHudFont +{ + BHL_HUD_FONT_TEXT = 0, + BHL_HUD_FONT_LARGE = 1, + BHL_HUD_FONT_SMALL = 2, + BHL_HUD_FONT_HUGE = 3 +}; + +enum BhlHudAlign +{ + BHL_HUD_AUTO = 0, + BHL_HUD_LEFT = 1, + BHL_HUD_HCENTER = 2, + BHL_HUD_RIGHT = 3, + BHL_HUD_TOP = (1 << 2), + BHL_HUD_VCENTER = (2 << 2), + BHL_HUD_BOTTOM = (3 << 2) +}; + +enum BhlHudFlags +{ + BHL_HUD_NONE = 0, + BHL_HUD_SUBJECT = (1 << 1), + BHL_HUD_NO_SCOREBOARD = (1 << 2), + BHL_HUD_LEADER = (1 << 3), + BHL_HUD_DEFAULT = (1 << 1) | (1 << 2) +}; + +enum BhlHudPlace +{ + BHL_HUD_SCREEN = 0, + BHL_HUD_PARENT = 1, + BHL_HUD_NUMBERS_ROW = 2, + BHL_HUD_BANNER_TOP = 3, + BHL_HUD_BANNER_BOTTOM = 4, + BHL_HUD_PARENT_LEFT = 5, + BHL_HUD_PARENT_RIGHT = 6 +}; + +enum BhlHudParam +{ + BHL_HUD_P_DOTS = 1, + BHL_HUD_P_DOT_SIZE = 2, + BHL_HUD_P_DOT_GAP = 3, + BHL_HUD_P_BAR_WIDE = 4, + BHL_HUD_P_COUNTER = 5, + BHL_HUD_P_COUNTER_GAP = 6, + BHL_HUD_P_ALPHA_EMPTY = 7, + BHL_HUD_P_CELL_WIDE = 10, + BHL_HUD_P_CELL_MIN_WIDE = 11, + BHL_HUD_P_CELL_TALL = 12, + BHL_HUD_P_CELL_GAP = 13, + BHL_HUD_P_ICON_PADDING = 14, + BHL_HUD_P_MAX_WIDE = 15, + BHL_HUD_P_ALPHA_PASSED = 16, + BHL_HUD_P_ALPHA_CURRENT = 17, + BHL_HUD_P_ALPHA_FUTURE = 18, + BHL_HUD_P_ALPHA_ICON_FUTURE = 19, + BHL_HUD_P_FRAME = 20, + BHL_HUD_P_ICON_TALL = 30, + BHL_HUD_P_ICON_GAP = 31, + BHL_HUD_P_FLASH_MS = 32, // every kind + BHL_HUD_P_FADE_MS = 33, // every kind + BHL_HUD_P_HOLD_MS = 34, // every kind + BHL_HUD_P_WARN_AT = 35, // every kind + BHL_HUD_P_WARN_PULSE_MS = 36, // every kind + BHL_HUD_P_FORM = 40, // 0 dots or bar, 1 ring + BHL_HUD_P_TRACK = 41, // 0 off, 1 marks of the other players + BHL_HUD_P_ROWS = 44, + BHL_HUD_P_BOARD_MODE = 45, // 0 first rows, 1 first rows and the own row, 2 rows around the own row + BHL_HUD_P_ROW_GAP = 46, + BHL_HUD_P_COLUMN_GAP = 47, + BHL_HUD_P_FILL_ALPHA = 48, + BHL_HUD_P_HIGHLIGHT_ALPHA = 49, + BHL_HUD_P_LINES = 52, + BHL_HUD_P_LIFE_MS = 53, + BHL_HUD_P_LINE_FADE_MS = 54, + BHL_HUD_P_QUEUE = 55, // 0 newest lines on top, 1 one line at a time + BHL_HUD_P_LINE_GAP = 56, + BHL_HUD_P_ACCENT_WIDE = 60, + BHL_HUD_P_RADIUS = 61 +}; + +enum BhlHudStd +{ + BHL_HUD_STD_NONE = 0, + BHL_HUD_STD_TIMER = (1 << 0), + BHL_HUD_STD_NEXTMAP = (1 << 1), + BHL_HUD_STD_CUSTOM_TIMERS = (1 << 2), + BHL_HUD_STD_SPEEDOMETER = (1 << 3), + BHL_HUD_STD_JUMPSPEED = (1 << 4) +}; + +#define BHL_HUD_COLOR -1 +#define BHL_HUD_MAX_TEXT 188 + +// Color slots of bhl_hud_slot_color after the text variants 0-7 +#define BHL_HUD_SLOT_WARN 8 +#define BHL_HUD_SLOT_ACCENT 9 + +stock BhlSbTarget:bhl_sb_player(idx) +{ + return BhlSbTarget:idx; +} + +native BhlSbTarget:bhl_sb_team(const teamName[]); + +native BhlClientCaps:bhl_get_client_caps(idx); +forward bhl_client_caps_changed(idx); + +native bool:bhl_sb_available(); +native bhl_sb_reset(); +native bhl_sb_config(BhlSbHide:hide, const title[] = "", const tag[] = ""); +native bool:bhl_sb_add_column(const key[], const title[], BhlSbDisplay:display = BHL_SB_TEXT, + width = 0, sort = 0, BhlSbColumnFlags:flags = BHL_SB_COL_NONE); +native bool:bhl_sb_add_badge(const key[], const host[]); + +native bhl_sb_set_int(BhlSbTarget:target, const key[], value); +native bhl_sb_set_text(BhlSbTarget:target, const key[], const text[]); +native bhl_sb_set_icon(BhlSbTarget:target, const key[], const sprite[], const text[]); +native bhl_sb_set_progress(BhlSbTarget:target, const key[], cur, max); +native bhl_sb_set_clock(BhlSbTarget:target, const key[], ms, BhlSbClock:flags = BHL_SB_CLOCK_RUN); +native bhl_sb_clear(BhlSbTarget:target, const key[] = ""); + +native bool:bhl_sb_list_resize(const key[], count); +native bhl_sb_list_set_int(const key[], index, value); +native bhl_sb_list_set_text(const key[], index, const text[]); +native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]); + +native bool:bhl_hud_add(const key[], BhlHudKind:kind, Float:x = -1.0, Float:y = -1.0, + BhlHudFont:font = BHL_HUD_FONT_TEXT, BhlHudAlign:align = BHL_HUD_AUTO, + BhlHudFlags:flags = BHL_HUD_DEFAULT); +native bool:bhl_hud_place(const key[], BhlHudPlace:place, const parent[] = "", gap = 0); +native bool:bhl_hud_color(const key[], r = BHL_HUD_COLOR, g = 0, b = 0, a = 255); +native bool:bhl_hud_bind(const key[], const value[] = "", const list[] = "", const select[] = ""); +native bool:bhl_hud_param(const key[], BhlHudParam:param, value); +native bool:bhl_hud_text(player, const key[], variant, const fmt[], any:...); +native bool:bhl_hud_show(player, const key[], bool:show = true); +native bhl_hud_remove(const key[] = ""); +native bhl_hud_hide_std(BhlHudStd:parts, bool:hide = true); +native bool:bhl_hud_slot_color(const key[], slot, r, g, b, a = 255); +native bool:bhl_hud_event(player, const key[], variant, life_ms = 0, const sprite[] = "", + const sprite_text[] = "", any:...); + +stock bool:bhl_hud_text_lang(player, const key[], variant, const mlKey[]) +{ + if (player) + return bhl_hud_text(player, key, variant, "%L", player, mlKey); + + new players[32], num; + get_players(players, num, "ch"); + bhl_hud_text(0, key, variant, "%L", LANG_SERVER, mlKey); + + for (new i; i < num; i++) + bhl_hud_text(players[i], key, variant, "%L", players[i], mlKey); + + return true; +} + +// +// Doubles { and } so that a server string formatted into a template stays literal. +// A too long string is cut on a UTF-8 character boundary. src and dst must be different arrays. +// +stock bhl_hud_escape(const src[], dst[], len) +{ + new i, j; + + for (; src[i] && j < len; i++) + { + if (src[i] == '{' || src[i] == '}') + { + if (j + 2 > len) + break; + + dst[j++] = src[i]; + } + + dst[j++] = src[i]; + } + + // The next byte continues a character, so drop its copied part + while (j > 0 && (src[i] & 0xC0) == 0x80) + { + i--; + j--; + } + + dst[j] = EOS; + return j; +} +``` + +Scoreboard: + +- Teams are addressed by name, the same name `get_user_team()` returns. `bhl_sb_team()` returns + an opaque handle that stays valid until the map changes, or `BHL_SB_INVALID` for an unknown team. +- Values for players that are not connected are ignored. +- `sort` is a priority starting at 1; add `BHL_SB_SORT_ASC` for ascending order. +- A `BHL_SB_BUILTIN` column takes one of the keys from 4.3: `rank`, `frags`, `deaths`, `eff`, + `steamid`, `ping`. The server accepts any other valid key, and the client ignores such a column. +- `bhl_sb_add_column()` returns false for an invalid key, for `BHL_SB_BADGE` or another display + outside 0–4, and when 32 columns exist. `bhl_sb_add_badge()` adds a `Badge` column after the + column `host`, which may be added later. Its cells are set with the usual `bhl_sb_set_*` + natives. +- `bhl_sb_set_clock()` sets a `Clock` (4.3): `ms` is its value now. `BHL_SB_CLOCK_RUN` runs it, + `BHL_SB_CLOCK_DOWN` makes it count down to 0. A new call restarts a running clock, even with the + same values (5.2). +- `bhl_sb_list_resize()` creates the list on first use. Setting an item out of range is ignored. +- `sprite` of `bhl_sb_set_icon()` and `bhl_sb_list_set_icon()` is a `hud.txt` name or the path of + a sprite file, `sprites/.spr` (4.3). The plugin precaches a file with `precache_generic` + in `plugin_precache`. +- `bhl_sb_reset()` removes everything: schema, cells, lists, elements, texts, visibility, hidden + standard parts and queued events. +- `bhl_get_client_caps()` returns the normalized caps (3.1): `BHL_CAPS_HUD_V1` only together with + `BHL_CAPS_SCOREBOARD_V1`, and 0 for bots and HLTV. Like the other natives of the extension it + needs server API 1.4 and returns 0 on an older server. + +HUD: + +- Element keys are up to 15 characters of `[a-z0-9_]`, in their own namespace. `bhl_hud_add()` + returns false for an invalid key or kind, or when 32 elements exist. The other `bhl_hud_*` + natives return false for an unknown key. A `bhl_hud_*` native that returns false logs one line + for that call. `bhl_hud_remove()` ignores an unknown key and logs nothing. +- A new element is shown, is placed on the screen, follows `hud_color` with alpha 255 and has no + refs, params, slot colors or texts. `bhl_hud_add()` on an existing key changes its kind, + position, font, anchors and flags and keeps the rest; a kind change drops its texts, the + per-player ones included, its refs, params and slot colors, and keeps its place, color and + visibility. The color mode comes only from `bhl_hud_color()`. +- `x` and `y` work like in `set_hudmessage`; hl.so sends them in 1/8192, rounded (4.3). +- `bhl_hud_place()` takes the key of the parent, which may be added later. While no element has + that key, the element is not drawn (8.4). The parent is ignored for places that are not parent + places. +- `bhl_hud_color()` with `r = BHL_HUD_COLOR` follows `hud_color` and uses only `a`. +- `bhl_hud_bind()` sets the refs: `value` and `select` are a column key or a built-in value, with an + optional `^` and one of `cur`, `max` and `left` (`@state`, `level:left`); `list` is a list key. +- `bhl_hud_param()` takes a param of the element's kind or of every kind (8.13) and clamps the + value to the range of the param (8.7–8.9, 8.13–8.16); it returns false for a param of another + kind. +- `bhl_hud_slot_color()` sets the color of slot 0–9 (8.5), used as it is, also with + `BHL_HUD_COLOR`; `r = -1` clears the slot. Components are clamped to 0–255. +- `bhl_hud_bind()`, `bhl_hud_param()` and `bhl_hud_slot_color()` return false and change nothing + when the `Element` message would exceed 192 bytes; with the current kinds it never does (4.3). +- `bhl_hud_event()` adds a line to a `BHL_HUD_FEED` element. The text variant is evaluated by each + client once, with up to 4 numbers as `@a`–`@d` and the icon as `@icon` (8.11); the sprite is + drawn before the line. `life_ms` 0 takes the `life_ms` param of the element. Lines are not kept: + only players in game with `BHL_CAPS_HUD_V1` at the moment of the call get them, and a line that + can't be sent before its life ends is dropped (5.6). The native returns false for an unknown + element or one that is not a feed, a variant out of 0–7, a player out of range or not + connected, and more than 4 numbers. As AMXX passes variadic args by reference, the numbers can + be any expressions. +- `player` 0 means everyone and always drops the per-player values of that text variant or + visibility bit (5.4); a player index sets them for that player only, and returns false for a + player who is not connected. Per-player settings are dropped when the slot is cleared, so a + plugin sets them again in `client_putinserver`. +- `bhl_hud_text()` formats like `format()`: `%L` works and `%%` writes `%`. With `%L` the + dictionary text is a format too, so a literal `%` in it is written `%%`. A result longer than + `BHL_HUD_MAX_TEXT` (188) bytes is not set: the native returns false and logs an error. Text typed + by players must not be formatted into a template; use refs such as `@rival` or the `name` format + instead. Server strings such as map or config names go through `bhl_hud_escape()`. +- `bhl_hud_text_lang()` sets a text from the plugin dictionary: for one player in his language, + or for player 0 the default in the server language plus every player in his language. +- `bhl_hud_hide_std()` sets or clears only the given standard parts, for everyone, so plugins that + hide different parts don't undo each other. `bhl_sb_reset()` clears all. +- Setting a cell, an item, a text, a visibility or the hidden parts to the value it already has + sends nothing; a running clock is restarted instead (5.2). +- `bhl_client_caps_changed` doesn't fire for the caps a player had when he joined, because they + are known before he is in game. Plugins check `bhl_get_client_caps()` when they need it. + +### 9.3 GunGame + +The plugin keeps working without the module: `set_module_filter` and `set_native_filter` in +`plugin_natives` let it load, and every call is guarded by `bhlApi`. The `level * 100` frags hack +stays for old clients. A per-player counter keeps the kills of the warmup and then of the match +for the `kills` column. + +Data: + +| Key | Kind | Target | Type | Meaning | +|--------------|----------------------|----------------|------------|--------------------------------------------------------------| +| `rank` | builtin column | — | — | Place, computed by the client | +| `level` | `Steps`, `MarkLast` | player or team | `Progress` | Current level, 1-based / number of levels | +| `weapon` | `Icon` | player or team | `Icon` | Weapon of the current level | +| `progress` | `Meter` | player or team | `Progress` | Kills on the current level / kills it needs | +| `final` | badge after `weapon` | player or team | `Text` | `#BHL_SB_Final` on the last level | +| `kills` | `Text` | player, team | `Int` | Kills in the warmup, then in the match | +| `score` | `Text`, hidden | player, team | `Int` | Progress P, first sort key in the match | +| `phase` | `Text`, hidden | the whole game | `Int` | 0 game, 1 warmup, 2 start countdown, 3 finished | +| `phase_left` | `Text`, hidden | the whole game | `Int` | Seconds left in the warmup or the countdown; empty otherwise | +| `levels` | list | the whole game | `Icon` | Weapon of every level, in order | + +- P is the sum of kills needed on all passed levels plus kills on the current level. Kills per + level differ (1–7 in the shipped configs) and teamplay multiplies them by + `gg_teamplay_multigoal`. Ordering by P gives the same order as the plugin's `Sort_RankPos` + (level, then kills). Every player on the last level is ahead of every player who isn't. +- `kills` counts kills of other players. Suicides and team kills don't count. The counter is reset + together with the scores when the match starts. +- Levels are the same for everybody in the warmup. While `phase` is 1 or 2 the plugin sends the + columns again: `level`, `weapon` and `progress` become `Hidden`, `kills` becomes visible, + `Primary` and the first sort key, `score` the second one. When the match starts it sends the + match columns: `kills` is the second sort key, `Hidden` without teamplay. In teamplay `kills` + stays visible and `progress` is 60 units wide, so Ping still fits. +- Without teamplay `level`, `weapon`, `progress` and `final` are player cells. In teamplay the + level is shared by the team, so they are team cells only: the team header shows them, with the + `final` badge after the team's weapon (6.7), and player rows leave them empty and show `kills`. + HUD elements read them through the team cells (8.10). `score` stays a player cell too, so + players of a team are ordered by `kills`. + +HUD elements: + +| Key | Kind | Place | Refs | Variants | Shown | +|-----------------|--------------------|---------------------------------|------------------------------------|-------------------------------------|---------------| +| `gg_place` | `Text`, large font | top center, `y 0.025` | `select phase`, `value phase_left` | place, warmup, countdown | always | +| `gg_box` | `Box` | at `gg_place`, padding 6 | — | — | always | +| `gg_rival` | `Text` | under `gg_place`, gap 2 | `select @state` | waiting, overtake, tied, lead | match | +| `gg_kills` | `Meter` | under `gg_rival`, gap 6 | `value progress` | — | match | +| `gg_levels` | `Strip` | numbers row, gap 3 | `value level`, `list levels` | — | match | +| `gg_top` | `Board` | left top, `x 0.015`, `y 0.025` | `value weapon` | row | match | +| `gg_banner_top` | `Text`, `Leader` | banner top | `select level:left` | title | until the win | +| `gg_banner_bot` | `Text`, `Leader` | banner bottom | `select level:left` | leader line | until the win | +| `gg_feed` | `Feed`, small font | right top, `x −0.015`, `y 0.22` | — | last level, lost level, lead | always | +| `gg_ann` | `Feed`, huge font | center, `y 0.30` | — | level, last level, lost level, lead | always | + +Params and colors: + +| Key | Params, colors and texts | +|-------------|--------------------------------------------------------------------------------------------------------| +| `gg_place` | `fade_ms` 300, `warn_at` 3, `warn_pulse_ms` 500; `flash_ms` 600 in the match, 0 otherwise | +| `gg_box` | color `0 0 0 110`, `fade_ms` 300, `accent_wide` 2, `radius` 3 | +| `gg_rival` | `fade_ms` 300; slot 1 `255 106 77`, slot 2 `255 210 74`, slot 3 `124 214 124` | +| `gg_kills` | `fade_ms` 300 | +| `gg_levels` | `fade_ms` 300, `track` 1 | +| `gg_top` | `fade_ms` 300, `board_mode` 1; variant 0 `{@place}.⇥{@name:16}⇥{level:cur}` for everybody (⇥ is a TAB) | +| `gg_feed` | flags `NoScoreboard` only, `life_ms` 6000 | +| `gg_ann` | `lines` 1, `life_ms` 2500, `line_fade_ms` 300, `queue` 1 | + +- "Match" means the plugin shows the element while `phase` is 0, "until the win" while `phase` is + not 3. +- `phase` 3 has no variant in `gg_place`, so after the win the place block is empty. +- `gg_box` is a dark plate with an accent bar in `hud_color` behind `gg_place`, `gg_rival` and + `gg_kills`, the elements whose parent chain reaches `gg_place`. In the warmup it is behind + `gg_place` alone, and it fades with them. +- `gg_place` warns in the last 3 seconds of the warmup and the countdown: red and pulsing. The + plugin sets `phase_left` only while `phase` is 1 or 2 and clears it otherwise, so the warning + never holds in the match or after the win. `flash_ms` is 600 only in the match, where the text + changes with the place; the warmup texts change every second. +- `gg_rival` is colored by its variant: overtake orange-red, tied yellow, lead green; waiting keeps + `hud_color`. +- `gg_levels` shows the other players above the levels they are on (`track`, 8.8). +- `gg_top` lists the first `rows` (3 by default) players, or teams in teamplay, with their place, + name, weapon icon (the row's `weapon`) and level; a viewer whose player or team is not among them + sees its row after `…`. Its template has no words, so it is set once for everybody. +- `gg_feed` has no `Subject`, so a roaming spectator sees it too. Both feeds get lines only through + events (below). +- The banner rows read the leader's `level`: `left` is 0 only while the leader is on the last + level, and only variant 0 has a template, so otherwise the rows are empty. The client decides + this with the same leader it shows, and the plugin sends nothing when the leader changes. +- After the win the winner stays on the last level with all its kills, and the bottom row would + say `0 kills to win`, so the plugin hides both banner rows in `phase` 3. +- The key of the bottom row is `gg_banner_bot`: `gg_banner_bottom` exceeds the 15-byte limit. +- The `Meter` counter is the default `16 / 25`. +- The default params are the sizes and alphas of the GunGame look. + +```pawn +#define HUD_TOP 0.025 // 12 of 480 units + +Scoreboard_Setup(){ + if(!bhlApi) + return + + bhl_sb_reset() + bhl_sb_config(BHL_SB_HIDE_FRAGS | BHL_SB_HIDE_DEATHS | BHL_SB_HIDE_EFF | BHL_SB_HIDE_STEAMID,"",get_pcvar_num(cvar[CVAR_TEAMPLAY]) == 1 ? "TEAM" : "FFA") + + bhl_sb_add_column("rank","",BHL_SB_BUILTIN) + Scoreboard_SetColumns(warmUpMode == 1 || warmUpMode == 3) + bhl_sb_add_badge("final","weapon") + bhl_sb_add_column("phase","",BHL_SB_TEXT,0,0,BHL_SB_COL_HIDDEN) + bhl_sb_add_column("phase_left","",BHL_SB_TEXT,0,0,BHL_SB_COL_HIDDEN) + + bhl_sb_list_resize("levels",maxLevel_Int) + sbPhase = -1 + hudLeaderUserId = 0 + + new weaponSet[weaponSetStruct] + + for(new i ; i < maxLevel_Int ; ++i){ + ArrayGetArray(weaponSets_Array,i,weaponSet) + bhl_sb_list_set_icon("levels",i,weaponSet[WSET_ICONSPRITE],weaponSet[WSET_SHOWNAME]) + } + + Hud_Setup() + Scoreboard_SetPhase(0) +} + +Scoreboard_SetColumns(bool:warmup){ + new bool:teamplay = get_pcvar_bool(cvar[CVAR_TEAMPLAY]) + new BhlSbColumnFlags:levelFlags = warmup ? BHL_SB_COL_HIDDEN : BHL_SB_COL_NONE + new BhlSbColumnFlags:killsFlags = warmup ? BHL_SB_COL_PRIMARY : (teamplay ? BHL_SB_COL_NONE : BHL_SB_COL_HIDDEN) + + sbWarmupColumns = warmup + + bhl_sb_add_column("level","#BHL_SB_Level",BHL_SB_STEPS,60,0,BHL_SB_COL_MARK_LAST | (warmup ? BHL_SB_COL_HIDDEN : BHL_SB_COL_PRIMARY)) + bhl_sb_add_column("weapon","#BHL_SB_Weapon",BHL_SB_ICON,100,0,levelFlags) + bhl_sb_add_column("progress","#BHL_SB_Progress",BHL_SB_METER,teamplay ? 60 : 90,0,levelFlags) + bhl_sb_add_column("kills","#BHL_SB_Kills",BHL_SB_TEXT,60,warmup ? 1 : 2,BHL_SB_COL_RIGHT | killsFlags) + bhl_sb_add_column("score","",BHL_SB_TEXT,0,warmup ? 2 : 1,BHL_SB_COL_HIDDEN) +} + +Hud_Setup(){ + bhl_hud_hide_std(BHL_HUD_STD_TIMER | BHL_HUD_STD_NEXTMAP | BHL_HUD_STD_CUSTOM_TIMERS) + + bhl_hud_add("gg_place",BHL_HUD_TEXT,-1.0,HUD_TOP,BHL_HUD_FONT_LARGE) + bhl_hud_bind("gg_place","phase_left",.select = "phase") + bhl_hud_param("gg_place",BHL_HUD_P_FADE_MS,300) + bhl_hud_param("gg_place",BHL_HUD_P_WARN_AT,3) + bhl_hud_param("gg_place",BHL_HUD_P_WARN_PULSE_MS,500) + + bhl_hud_add("gg_box",BHL_HUD_BOX) + bhl_hud_place("gg_box",BHL_HUD_PARENT,"gg_place",6) + bhl_hud_color("gg_box",0,0,0,110) + bhl_hud_param("gg_box",BHL_HUD_P_FADE_MS,300) + bhl_hud_param("gg_box",BHL_HUD_P_ACCENT_WIDE,2) + bhl_hud_param("gg_box",BHL_HUD_P_RADIUS,3) + + bhl_hud_add("gg_rival",BHL_HUD_TEXT) + bhl_hud_place("gg_rival",BHL_HUD_PARENT,"gg_place",2) + bhl_hud_bind("gg_rival",.select = "@state") + bhl_hud_param("gg_rival",BHL_HUD_P_FADE_MS,300) + bhl_hud_slot_color("gg_rival",1,255,106,77) + bhl_hud_slot_color("gg_rival",2,255,210,74) + bhl_hud_slot_color("gg_rival",3,124,214,124) + + bhl_hud_add("gg_kills",BHL_HUD_METER) + bhl_hud_place("gg_kills",BHL_HUD_PARENT,"gg_rival",6) + bhl_hud_bind("gg_kills","progress") + bhl_hud_param("gg_kills",BHL_HUD_P_FADE_MS,300) + + bhl_hud_add("gg_levels",BHL_HUD_STRIP) + bhl_hud_place("gg_levels",BHL_HUD_NUMBERS_ROW,"",3) + bhl_hud_bind("gg_levels","level","levels") + bhl_hud_param("gg_levels",BHL_HUD_P_FADE_MS,300) + bhl_hud_param("gg_levels",BHL_HUD_P_TRACK,1) + + // Rows are teams in teamplay + bhl_hud_add("gg_top",BHL_HUD_BOARD,0.015,HUD_TOP,BHL_HUD_FONT_TEXT,BHL_HUD_LEFT | BHL_HUD_TOP) + bhl_hud_bind("gg_top","weapon") + bhl_hud_param("gg_top",BHL_HUD_P_FADE_MS,300) + bhl_hud_param("gg_top",BHL_HUD_P_BOARD_MODE,1) + bhl_hud_text(0,"gg_top",0,"{@place}.^t{@name:16}^t{level:cur}") + + bhl_hud_add("gg_banner_top",BHL_HUD_TEXT,.flags = BHL_HUD_LEADER) + bhl_hud_place("gg_banner_top",BHL_HUD_BANNER_TOP) + bhl_hud_bind("gg_banner_top",.select = "level:left") + + bhl_hud_add("gg_banner_bot",BHL_HUD_TEXT,.flags = BHL_HUD_LEADER) + bhl_hud_place("gg_banner_bot",BHL_HUD_BANNER_BOTTOM) + bhl_hud_bind("gg_banner_bot",.select = "level:left") + + bhl_hud_add("gg_feed",BHL_HUD_FEED,-0.015,0.22,BHL_HUD_FONT_SMALL,BHL_HUD_RIGHT | BHL_HUD_TOP,BHL_HUD_NO_SCOREBOARD) + bhl_hud_param("gg_feed",BHL_HUD_P_LIFE_MS,6000) + + bhl_hud_add("gg_ann",BHL_HUD_FEED,-1.0,0.30,BHL_HUD_FONT_HUGE) + bhl_hud_param("gg_ann",BHL_HUD_P_LINES,1) + bhl_hud_param("gg_ann",BHL_HUD_P_LIFE_MS,2500) + bhl_hud_param("gg_ann",BHL_HUD_P_LINE_FADE_MS,300) + bhl_hud_param("gg_ann",BHL_HUD_P_QUEUE,1) + + Hud_SetTexts(0) +} + +// +// Texts in the language of the player, 0 for everybody. +// Also called from client_putinserver and when the player changes "lang". +// +Hud_SetTexts(id){ + if(!bhlApi || !ggActive) + return + + bhl_hud_text_lang(id,"gg_place",0,"GG_HUD_PLACE") + bhl_hud_text_lang(id,"gg_place",1,"GG_HUD_WARMUP") + bhl_hud_text_lang(id,"gg_place",2,"GG_HUD_START_IN") + bhl_hud_text_lang(id,"gg_rival",0,"GG_HUD_WAITING") + bhl_hud_text_lang(id,"gg_rival",1,"GG_HUD_OVERTAKE") + bhl_hud_text_lang(id,"gg_rival",2,"GG_HUD_TIED") + bhl_hud_text_lang(id,"gg_rival",3,"GG_HUD_LEAD") + bhl_hud_text_lang(id,"gg_banner_top",0,"GG_SB_BANNER_TITLE") + bhl_hud_text_lang(id,"gg_banner_bot",0,"GG_SB_BANNER_LINE") + bhl_hud_text_lang(id,"gg_feed",0,"GG_HUD_FEED_LAST") + bhl_hud_text_lang(id,"gg_feed",1,"GG_HUD_FEED_DOWN") + bhl_hud_text_lang(id,"gg_feed",2,"GG_HUD_FEED_LEAD") + bhl_hud_text_lang(id,"gg_ann",0,"GG_HUD_ANN_LEVEL") + bhl_hud_text_lang(id,"gg_ann",1,"GG_HUD_ANN_LAST") + bhl_hud_text_lang(id,"gg_ann",2,"GG_HUD_ANN_DOWN") + bhl_hud_text_lang(id,"gg_ann",3,"GG_HUD_ANN_LEAD") +} + +Scoreboard_SetPhase(timeLeft){ + if(!bhlApi) + return + + new phase + + if(isEndGame) + phase = 3 + else if(warmUpMode == 1) + phase = 1 + else if(warmUpMode == 3) + phase = 2 + + new bool:warmup = phase == 1 || phase == 2 + + if(warmup != sbWarmupColumns) + Scoreboard_SetColumns(warmup) + + bhl_sb_set_int(BHL_SB_GLOBAL,"phase",phase) + + // Missing outside the countdowns, so the warning of gg_place holds only there + if(warmup) + bhl_sb_set_int(BHL_SB_GLOBAL,"phase_left",timeLeft) + else + bhl_sb_clear(BHL_SB_GLOBAL,"phase_left") + + // + // A write for player 0 drops per-player visibility, so only on a phase change + // + if(phase == sbPhase) + return + + sbPhase = phase + + new bool:match = phase == 0 + new bool:won = phase == 3 + + bhl_hud_show(0,"gg_rival",match) + bhl_hud_show(0,"gg_kills",match) + bhl_hud_show(0,"gg_levels",match) + bhl_hud_show(0,"gg_top",match) + + // Warmup texts change every second + bhl_hud_param("gg_place",BHL_HUD_P_FLASH_MS,match ? 600 : 0) + + // After the win the leader line would read "0 kills to win" + bhl_hud_show(0,"gg_banner_top",!won) + bhl_hud_show(0,"gg_banner_bot",!won) +} + +bool:Player_HasBhlHud(id){ + return bhlApi && (bhl_get_client_caps(id) & BHL_CAPS_HUD_V1) != BHL_CAPS_NONE +} + +// +// The event is about the player himself, or about his team in teamplay +// +bool:Hud_IsOwnEvent(player,id){ + return player == id || get_pcvar_bool(cvar[CVAR_TEAMPLAY]) && isPlayersTeamSame(player,id) +} + +// +// Level change from gg_notify_msg (NOTIFY_UP to NOTIFY_SKIP), also when its chat line is off: +// the announcer of the player and his team, the feed of the others on the last level or a lost level. +// In teamplay once per team level, as the chat: after a level down the equip of each teammate notifies it. +// +Hud_LevelEvent(id,notifyId){ + if(!bhlApi || notifyId > NOTIFY_SKIP) + return + + new level = playersData[id][PLAYER_CURRENTLEVEL] + + if(get_pcvar_bool(cvar[CVAR_TEAMPLAY])){ + static lastTeam,lastLevel + + if(lastTeam == playersData[id][PLAYER_TEAM] && lastLevel == level) + return + + lastTeam = playersData[id][PLAYER_TEAM] + lastLevel = level + } + + new weaponSet[weaponSetStruct] + ArrayGetArray(playersData[id][PLAYER_WEAPONSETS],level,weaponSet) + + new bool:down = notifyId == NOTIFY_DOWN + new bool:last = isPlayerLastLevel(id) + new players[32],pnum + get_players(players,pnum,"ch") + + for(new i,player ; i < pnum ; ++i){ + player = players[i] + + if(!Player_HasBhlHud(player)) + continue + + if(Hud_IsOwnEvent(player,id)) + bhl_hud_event(player,"gg_ann",down ? 2 : _:last,0,weaponSet[WSET_ICONSPRITE],weaponSet[WSET_SHOWNAME],level + 1) + else if(down) + bhl_hud_event(player,"gg_feed",1,0,"","",id) + else if(last) + bhl_hud_event(player,"gg_feed",0,0,weaponSet[WSET_ICONSPRITE],weaponSet[WSET_SHOWNAME],id) + } + + Hud_CheckLeader() +} + +// +// The announcer or the feed of a player with the HUD shows this chat line: his own level change, +// the last level or a lost level of the others. The skip line keeps its reason. +// +bool:Hud_ShowsNotify(player,id,notifyId){ + switch(notifyId){ + case NOTIFY_UP,NOTIFY_LAST,NOTIFY_TEAMUP,NOTIFY_TEAMLAST:{ + if(!Hud_IsOwnEvent(player,id) && !isPlayerLastLevel(id)) + return false + } + case NOTIFY_DOWN:{} + default: + return false + } + + return Player_HasBhlHud(player) +} +``` + +`Scoreboard_SetLevelCells` fills the level cells and the badge of its target: the player without +teamplay, the team in teamplay. A level change that waits for the respawn equip already shows the +kills the equip sets: 0 after a level-up, one short of the next level (`WSET_KILLS − 1`) after a +level-down. For the winner `level` stays on the last level: + +```pawn + if(level == maxLevel - 1) + bhl_sb_set_text(target,"final","#BHL_SB_Final") + else + bhl_sb_clear(target,"final") +``` + +Events. `gg_notify_msg` calls `Hud_LevelEvent(id, notifyId)` first, so the events go out also +when the chat line of that notification is turned off. Each player in game with `HudV1` (bots and +HLTV skipped) gets one event, and level changes of other players below the last level give none. +In teamplay a team level sends its events once, like its chat line, though the equip of every +teammate notifies a level down: + +| Notification of player `id` | Player `id`, his team in teamplay | Other players | +|-----------------------------------------|----------------------------------------|-------------------------------------------| +| Level up or skip, not to the last level | `gg_ann` 0 `LEVEL n · weapon` | — | +| Level up or skip to the last level | `gg_ann` 1 `LAST LEVEL · weapon` | `gg_feed` 0 `name reached the last level` | +| Level down | `gg_ann` 2 `LEVEL LOST · weapon` | `gg_feed` 1 `name lost a level` | +| New unique leader, without teamplay | `gg_ann` 3 `YOU TAKE THE LEAD`, to him | `gg_feed` 2 `name takes the lead` | + +- The announcer events carry the weapon of the new level as their icon (`WSET_ICONSPRITE`, its + `WSET_SHOWNAME` as `@icon`) and the level, 1-based, as `@a`. The feed events carry the player + index as `@a`, written with `{@a:name}`, and the "last level" line the weapon icon too. +- After every level event, kill and descore `Hud_CheckLeader()` looks for the leader: the only + participant with the best score P (`Scoreboard_SetLevelCells` with `scoreOnly`, which also sends + `score` when a skip raised it). A tie keeps the last leader. When the leader changes (by userid, + as slots are reused; `Scoreboard_Setup` forgets it) and at least 2 participants play, the leader + gets `gg_ann` 3 and the others `gg_feed` 2. Teams share the level in teamplay, so there is no + leader event there. +- `life_ms` 0 in all events: the lines live for the `life_ms` of their feed. + +Chat. The plugin doesn't print a chat notification to a player with `HudV1` when his feed or +announcer shows it (`Hud_ShowsNotify`): his own (or his team's) level up and last level, the last +level of any other player, and any level down. Level-ups of others below the last level, the skip +line with its reason, the win and the mode messages stay in chat for everybody. A player without +`HudV1` gets every chat line as before. + +`gungame.txt` gets the texts in English, Russian and Spanish. Other languages follow the same +pattern; a language with two forms uses two. The texts go through `%L`, so a literal `%` in them +is written `%%`. + +``` +[en] +GG_HUD_PLACE = PLACE {@place} / {@total} +GG_HUD_WARMUP = WARMUP {@value:time} +GG_HUD_START_IN = START IN {@value} +GG_HUD_WAITING = Waiting for opponents +GG_HUD_OVERTAKE = To pass {@rival:20}: {@pass|# kill|# kills} +GG_HUD_TIED = Tied +GG_HUD_LEAD = Lead: {@lead|# kill|# kills} +GG_SB_BANNER_TITLE = Leader on the last level +GG_SB_BANNER_LINE = {@name} · {weapon} · {progress:left|# kill|# kills} to win +GG_HUD_FEED_LAST = {@a:name} reached the last level +GG_HUD_FEED_DOWN = {@a:name} lost a level +GG_HUD_FEED_LEAD = {@a:name} takes the lead +GG_HUD_ANN_LEVEL = LEVEL {@a} · {@icon} +GG_HUD_ANN_LAST = LAST LEVEL · {@icon} +GG_HUD_ANN_DOWN = LEVEL LOST · {@icon} +GG_HUD_ANN_LEAD = YOU TAKE THE LEAD + +[ru] +GG_HUD_PLACE = МЕСТО {@place} / {@total} +GG_HUD_WARMUP = РАЗМИНКА {@value:time} +GG_HUD_START_IN = СТАРТ ЧЕРЕЗ {@value} +GG_HUD_WAITING = Ожидание соперников +GG_HUD_OVERTAKE = До обгона {@rival:20}: {@pass|# убийство|# убийства|# убийств} +GG_HUD_TIED = Вровень +GG_HUD_LEAD = Отрыв: {@lead|# убийство|# убийства|# убийств} +GG_SB_BANNER_TITLE = Лидер на последнем уровне +GG_SB_BANNER_LINE = {@name} · {weapon} · {progress:left|# убийство|# убийства|# убийств} до победы +GG_HUD_FEED_LAST = {@a:name} выходит на последний уровень +GG_HUD_FEED_DOWN = {@a:name} теряет уровень +GG_HUD_FEED_LEAD = {@a:name} выходит в лидеры +GG_HUD_ANN_LEVEL = УРОВЕНЬ {@a} · {@icon} +GG_HUD_ANN_LAST = ПОСЛЕДНИЙ УРОВЕНЬ · {@icon} +GG_HUD_ANN_DOWN = УРОВЕНЬ ПОТЕРЯН · {@icon} +GG_HUD_ANN_LEAD = ВЫ ВЫШЛИ В ЛИДЕРЫ +``` + +The longest text, the Russian banner line, takes 111 bytes. A plugin that doesn't want to send +texts to every player can use the client tokens instead (10.1), in English and Russian only: +`bhl_hud_text(0,"gg_place",0,"#BHL_HUD_Place")`. The `gg_top` row has no words and is set once +with `bhl_hud_text(0, …)`. + +| Plugin function | Calls | +|--------------------------|----------------------------------------------------------------------------------| +| `Enable_GunGame` | `Scoreboard_Setup()` | +| `Disable_GunGame` | `bhl_sb_reset()`; the standard HUD parts come back | +| `client_putinserver` | `Scoreboard_UpdatePlayer(id)`; `Hud_SetTexts(id)` except for bots and HLTV | +| `client_infochanged` | `Hud_SetTexts(id)` when `lang` changed, only for a connected player | +| `Equip_PlayerWithWeapon` | `Scoreboard_UpdatePlayer(id)` | +| Descore (suicide) | `Scoreboard_UpdatePlayer(victim)`, `Hud_CheckLeader()` | +| Kill and level-up | `Scoreboard_UpdatePlayer(killer)`, team cells in teamplay, `Hud_CheckLeader()` | +| `Update_TeamData` | Team cells through `bhl_sb_team(teamName)` | +| `WarmUp_Timer` | `Scoreboard_SetPhase(left)` every second | +| Match start | `Scoreboard_SetPhase(0)` | +| `resetPlayersScore` | `kills` 0 for everyone | +| Disconnect | Team `kills` without the player | +| `endgame` | Final player and team cells; `Scoreboard_SetPhase(0)` sets phase 3 (`isEndGame`) | +| Auto-save restore | `Scoreboard_UpdatePlayer(id)` | +| `gg_notify_msg` | `Hud_LevelEvent(id, notifyId)`, then chat lines filtered by `Hud_ShowsNotify` | + +The engine calls `client_infochanged` before `ClientConnect` too, when no text can be set for the +slot (9.2). So the plugin keeps the `lang` a player's texts were set for: it stores it in +`client_putinserver` after `Hud_SetTexts(id)`, compares it in `client_infochanged` and clears it on +disconnect. + +For players with `HudV1` (`Player_HasBhlHud`) the plugin skips: + +- the text informer (`Show_HudInformer`); +- `StatusIcon`; +- the warmup messages from `WarmUp_Timer`, which then go to every other player one by one + instead of `show_hudmessage(0, …)`; +- the chat lines of level changes that his feed or announcer shows (see Chat above). + +`bhl_client_caps_changed` switches the informer and `StatusIcon` on and off when a player changes +`hud_server_elements`; the other checks are made for every message. The winner message, the start +message (`WARMUP_ROUND_OVER`), the final table and the other chat notifications stay for everyone. + +A plugin with a long countdown can send a `Clock` (4.3) once instead of an `Int` every second. +GunGame keeps the `Int`: its warmup timer runs every second anyway. + +## 10. Localization + +### 10.1 Tokens + +The client ships these tokens in `bugfixedhl_english.utf8.txt` and `bugfixedhl_russian.utf8.txt`. +Other client languages use English. + +| Token | English | Russian | +|--------------------|-------------------------------------------------|---------------------------------------------------------------------| +| `BHL_SB_Level` | `Level` | `Уровень` | +| `BHL_SB_Weapon` | `Weapon` | `Оружие` | +| `BHL_SB_Progress` | `Progress` | `Прогресс` | +| `BHL_SB_Kills` | `Kills` | `Убийства` | +| `BHL_SB_Final` | `FINAL` | `ФИНАЛ` | +| `BHL_HUD_Place` | `PLACE {@place} / {@total}` | `МЕСТО {@place} / {@total}` | +| `BHL_HUD_Overtake` | `To pass {@rival:20}: {@pass\|# kill\|# kills}` | `До обгона {@rival:20}: {@pass\|# убийство\|# убийства\|# убийств}` | +| `BHL_HUD_Lead` | `Lead: {@lead\|# kill\|# kills}` | `Отрыв: {@lead\|# убийство\|# убийства\|# убийств}` | +| `BHL_HUD_Tied` | `Tied` | `Вровень` | +| `BHL_HUD_Waiting` | `Waiting for opponents` | `Ожидание соперников` | +| `BHL_HUD_Warmup` | `WARMUP {@value:time}` | `РАЗМИНКА {@value:time}` | +| `BHL_HUD_StartIn` | `START IN {@value}` | `СТАРТ ЧЕРЕЗ {@value}` | + +- `BHL_HUD_*` tokens are templates that use only built-in values, so any ranked mode can use them; + without sort keys they rank by frags (6.4). `BHL_HUD_Warmup` and `BHL_HUD_StartIn` read the + element's `value`. +- Texts of one mode, such as the GunGame banner, are plugin texts. A plugin covers any language by + sending each player a template in his language (`bhl_hud_text_lang`, 9.2). +- Badge cells are broadcast to everybody, so a badge in the player's language needs a client + token. +- Player names are never looked up as tokens. A team name that starts with `#` is localized when + VGUI2 has it, as in the team header (8.10). + +### 10.2 Word forms + +The number of forms in `{n|…}` selects the rule, so a template in any language picks its rule +without the client knowing the language: + +| Forms | Form 1 | Form 2 | Form 3 | +|-------|---------------------------------|-----------------------------------------|--------| +| 1 | Always | — | — | +| 2 | `n = 1` | Other | — | +| 3 | `n % 10 = 1` and `n % 100 ≠ 11` | `n % 10` in 2–4 and `n % 100` not 12–14 | Other | + +- `n` is the absolute value of the number. Forms after the third are ignored. +- Two forms fit English, Spanish, German and similar languages; three forms fit Russian, + Ukrainian and Belarusian. Languages with other rules (Polish, Czech) pick the closer one. + +### 10.3 Weapon names + +Names of standard HL weapons are the same in every language, as in the mockup. They are tokens +`BHL_Weapon_` with English text in the English file, which the other languages +fall back to. An `Icon` value with a `d_*` sprite shows this name; for other sprites `Icon.text` +from the server is used. + +| Sprite | Name | +|----------------|----------| +| `d_crowbar` | Crowbar | +| `d_9mmhandgun` | Glock | +| `d_357` | .357 | +| `d_9mmAR` | MP5 | +| `d_shotgun` | Shotgun | +| `d_crossbow` | Crossbow | +| `d_bolt` | Crossbow | +| `d_rpg_rocket` | RPG | +| `d_gauss` | Gauss | +| `d_egon` | Egon | +| `d_hornet` | Hornet | +| `d_grenade` | Grenade | +| `d_satchel` | Satchel | +| `d_tripmine` | Tripmine | +| `d_snark` | Snark | + +## 11. Compatibility + +Client and server: + +| Client \ Server | Old / AG / Valve | New, inactive | New, scoreboard (`Config`) | New, HUD (elements) | +|-------------------------------------|------------------|---------------|----------------------------|--------------------------| +| Old (BugfixedHL, Valve, AG, OpenAG) | as now | as now | as now | as now; plugin HUD texts | +| New, defaults | standard | standard | custom | elements | +| New, `hud_scoreboard_custom 0` | standard | standard | standard | elements | +| New, `hud_server_elements 0` | standard | standard | custom | plugin HUD texts | +| New, both 0 | standard | standard | standard | plugin HUD texts | +| New, `_bhl` not in userinfo | standard | standard | custom via query ¹ | elements via query ¹ | + +The last two columns are independent: a server that sends a `Config` and elements gives the +scoreboard from the "New, scoreboard" column and the HUD from the "New, HUD" column. + +¹ If the client passes the p47 and LAN checks. A changed client setting reaches the server within +10 s (3.3). + +GunGame on a server with the new plugin: + +| Client | Scoreboard | HUD | +|--------------------------------|--------------------------------|-------------------------------------------------------------------------------------------------------------| +| Old | standard | Plugin informer, `StatusIcon`, warmup texts, all chat lines | +| New, defaults | GunGame columns, banner, badge | Elements with feed and announcer; plugin texts off except winner, start and chat lines the feeds don't show | +| New, `hud_server_elements 0` | GunGame columns, banner, badge | Plugin informer, `StatusIcon`, warmup texts, all chat lines; timer shown | +| New, `hud_scoreboard_custom 0` | standard | As with the defaults | +| New, both 0 | standard | Plugin informer, `StatusIcon`, warmup texts, all chat lines; timer shown | + +On a client that draws the elements, GunGame hides the BugfixedHL timer, the next map line and +custom timers (8.12). The bottom speedometer and `hud_jumpspeed` stay and can cross the level +strip. + +Module and server DLL: + +| `bugfixedapi_amxx` \ `hl.so` | API 1.0–1.3 | API 1.4 | +|------------------------------|-------------------------------------------------------------------------|------------| +| Old module | as now | as now | +| New module | old natives work, no `bhl_sb_*`, `bhl_hud_*`, `bhl_get_client_caps()` 0 | everything | +| No module | GunGame works as now | same | + +Draft 3 changes nothing for old clients, Valve, AG and OpenAG clients, old servers and existing +plugins: everything new travels in `BhlScore`, which only `ScoreboardV1` clients get, as a new +opcode, new kinds, params from id 32 and a block at the end of `Element`. The old natives keep +their behaviour; the new methods and natives are appended (9.1, 9.2). + +Draft test builds are not supported: the client, `hl.so`, the module and the plugin are updated +together. In draft 1 builds `_bhl` bit 1 and `Config` mean something else, and their `hl.so` +reports API 1.2. Draft 2 builds report API 1.3 without the methods of 1.4, cap the params of an +`Element` at 16 and know none of the new kinds, params and messages. The new module refuses both +(9.1). + +## 12. Test plan + +Capabilities: + +- From a second client, the first client's userinfo has no `_bhl` (keys with `_` are not forwarded). +- Fill the userinfo with `setinfo` keys: `_bhl` doesn't fit, `bhl_caps` shows source `Query`, the + custom scoreboard and the elements still work. +- `setinfo` during a game reaches `ClientUserInfoChanged`. `hud_scoreboard_custom 0/1` and + `hud_server_elements 0/1`, alone and together, switch the scoreboard, the elements and the plugin + texts both ways; only switching both off and on brings a full sync. +- Writing the same `_bhl` value again doesn't cause `ClientUserInfoChanged` spam. +- With source `Query`, `hud_server_elements 0/1` reaches the plugin within 10 s. +- `setinfo _bhl 2` and a bot with `_bhl 3`: `bhl_get_client_caps()` returns 0. +- Both cvars to 0, then one back to 1: no old data is drawn before the full sync. + +Protocol and server: + +- Every cell of the compatibility tables in section 11. +- Map change, reconnect, joining mid-game, GunGame on and off, teamplay. +- 32 players with bots: the full sync with the HUD part never triggers `Reliable channel overflowed`. +- The full sync arrives after the client's `VidInit` and nothing is lost; elements appear only + after their texts. +- A plugin with elements and hidden columns but no `Config`: the standard scoreboard and the + elements. +- Adding, changing, removing and removing all elements; ids reused after a removal; a removal and + a new element in one frame and during the 0.1 s pause, also with every other id taken (no old + variant is drawn); a kind change and back in one frame. +- A plugin that changes 32 cells every frame at `sys_ticrate 1000` never causes `Reliable channel + overflowed`. +- A parent defined after its child; a parent removed (the children disappear) and added again; a + parent id given to an unrelated element; a parent cycle; a banner element as a parent. +- Two plugins hiding different standard parts; a player-0 visibility write that doesn't change the + default drops the per-player overrides. +- Per-player texts and visibility: an English and a Russian player on one server, a spectator in + `OBS_IN_EYE` of a player with the other language, a player joining later, a reconnect into the + same slot. +- Malformed messages: short `Element`, `Template` and `HudState`, strings without a NUL, more params + than `count`, unknown kinds, places, fonts and params, templates for undefined elements. The + client doesn't crash (checked offline by feeding the parser). +- Layout without data: a `Strip` without a list and without a value, a `Meter` without a value, an + `Icon` without a value, each as a parent; `cell_min_wide` and `cell_gap` at their minimum at + 640×480. No division by zero. +- A template of 188 bytes is set; one of 189 bytes is refused with an error. +- An element without slot colors is sent with `colors` 0. A `Strip` with all 17 params and all 10 + color slots (181 bytes) is read whole; a slot of 10 or more and params of other kinds are skipped + and the slots after them still apply. +- A param of every kind on each kind; a param of another kind is refused. `bhl_hud_slot_color()` + with `r = -1` clears the slot, and the element is sent with `colors` 0 again. +- Events: to player 0 and to one player; a client without `HudV1`, or not ready yet, gets nothing, + also later; an event during the full sync of a client waits and arrives after its `HudState`; an + event for an element removed before it was sent waits and is dropped after its life; 9 events in + one frame give the newest 8 in order; a map change, `bhl_sb_reset()` and a reconnect into the slot + clear the queue; a full sync doesn't replay events. A non-feed key, variant 8, 5 numbers and a + player who is not connected return false. +- Malformed `Event` messages: a short header, `count` larger than the args, an unknown arg type, an + event for an element that is not a `Feed` or has no template for the variant. +- The new module with a draft 2 `hl.so` (API 1.3): `bhl_sb_available()` is false, + `bhl_get_client_caps()` 0, the other natives log one error and do nothing. + +Templates (an offline table run through the parser): + +- Word forms for 0, 1, 2, 5, 11, 12, 21, 22, 25 and −1 with 1, 2 and 3 forms, with and without `#`. +- `time` for −5, 0, 15, 75, 3600; `time2` for an `Int` and for running, stopped and counting-down + clocks; cuts in Latin and Cyrillic, `…` only when cut; `{{ }}`; a lone `}`; `{ref?}`; missing + refs. +- Literal: `{}`, `{ @place }`, `{Имя}`, an unclosed `{`, `#1`. Missing: `{x:foo}`, `{@foo}`. Parse + errors: `{x:cur:max}`, `{x:time|a|b}`, `{x:20:30}`, `{x:0}`, 17 placeholders. +- A client token that is missing; a token whose text is `#Other` is not looked up again. +- `^` refs and `@behind`, `@score`, `@frags`, `@deaths` with and without sort keys, in team mode and + without participants. +- A player named `{@place}` stays literal in `@rival` and in `Text` cells; one named + `#BHL_SB_Final` stays literal in `@name`, `@rival` and the `name` format. +- An element whose `value` is `@value`, `^@value` or `@value:cur`: the value is missing, without + recursion. +- `@index`, `@item` and `@value` in ranking and list boards; `@a`–`@d`, `{@a:name}`, `@icon` and an + arg of an unknown type in events; all of them and `{^@a}` are missing in a `Text` element. +- A `Board` template with TABs: 1, 4 and 5 columns. + +HUD elements of draft 3: + +- `Board`: ranking and list mode; `board_mode` 0, 1 and 2 with the own row first, last, in the + middle and outside the first rows; the separator; team mode; a roaming spectator has no own row; + numbers right-aligned and names left-aligned; icons of different widths and a missing sprite; + fill with `Progress` and `Int` values, 0 and negative ones; the own row with and without + variant 1. +- `Feed`: `queue` 0 with more lines than `lines`, lines expiring and fading; `queue` 1 with 3 events + in one frame shown one after another; more than 32 lines over two feeds; a removal and a `Reset` + drop the lines; top and bottom anchors, left, center and right alignment; a line with only an + icon, and one whose template has a missing value and no icon (dropped). +- `Box`: around a parent with children, a `Meter` counter and `Strip` scroll and track markers; + nothing drawn in the group hides it; a `Box` without a parent place and an element placed at a + `Box` are unplaced; a radius above half the height; the accent bar with and without slot 9; it + fades with its group. +- Effects: a flash on a content change only, none on appearance, a spectator switching players, a + full sync or a reconnect; `hold_ms` hides the element, and a change shows it again; a fade in, + out and reversed halfway; `hud_draw 0`, an intermission, `hud_server_elements 0`, a removal and a + kind change hide at once; `warn_at` with an `Int`, a `Progress` and a running `Clock`; the pulse; + the color order with `HudColor`, a variant slot, the warning and a flash. +- Ring: `max ≤ dots`, `max > dots`, `dots` 0 with `max` 10 (one dot per unit, no counter with + `counter` 1), `counter` 2; `dot_size` 2 and 64. +- Track: 1, 2 and 3 or more players on one cell, positions out of range, the subject left out, a + team subject with `Leader`, no markers over hidden cells. +- Sprite files: a precached file in a `Strip` list, an `Icon` element, a `Board`, a `Feed` line and + a scoreboard `Icon` column, with OpenGL and the software renderer; a missing file and a broken one + (wrong header, a frame above 1024) draw only the text and don't stop the engine, also with + `developer 2`; 33 different paths; a map change loads the files again. +- With OpenGL a `Box` and a `Board` plate drawn after a sprite of a lower id are translucent. + +GunGame scoreboard: + +- 640×480, 1280×720 and 1920×1080: the table has the size of the standard one and the columns fit. +- 12 and 32 players: compact spacing, then scrolling. +- 9, 14 and 24 levels in the level strip with the last step marked; dots without a counter with + 1–10 kills, the bar with the counter with more. +- Warmup: level, weapon and progress are hidden, kills and places by kills are shown; the match + columns come back when the match starts. +- Ties: shared places, the banner with several leaders on the last level; a long server name + next to the banner, and the banner laid out again when the leader changes; the `ФИНАЛ` badge + after the weapon on the last level only. +- A spectator who is on the last level doesn't bring the banner while the leader isn't. +- Teamplay with 2 and 4 teams: team headers with level, weapon, progress and the badge after the + weapon, player rows with kills only, players by kills, spectators at the bottom, the banner names + the team. At 640×480 the kills column and Ping both fit. +- `&` in the title, a column title, a `Text` cell, a team cell, a badge and a banner row: each + shows `&` and is not cut. +- After the win both banner rows are gone. +- Weapon icons in the scoreboard and the level strip with the OpenGL and the software renderer. +- A weapon with a non-standard sprite shows the name from the config. + +GunGame HUD: + +- The new elements match screenshots of the draft 1 widget at 640×480, 800×600, 1280×720, + 1920×1080 and 2560×1440, with 9, 14 and 24 levels and 3 and 25 kills per level. +- Cells shrink, then the window with `‹ ›` appears; the strip is lifted when it doesn't fit + between armor and ammo, with `hud_custom` 0 and 1. +- Warmup → countdown → game → win: the block changes, the plugin texts are not duplicated, the + block is empty after the win. +- Ties, a single player on the server, teamplay with 2 and 4 teams. +- Spectator in first-person, chase, map chase, roaming and free map modes; a dead player. +- A player who changes `lang` gets the texts in his new language. +- Kills per level ≤ 10 and > 10 (teamplay): dots and bar have the same length, the block doesn't jump. +- The timer, the next map line and custom timers are hidden while GunGame runs and come back + after `Disable_GunGame` and with `hud_server_elements 0`. The speedometer and `hud_jumpspeed` + stay in both positions. +- `gg_box` is behind the place, rival and kills in the match and behind the place alone in the + warmup, and fades with them. +- `gg_place` pulses red in the last 3 seconds of the warmup and of the countdown, never in the + match or after the win; it flashes on a place change in the match only. +- `gg_rival` colors for overtake, tied and lead; `gg_levels` markers with several players on one + level. +- `gg_top` with 2, 5 and 32 players, the own row after `…`, teams as rows in teamplay; hidden in the + warmup. +- Events: own level-up, skip, last level and level down in the announcer; the last level, a level + down and a new leader of others in the feed; level-ups of others below the last level give no + line and stay in chat; no leader event in teamplay, with one participant or on a tie; a lead + taken by kills or a descore alone; the first leader of a game after `gg_enable 0` and `1`; one + line for a team level down by `gg_set_player_level`; several announcer lines of one frame follow + each other; events also with the chat line turned off. +- A player with `hud_server_elements 0` gets every chat line and no events; turning it on stops + the chat lines that the feeds show. +- Feed and announcer lines in English, Russian and Spanish. diff --git a/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc b/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc index e4f067b1..09839949 100644 --- a/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc +++ b/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc @@ -135,3 +135,467 @@ native bhl_show_motd_from_file(E_MotdType:type, idx, const file[]); * @param deaths Number of deaths */ native bhl_set_player_score(idx, frags, deaths); + +//------------------------------------ +// Client capabilities, the scoreboard and HUD extension +// See docs/scoreboard-protocol.md in the BugfixedHL repository +//------------------------------------ + +enum BhlClientCaps +{ + BHL_CAPS_NONE = 0, + BHL_CAPS_SCOREBOARD_V1 = (1 << 0), + BHL_CAPS_HUD_V1 = (1 << 1) +}; + +enum BhlSbDisplay +{ + BHL_SB_TEXT = 0, + BHL_SB_ICON = 1, + BHL_SB_METER = 2, + BHL_SB_BUILTIN = 3, + BHL_SB_STEPS = 4, + BHL_SB_BADGE = 5 // added by bhl_sb_add_badge only +}; + +enum BhlSbHide +{ + BHL_SB_HIDE_NONE = 0, + BHL_SB_HIDE_FRAGS = (1 << 0), + BHL_SB_HIDE_DEATHS = (1 << 1), + BHL_SB_HIDE_EFF = (1 << 2), + BHL_SB_HIDE_STEAMID = (1 << 3) +}; + +enum BhlSbColumnFlags +{ + BHL_SB_COL_NONE = 0, + BHL_SB_COL_HIDDEN = (1 << 0), + BHL_SB_COL_CENTER = (1 << 1), + BHL_SB_COL_RIGHT = (2 << 1), + BHL_SB_COL_PRIMARY = (1 << 3), + BHL_SB_COL_MARK_LAST = (1 << 4) +}; + +enum BhlSbTarget +{ + BHL_SB_INVALID = -1, + BHL_SB_GLOBAL = 0 +}; + +#define BHL_SB_SORT_ASC 0x80 + +enum BhlSbClock +{ + BHL_SB_CLOCK_STOP = 0, + BHL_SB_CLOCK_RUN = (1 << 0), + BHL_SB_CLOCK_DOWN = (1 << 1) +}; + +enum BhlHudKind +{ + BHL_HUD_TEXT = 1, + BHL_HUD_METER = 2, + BHL_HUD_STRIP = 3, + BHL_HUD_ICON = 4, + BHL_HUD_BOARD = 5, // rows of the scoreboard order or of a list + BHL_HUD_FEED = 6, // lines of bhl_hud_event + BHL_HUD_BOX = 7 // backdrop of a group, placed with a parent place at the root of the group +}; + +enum BhlHudFont +{ + BHL_HUD_FONT_TEXT = 0, + BHL_HUD_FONT_LARGE = 1, + BHL_HUD_FONT_SMALL = 2, + BHL_HUD_FONT_HUGE = 3 +}; + +enum BhlHudAlign +{ + BHL_HUD_AUTO = 0, + BHL_HUD_LEFT = 1, + BHL_HUD_HCENTER = 2, + BHL_HUD_RIGHT = 3, + BHL_HUD_TOP = (1 << 2), + BHL_HUD_VCENTER = (2 << 2), + BHL_HUD_BOTTOM = (3 << 2) +}; + +enum BhlHudFlags +{ + BHL_HUD_NONE = 0, + BHL_HUD_SUBJECT = (1 << 1), + BHL_HUD_NO_SCOREBOARD = (1 << 2), + BHL_HUD_LEADER = (1 << 3), + BHL_HUD_DEFAULT = (1 << 1) | (1 << 2) +}; + +enum BhlHudPlace +{ + BHL_HUD_SCREEN = 0, + BHL_HUD_PARENT = 1, + BHL_HUD_NUMBERS_ROW = 2, + BHL_HUD_BANNER_TOP = 3, + BHL_HUD_BANNER_BOTTOM = 4, + BHL_HUD_PARENT_LEFT = 5, + BHL_HUD_PARENT_RIGHT = 6 +}; + +enum BhlHudParam +{ + BHL_HUD_P_DOTS = 1, + BHL_HUD_P_DOT_SIZE = 2, + BHL_HUD_P_DOT_GAP = 3, + BHL_HUD_P_BAR_WIDE = 4, + BHL_HUD_P_COUNTER = 5, + BHL_HUD_P_COUNTER_GAP = 6, + BHL_HUD_P_ALPHA_EMPTY = 7, + BHL_HUD_P_CELL_WIDE = 10, + BHL_HUD_P_CELL_MIN_WIDE = 11, + BHL_HUD_P_CELL_TALL = 12, + BHL_HUD_P_CELL_GAP = 13, + BHL_HUD_P_ICON_PADDING = 14, + BHL_HUD_P_MAX_WIDE = 15, + BHL_HUD_P_ALPHA_PASSED = 16, + BHL_HUD_P_ALPHA_CURRENT = 17, + BHL_HUD_P_ALPHA_FUTURE = 18, + BHL_HUD_P_ALPHA_ICON_FUTURE = 19, + BHL_HUD_P_FRAME = 20, + BHL_HUD_P_ICON_TALL = 30, + BHL_HUD_P_ICON_GAP = 31, + BHL_HUD_P_FLASH_MS = 32, // every kind + BHL_HUD_P_FADE_MS = 33, // every kind + BHL_HUD_P_HOLD_MS = 34, // every kind + BHL_HUD_P_WARN_AT = 35, // every kind + BHL_HUD_P_WARN_PULSE_MS = 36, // every kind + BHL_HUD_P_FORM = 40, // 0 dots or bar, 1 ring + BHL_HUD_P_TRACK = 41, // 0 off, 1 marks of the other players + BHL_HUD_P_ROWS = 44, + BHL_HUD_P_BOARD_MODE = 45, // 0 first rows, 1 first rows and the own row, 2 rows around the own row + BHL_HUD_P_ROW_GAP = 46, + BHL_HUD_P_COLUMN_GAP = 47, + BHL_HUD_P_FILL_ALPHA = 48, + BHL_HUD_P_HIGHLIGHT_ALPHA = 49, + BHL_HUD_P_LINES = 52, + BHL_HUD_P_LIFE_MS = 53, + BHL_HUD_P_LINE_FADE_MS = 54, + BHL_HUD_P_QUEUE = 55, // 0 newest lines on top, 1 one line at a time + BHL_HUD_P_LINE_GAP = 56, + BHL_HUD_P_ACCENT_WIDE = 60, + BHL_HUD_P_RADIUS = 61 +}; + +enum BhlHudStd +{ + BHL_HUD_STD_NONE = 0, + BHL_HUD_STD_TIMER = (1 << 0), + BHL_HUD_STD_NEXTMAP = (1 << 1), + BHL_HUD_STD_CUSTOM_TIMERS = (1 << 2), + BHL_HUD_STD_SPEEDOMETER = (1 << 3), + BHL_HUD_STD_JUMPSPEED = (1 << 4) +}; + +#define BHL_HUD_COLOR -1 +#define BHL_HUD_MAX_TEXT 188 + +// Color slots of bhl_hud_slot_color after the text variants 0-7 +#define BHL_HUD_SLOT_WARN 8 +#define BHL_HUD_SLOT_ACCENT 9 + +/** + * Returns the scoreboard target of a player. + * @param idx Player's index + */ +stock BhlSbTarget:bhl_sb_player(idx) +{ + return BhlSbTarget:idx; +} + +/** + * Returns the scoreboard target of a team. + * The target stays valid until the map changes. + * @param teamName Team name, the same that get_user_team() returns + * @return Team target or BHL_SB_INVALID + */ +native BhlSbTarget:bhl_sb_team(const teamName[]); + +/** + * Returns features the client reports to the server. + * BHL_CAPS_HUD_V1 is only set together with BHL_CAPS_SCOREBOARD_V1. Bots and HLTV get BHL_CAPS_NONE. + * Use bitwise AND to check: + * if (bhl_get_client_caps(idx) & BHL_CAPS_HUD_V1) { ... } + * @param idx Player's index + * @return BhlClientCaps bitfield, BHL_CAPS_NONE on servers without the feature + */ +native BhlClientCaps:bhl_get_client_caps(idx); + +/** + * Called when the value returned by bhl_get_client_caps() changes for a player in game, + * for example when he changes hud_server_elements. + * Not called for the caps a player has when he joins: check bhl_get_client_caps() when you need it. + * @param idx Player's index + */ +forward bhl_client_caps_changed(idx); + +/** + * Returns whether the server supports the scoreboard and HUD extension (server API 1.4 or newer). + * All other bhl_sb_* and bhl_hud_* natives log one error and do nothing when it returns false. + */ +native bool:bhl_sb_available(); + +/** + * Removes everything of every plugin: schema, values, lists, elements, texts, visibility + * and hidden standard HUD parts. Clients return to the standard scoreboard and HUD. + */ +native bhl_sb_reset(); + +/** + * Turns the custom scoreboard on. + * Not needed for HUD elements: a plugin that only adds elements keeps the standard scoreboard. + * @param hide Standard columns to hide + * @param title Replaces the server name if not empty + * @param tag Badge after the server name, for example "FFA" + */ +native bhl_sb_config(BhlSbHide:hide, const title[] = "", const tag[] = ""); + +/** + * Adds a column, or replaces the column with the same key. Its values are kept. + * Custom and built-in columns are shown in the order their keys were first added; re-adding a key + * keeps its place. rank is always first. Standard columns that no built-in column moves keep + * their default places. + * @param key Up to 15 characters of [a-z0-9_]. For BHL_SB_BUILTIN one of: + * rank, frags, deaths, eff, steamid, ping + * @param title Text or #token shipped with the client, "" for the default title of a built-in column + * @param display How the values are drawn; BHL_SB_BADGE is refused, use bhl_sb_add_badge + * @param width Width in proportional units, 0 for the default + * @param sort 0 or sort priority starting at 1, plus BHL_SB_SORT_ASC for ascending order + * @param flags Column flags + * @return true on success + */ +native bool:bhl_sb_add_column(const key[], const title[], BhlSbDisplay:display = BHL_SB_TEXT, + width = 0, sort = 0, BhlSbColumnFlags:flags = BHL_SB_COL_NONE); + +/** + * Adds a badge column: its values are drawn as badges after the values of the column host. + * Values are set with the usual bhl_sb_set_* natives. A #token is localized. + * @param key Up to 15 characters of [a-z0-9_] + * @param host Key of the column the badges follow; it may be added later + * @return true on success + */ +native bool:bhl_sb_add_badge(const key[], const host[]); + +/** + * Sets a value of a column for a target. + * Values for players that are not connected are ignored. + * Setting the value a cell already has sends nothing. + * @param target BHL_SB_GLOBAL, bhl_sb_player(idx) or bhl_sb_team(name) + * @param key Column key + */ +native bhl_sb_set_int(BhlSbTarget:target, const key[], value); +native bhl_sb_set_text(BhlSbTarget:target, const key[], const text[]); +native bhl_sb_set_icon(BhlSbTarget:target, const key[], const sprite[], const text[]); +native bhl_sb_set_progress(BhlSbTarget:target, const key[], cur, max); + +/** + * Sets a clock: a time that the client runs itself, for timers that change every frame. + * @param ms Value now, in milliseconds + * @param flags BHL_SB_CLOCK_RUN runs it, BHL_SB_CLOCK_DOWN makes it count down to 0 + */ +native bhl_sb_set_clock(BhlSbTarget:target, const key[], ms, BhlSbClock:flags = BHL_SB_CLOCK_RUN); + +/** + * Clears a value of a target, or every value of the target if key is empty. + */ +native bhl_sb_clear(BhlSbTarget:target, const key[] = ""); + +/** + * Creates a list on first use and sets its size (up to 64 items). + * @param key Up to 15 characters of [a-z0-9_] + * @return true on success + */ +native bool:bhl_sb_list_resize(const key[], count); + +/** + * Sets an item of a list. Items out of range are ignored. + */ +native bhl_sb_list_set_int(const key[], index, value); +native bhl_sb_list_set_text(const key[], index, const text[]); +native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]); + +/** + * Adds a HUD element, or changes kind, position, font, anchors and flags of an existing one. + * A new element is shown, is placed on the screen, follows hud_color with alpha 255 and has + * no refs, params or texts. A kind change drops its texts, refs and params. + * @param key Up to 15 characters of [a-z0-9_], in their own namespace + * @param kind Kind of the element + * @param x Like in set_hudmessage: 0.0-1.0 from the left, negative from the right, -1.0 is the center + * @param y The same from the top + * @param font Font of the texts + * @param align Horizontal and vertical anchor, BHL_HUD_AUTO follows set_hudmessage + * @param flags Element flags; the color mode comes from bhl_hud_color + * @return false for an invalid key or kind, or when 32 elements exist + */ +native bool:bhl_hud_add(const key[], BhlHudKind:kind, Float:x = -1.0, Float:y = -1.0, + BhlHudFont:font = BHL_HUD_FONT_TEXT, BhlHudAlign:align = BHL_HUD_AUTO, + BhlHudFlags:flags = BHL_HUD_DEFAULT); + +/** + * Sets what the position of an element is relative to. + * While no element has the key parent, the element is not drawn. + * @param place Place of the element + * @param parent Key of the parent for the parent places; it may be added later + * @param gap Distance to the parent, or the margin on the numbers row, in proportional units + * @return false for an unknown element or place, or an invalid parent key + */ +native bool:bhl_hud_place(const key[], BhlHudPlace:place, const parent[] = "", gap = 0); + +/** + * Sets the color of an element. + * @param r 0-255, or BHL_HUD_COLOR to follow hud_color (g and b are ignored then) + * @return false for an unknown element + */ +native bool:bhl_hud_color(const key[], r = BHL_HUD_COLOR, g = 0, b = 0, a = 255); + +/** + * Sets the data an element shows. + * In Pawn strings the ^ prefix of a ref is written ^^. + * @param value Column key or built-in value with an optional ^ and one of :cur, :max and :left, + * for example "progress", "@state", "level:left", "^^weapon" + * @param list List key: the icons of a strip, the rows of a board + * @param select Ref like value whose number picks the text variant 0-7, "" for variant 0 + * @return false for an unknown element, an invalid ref or list key, or when the element + * would not fit in a message; nothing changes then + */ +native bool:bhl_hud_bind(const key[], const value[] = "", const list[] = "", const select[] = ""); + +/** + * Sets a parameter of an element kind, or of every kind. The value is clamped to the range of the parameter. + * @return false for an unknown element, a parameter of another kind, or when the element + * would not fit in a message + */ +native bool:bhl_hud_param(const key[], BhlHudParam:param, value); + +/** + * Sets a text variant of an element: a template with placeholders such as {@place} and {level:cur}. + * In Pawn strings the ^ prefix of a ref is written ^^: "{^^weapon}". + * Formats like format(): %L works and %% writes %. A result longer than BHL_HUD_MAX_TEXT bytes + * is not set. Never format text typed by players into a template; escape server strings + * with bhl_hud_escape(). + * @param player 0 sets the default for everybody and drops the per-player texts of the variant, + * a player index sets the text for that player only until his slot is cleared + * (connect, disconnect), so set it again in client_putinserver + * @param variant 0-7 + * @param fmt Template, "" removes the variant + * @return false for an unknown element, a variant out of range, a player out of range + * or not connected, or a too long text + */ +native bool:bhl_hud_text(player, const key[], variant, const fmt[], any:...); + +/** + * Shows or hides an element. + * @param player 0 sets the default for everybody and drops the per-player visibility, + * a player index sets it for that player only until his slot is cleared + * (connect, disconnect), so set it again in client_putinserver + * @return false for an unknown element, or a player out of range or not connected + */ +native bool:bhl_hud_show(player, const key[], bool:show = true); + +/** + * Removes an element, or every element if key is empty. + */ +native bhl_hud_remove(const key[] = ""); + +/** + * Hides or shows standard HUD parts on clients that draw the elements. + * Changes only the given parts, so plugins that hide different parts don't undo each other. + */ +native bhl_hud_hide_std(BhlHudStd:parts, bool:hide = true); + +/** + * Sets the color of a color slot of an element. It replaces the color of the element while that + * text variant is drawn (slots 0-7), while the warn_at param holds (BHL_HUD_SLOT_WARN), or for + * the accent bar of a box (BHL_HUD_SLOT_ACCENT). It is used as is, also for elements that follow + * hud_color. A kind change drops the slot colors. + * @param slot 0-7, BHL_HUD_SLOT_WARN or BHL_HUD_SLOT_ACCENT + * @param r 0-255, or -1 to clear the slot (g, b and a are ignored then) + * @return false for an unknown element, a slot out of range, or when the element + * would not fit in a message + */ +native bool:bhl_hud_slot_color(const key[], slot, r, g, b, a = 255); + +/** + * Adds a line to a feed: the text variant is evaluated once with the numbers and the icon. + * In the template {@a} to {@d} are the numbers ({@a:name} writes the name of the player with + * that index) and {@icon} is the icon text; the icon sprite is drawn before the line. + * Lines are not kept: only players in game who draw elements (BHL_CAPS_HUD_V1) get them now, + * and a line that can't be sent before its life ends is dropped. + * @param player 0 for every player, or a player index + * @param key Key of a BHL_HUD_FEED element + * @param variant Text variant 0-7 + * @param life_ms How long the line is shown, up to 65535, 0 for the life_ms param of the element + * @param sprite Icon of the line: hud.txt name or "sprites/.spr" precached by the plugin, "" for none + * @param sprite_text Text of the icon, written by {@icon} + * @param ... Up to 4 numbers + * @return false for an unknown element or one that is not a feed, a variant out of range, + * a player out of range or not connected, or more than 4 numbers + */ +native bool:bhl_hud_event(player, const key[], variant, life_ms = 0, const sprite[] = "", + const sprite_text[] = "", any:...); + +/** + * Sets a text variant from the plugin dictionary: for one player in his language, + * or for player 0 the default in the server language plus every player in game in his language. + * Players who join later get the default, so call it with the player index in client_putinserver. + * In the dictionary ^ is written once. AMXX turns ^n, ^t and ^1-^4 there into control characters + * and breaks every other ^ after them in the same text, so a ^ ref can't name a key that starts + * with n, t or 1-4 and can't follow such an escape. + * @param mlKey Dictionary key; a literal % in the text is written %% + */ +stock bool:bhl_hud_text_lang(player, const key[], variant, const mlKey[]) +{ + if (player) + return bhl_hud_text(player, key, variant, "%L", player, mlKey); + + new players[32], num; + get_players(players, num, "ch"); + bhl_hud_text(0, key, variant, "%L", LANG_SERVER, mlKey); + + for (new i; i < num; i++) + bhl_hud_text(players[i], key, variant, "%L", players[i], mlKey); + + return true; +} + +// +// Doubles { and } so that a server string formatted into a template stays literal. +// A too long string is cut on a UTF-8 character boundary. src and dst must be different arrays. +// len is charsmax(dst). Returns the number of characters written. +// +stock bhl_hud_escape(const src[], dst[], len) +{ + new i, j; + + for (; src[i] && j < len; i++) + { + if (src[i] == '{' || src[i] == '}') + { + if (j + 2 > len) + break; + + dst[j++] = src[i]; + } + + dst[j++] = src[i]; + } + + // The next byte continues a character, so drop its copied part + while (j > 0 && (src[i] & 0xC0) == 0x80) + { + i--; + j--; + } + + dst[j] = EOS; + return j; +} diff --git a/gamedir/ui/resource/ClientSchemeBase.res b/gamedir/ui/resource/ClientSchemeBase.res index dba66c7e..45b530d6 100644 --- a/gamedir/ui/resource/ClientSchemeBase.res +++ b/gamedir/ui/resource/ClientSchemeBase.res @@ -596,6 +596,172 @@ Scheme "custom" "1" } } + + // HUD elements defined by the server (HudServerPanel) + "HudServerText" // text of HUD elements defined by the server + { + "1" + { + "name" "Verdana" + "tall" "12" + "weight" "600" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "13" + "weight" "600" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "14" + "weight" "600" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "20" + "weight" "600" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "24" + "weight" "600" + "yres" "1200 6000" + "antialias" "1" + } + } + "HudServerLarge" // large font of HUD elements + { + "1" + { + "name" "Verdana" + "tall" "16" + "weight" "800" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "18" + "weight" "800" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "20" + "weight" "800" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "28" + "weight" "800" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "34" + "weight" "800" + "yres" "1200 6000" + "antialias" "1" + } + } + "HudServerSmall" // small font of HUD elements + { + "1" + { + "name" "Verdana" + "tall" "10" + "weight" "600" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "11" + "weight" "600" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "12" + "weight" "600" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "16" + "weight" "600" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "18" + "weight" "600" + "yres" "1200 6000" + "antialias" "1" + } + } + "HudServerHuge" // huge font of HUD elements + { + "1" + { + "name" "Verdana" + "tall" "24" + "weight" "800" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "28" + "weight" "800" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "32" + "weight" "800" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "44" + "weight" "800" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "52" + "weight" "800" + "yres" "1200 6000" + "antialias" "1" + } + } } // diff --git a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt index 2484a8b1..e3990a32 100644 --- a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt @@ -24,6 +24,40 @@ "BHL_Scores_MenuCopySteamID" "Copy SteamID" "BHL_Scores_MenuCopySteamID64" "Copy SteamID64" +// Scoreboard extension +"BHL_SB_Level" "Level" +"BHL_SB_Weapon" "Weapon" +"BHL_SB_Progress" "Progress" +"BHL_SB_Kills" "Kills" +"BHL_SB_Final" "FINAL" + +// HUD element templates (docs/scoreboard-protocol.md, 8.10): keep the placeholders in braces. +// A list of word forms picks one by the number: 2 forms in English, 3 in Russian. +"BHL_HUD_Place" "PLACE {@place} / {@total}" +"BHL_HUD_Overtake" "To pass {@rival:20}: {@pass|# kill|# kills}" +"BHL_HUD_Lead" "Lead: {@lead|# kill|# kills}" +"BHL_HUD_Tied" "Tied" +"BHL_HUD_Waiting" "Waiting for opponents" +"BHL_HUD_Warmup" "WARMUP {@value:time}" +"BHL_HUD_StartIn" "START IN {@value}" + +// Weapon names: English in every language, the other files fall back to this one +"BHL_Weapon_crowbar" "Crowbar" +"BHL_Weapon_9mmhandgun" "Glock" +"BHL_Weapon_357" ".357" +"BHL_Weapon_9mmAR" "MP5" +"BHL_Weapon_shotgun" "Shotgun" +"BHL_Weapon_crossbow" "Crossbow" +"BHL_Weapon_bolt" "Crossbow" +"BHL_Weapon_rpg_rocket" "RPG" +"BHL_Weapon_gauss" "Gauss" +"BHL_Weapon_egon" "Egon" +"BHL_Weapon_hornet" "Hornet" +"BHL_Weapon_grenade" "Grenade" +"BHL_Weapon_satchel" "Satchel" +"BHL_Weapon_tripmine" "Tripmine" +"BHL_Weapon_snark" "Snark" + "BHL_Update_Notif_Title" "Update notification" "BHL_Update_Notif_Text" "A new update has been released." "BHL_Update_Notif_OldVer" "Your version: " diff --git a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt index 8b8ddd24..01ea5a54 100644 --- a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt @@ -24,6 +24,23 @@ "BHL_Scores_MenuCopySteamID" "Скопировать SteamID" "BHL_Scores_MenuCopySteamID64" "Скопировать SteamID64" +// Scoreboard extension +"BHL_SB_Level" "Уровень" +"BHL_SB_Weapon" "Оружие" +"BHL_SB_Progress" "Прогресс" +"BHL_SB_Kills" "Убийства" +"BHL_SB_Final" "ФИНАЛ" + +// HUD element templates (docs/scoreboard-protocol.md, 8.10): keep the placeholders in braces. +// A list of word forms picks one by the number: 2 forms in English, 3 in Russian. +"BHL_HUD_Place" "МЕСТО {@place} / {@total}" +"BHL_HUD_Overtake" "До обгона {@rival:20}: {@pass|# убийство|# убийства|# убийств}" +"BHL_HUD_Lead" "Отрыв: {@lead|# убийство|# убийства|# убийств}" +"BHL_HUD_Tied" "Вровень" +"BHL_HUD_Waiting" "Ожидание соперников" +"BHL_HUD_Warmup" "РАЗМИНКА {@value:time}" +"BHL_HUD_StartIn" "СТАРТ ЧЕРЕЗ {@value}" + "BHL_Update_Notif_Title" "Уведомление об обновлении" "BHL_Update_Notif_Text" "Вышло новое обновление." "BHL_Update_Notif_OldVer" "Ваша версия: " diff --git a/gamedir/ui/scripts/HudLayoutBase.res b/gamedir/ui/scripts/HudLayoutBase.res index 2bcb5cd7..1c819a63 100644 --- a/gamedir/ui/scripts/HudLayoutBase.res +++ b/gamedir/ui/scripts/HudLayoutBase.res @@ -106,4 +106,72 @@ "default_name_color_kill" "OffWhite" "default_name_color_death" "OffWhite" } + + HudServerPanel + { + "fieldName" "HudServerPanel" + "visible" "1" + "enabled" "1" + "xpos" "0" + "ypos" "0" + "wide" "f0" + "tall" "f0" + + // Defaults of the params of HUD elements defined by the server; a param sent by the server wins. + // Sizes are proportional units of a 640x480 screen, alphas are 0-255 and apply to the element color. + + // Meter: dots, or a rounded bar with a counter + "dots" "10" // Up to this max the meter is drawn as dots, above it as a bar; 0: always a bar + "dot_size" "7" // Diameter of a dot, height of the bar + "dot_gap" "3" // Distance between dots + "bar_wide" "0" // Length of the bar; 0: the length of "dots" dots (10 for 0 dots) + "counter" "1" // Counter: 0 never, 1 with the bar, 2 always + "counter_gap" "6" // Distance between the meter and the counter + "alpha_empty" "80" // Empty part of the bar + "form" "0" // 0: dots or a bar, 1: a ring of dots with the counter inside + + // Strip: a row of cells, the current one framed + "cell_wide" "30" // Width of a cell + "cell_min_wide" "14" // Cells shrink down to this width, then the strip shows a window around the current cell + "cell_tall" "15" // Height of a cell + "cell_gap" "3" // Distance between cells + "icon_padding" "2" // Padding of the icon inside a cell + "max_wide" "300" // Width limit of the strip; 0: the screen width + "alpha_passed" "112" // Cells before the current one + "alpha_current" "48" // Current cell + "alpha_future" "24" // Cells after the current one + "alpha_icon_future" "80" // Icons and texts of the cells after the current one + "frame" "1" // 1: the current cell has a frame + "track" "0" // 1: markers of the other players above the cells they are on + + // Icon: a sprite of hud.txt with a text after it + "icon_tall" "0" // Height of the icon; 0: the height of the element font + "icon_gap" "2" // Distance between the icon and the text + + // Board: rows of the ranking or of a list + "rows" "3" // Number of rows + "board_mode" "0" // 0: the first rows, 1: also the own row after them, 2: rows around the own row + "row_gap" "2" // Distance between rows + "column_gap" "8" // Distance between columns (TAB characters in the row text) + "fill_alpha" "0" // Bar behind a row by its value + "highlight_alpha" "48" // Plate behind the own row + + // Feed: lines of events + "lines" "4" // Number of lines + "life_ms" "5000" // Life of a line when the event doesn't give one + "line_fade_ms" "400" // A line fades in and out over this time + "queue" "0" // 0: the newest lines on top, 1: one line at a time in arrival order + "line_gap" "2" // Distance between lines + + // Box: a backdrop of a group of elements + "accent_wide" "0" // Width of the accent bar on the left edge + "radius" "0" // Radius of the corners + + // Every kind + "flash_ms" "0" // The color flashes white when the content changes + "fade_ms" "0" // The element fades in and out + "hold_ms" "0" // After it appears or changes the element is shown this long; 0: always + "warn_at" "0" // While the value is at most this, the element has the warn color; 0: off + "warn_pulse_ms" "0" // Period of the alpha pulse while warning; 0: no pulse + } } diff --git a/src/bugfixedapi_amxx/bhl_api.cpp b/src/bugfixedapi_amxx/bhl_api.cpp index 95dbb95d..74e67dbc 100644 --- a/src/bugfixedapi_amxx/bhl_api.cpp +++ b/src/bugfixedapi_amxx/bhl_api.cpp @@ -23,6 +23,11 @@ bool bhl::IsServerApiReady() return (g_pServerApi != nullptr); } +bool bhl::IsScoreboardApiReady() +{ + return g_pServerApi != nullptr && g_iServerMinor >= SCOREBOARD_API_MINOR; +} + bhl::E_ApiInitResult bhl::InitServerApi() { assert(!IsServerApiReady()); @@ -50,7 +55,7 @@ bhl::E_ApiInitResult bhl::InitServerApi() // Check version pIface->GetInterfaceVersion(g_iServerMajor, g_iServerMinor); - if (!(g_iServerMajor == IBUGFIXEDSERVER_MAJOR && g_iServerMinor >= IBUGFIXEDSERVER_MINOR)) + if (g_iServerMajor != IBUGFIXEDSERVER_MAJOR) return E_ApiInitResult::VersionMismatch; g_pServerApi = pIface; diff --git a/src/bugfixedapi_amxx/bhl_api.h b/src/bugfixedapi_amxx/bhl_api.h index 7a84acd9..4c7209a0 100644 --- a/src/bugfixedapi_amxx/bhl_api.h +++ b/src/bugfixedapi_amxx/bhl_api.h @@ -16,6 +16,9 @@ enum class E_ApiInitResult VersionMismatch // GetInterfaceVersion returned incompatible version }; +//! Server API minor version of the IScoreboardExt layout the natives call: older draft builds have another one and would crash (docs/scoreboard-protocol.md, 9.1) +constexpr int SCOREBOARD_API_MINOR = 4; + /** * @returns pointer to server API or nullptr */ @@ -26,6 +29,11 @@ bhl::IBugfixedServer *serverapi(); */ bool IsServerApiReady(); +/** + * Return true if API is available and has every method of IScoreboardExt (v1.4 or newer). + */ +bool IsScoreboardApiReady(); + /** * Initializes server API. * Uses functions from interface.h to get API pointer and check the version. diff --git a/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp b/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp index e1944cf2..cb3180ba 100644 --- a/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp +++ b/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp @@ -1,5 +1,10 @@ +#include +#include +#include +#include #include "amxxmodule.h" #include "bhl_api.h" +#include #ifndef _WIN32 #include @@ -176,6 +181,286 @@ static cell AMX_NATIVE_CALL bhl_set_player_score(AMX *amx, cell *params) return 1; } +static int g_iClientCapsChangedFwd = -1; +static bhl::E_ClientCaps g_ClientCaps[32 + 1]; +static bool g_bScoreboardErrorLogged = false; + +extern AMX_NATIVE_INFO bugfixedapi_Exports[]; + +//! Returns the file name of the plugin that owns amx, for log messages +static const char *GetPluginName(AMX *amx) +{ + const char *path = MF_GetScriptName(MF_FindScriptByAmx(amx)); + + if (!path) + return "unknown"; + + const char *name = path; + + for (const char *c = path; *c; c++) + { + if (*c == '/' || *c == '\\') + name = c + 1; + } + + return name; +} + +/** + * Returns true if the server has the scoreboard and HUD extension. + * Otherwise logs once per map, with the name native is registered under. + * Errors are logged with MF_Log: MF_LogError would abort the plugin's callback. + */ +static bool CheckScoreboardApi(AMX *amx, AMX_NATIVE native) +{ + if (bhl::IsScoreboardApiReady()) + return true; + + if (!g_bScoreboardErrorLogged) + { + const AMX_NATIVE_INFO *info = bugfixedapi_Exports; + + while (info->func != native) + info++; + + if (bhl::IsServerApiReady()) + { + int major = 0, minor = 0; + bhl::GetServerApiVersion(major, minor); + MF_Log("%s: server API %d.%d doesn't support the scoreboard and HUD extension (requires %d.%d). bhl_sb_* and bhl_hud_* natives will not function (plugin \"%s\").", info->name, major, minor, IBUGFIXEDSERVER_MAJOR, bhl::SCOREBOARD_API_MINOR, GetPluginName(amx)); + } + else + { + MF_Log("%s: server API is not available. bhl_sb_* and bhl_hud_* natives will not function (plugin \"%s\").", info->name, GetPluginName(amx)); + } + + g_bScoreboardErrorLogged = true; + } + + return false; +} + +//! Logs one line for a bhl_hud_* call that failed. Returns 0, the result of the failed native. +static cell LogHudError(AMX *amx, const char *native, const char *key, const char *fmt, ...) +{ + char reason[512]; + va_list args; + va_start(args, fmt); + vsnprintf(reason, sizeof(reason), fmt, args); + va_end(args); + + MF_Log("%s: %s (element \"%s\", plugin \"%s\").", native, reason, key, GetPluginName(amx)); + return 0; +} + +//! Converts param Pos + 1 of a native to argument Pos of an IScoreboardExt method; a string uses the AMXX buffer Pos +template +static T GetMethodArg(AMX *amx, cell *params) +{ + if constexpr (std::is_same_v) + { + static_assert(Pos < 4, "AMXX has 4 string buffers"); + return MF_GetAmxString(amx, params[Pos + 1], Pos, nullptr); + } + else + { + static_assert(std::is_integral_v, "only strings and integers are forwarded, a float needs amx_ctof"); + return static_cast(params[Pos + 1]); + } +} + +//! Calls the method with the params of the native in order; a void method returns 1 +template +static cell CallMethod(AMX *amx, cell *params, bhl::IScoreboardExt *sb, R (bhl::IScoreboardExt::*method)(Args...), std::integer_sequence) +{ + if constexpr (std::is_void_v) + { + (sb->*method)(GetMethodArg(amx, params)...); + return 1; + } + else + { + return (cell)(sb->*method)(GetMethodArg(amx, params)...); + } +} + +template +static cell CallMethod(AMX *amx, cell *params, bhl::IScoreboardExt *sb, R (bhl::IScoreboardExt::*method)(Args...)) +{ + return CallMethod(amx, params, sb, method, std::make_integer_sequence()); +} + +/** + * Calls a bhl_sb_* or bhl_hud_* native, or returns FailValue if CheckScoreboardApi fails. + * Native is a function (AMX *, cell *, bhl::IScoreboardExt *) or an IScoreboardExt method that takes the params in order. + */ +template +static cell AMX_NATIVE_CALL ScoreboardNative(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(amx, ScoreboardNative)) + return FailValue; + + bhl::IScoreboardExt *sb = bhl::serverapi()->GetScoreboard(); + + if constexpr (std::is_member_function_pointer_v) + return CallMethod(amx, params, sb, Native); + else + return Native(amx, params, sb); +} + +// native BhlClientCaps:bhl_get_client_caps(idx) +static cell AMX_NATIVE_CALL bhl_get_client_caps(AMX *amx, cell *params) +{ + if (!bhl::IsScoreboardApiReady()) + return 0; + int idx = params[1]; + if (idx < 1 || idx > gpGlobals->maxClients) + return 0; + return (cell)bhl::serverapi()->GetClientCaps(idx); +} + +// native bool:bhl_sb_available() +static cell AMX_NATIVE_CALL bhl_sb_available(AMX *amx, cell *params) +{ + return bhl::IsScoreboardApiReady(); +} + +// native bool:bhl_hud_add(const key[], BhlHudKind:kind, Float:x = -1.0, Float:y = -1.0, BhlHudFont:font = BHL_HUD_FONT_TEXT, BhlHudAlign:align = BHL_HUD_AUTO, BhlHudFlags:flags = BHL_HUD_DEFAULT) +static cell bhl_hud_add(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + int kind = params[2]; + + if (!sb->HudAdd(key, kind, amx_ctof(params[3]), amx_ctof(params[4]), params[5], params[6], static_cast(params[7]))) + return LogHudError(amx, __func__, key, "invalid key or kind %d, or all %d elements are used", kind, bhl::sb::MAX_ELEMENTS); + + return 1; +} + +// native bool:bhl_hud_place(const key[], BhlHudPlace:place, const parent[] = "", gap = 0) +static cell bhl_hud_place(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + const char *parent = MF_GetAmxString(amx, params[3], 1, nullptr); + int place = params[2]; + + if (!sb->HudSetPlace(key, place, parent, params[4])) + return LogHudError(amx, __func__, key, "unknown element or place %d, or invalid parent key \"%s\"", place, parent); + + return 1; +} + +// native bool:bhl_hud_color(const key[], r = BHL_HUD_COLOR, g = 0, b = 0, a = 255) +static cell bhl_hud_color(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + + if (!sb->HudSetColor(key, params[2], params[3], params[4], params[5])) + return LogHudError(amx, __func__, key, "unknown element"); + + return 1; +} + +// native bool:bhl_hud_bind(const key[], const value[] = "", const list[] = "", const select[] = "") +static cell bhl_hud_bind(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + const char *value = MF_GetAmxString(amx, params[2], 1, nullptr); + const char *list = MF_GetAmxString(amx, params[3], 2, nullptr); + const char *select = MF_GetAmxString(amx, params[4], 3, nullptr); + + if (!sb->HudBind(key, value, list, select)) + return LogHudError(amx, __func__, key, "unknown element, invalid value \"%s\", list \"%s\" or select \"%s\", or the element would exceed %d bytes", value, list, select, bhl::sb::MAX_MSG_SIZE); + + return 1; +} + +// native bool:bhl_hud_param(const key[], BhlHudParam:param, value) +static cell bhl_hud_param(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + int param = params[2]; + + if (!sb->HudSetParam(key, param, params[3])) + return LogHudError(amx, __func__, key, "unknown element, its kind has no param %d, or the element would exceed %d bytes", param, bhl::sb::MAX_MSG_SIZE); + + return 1; +} + +// native bool:bhl_hud_text(player, const key[], variant, const fmt[], any:...) +static cell bhl_hud_text(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + int player = params[1]; + int variant = params[3]; + int textLength = 0; + const char *text = MF_FormatAmxString(amx, params, 4, &textLength); + + // AMXX has reported the format error, the buffer holds a partial text + if (amx->error != AMX_ERR_NONE) + return 0; + + const char *key = MF_GetAmxString(amx, params[2], 0, nullptr); + + // A cut template could end inside a placeholder, so it is refused instead + if (textLength > bhl::sb::MAX_TEMPLATE_LEN) + return LogHudError(amx, __func__, key, "the text for player %d, variant %d has %d bytes, more than %d", player, variant, textLength, bhl::sb::MAX_TEMPLATE_LEN); + + if (!sb->HudSetText(player, key, variant, text)) + return LogHudError(amx, __func__, key, "unknown element, variant %d out of range, or player %d out of range or not connected", variant, player); + + return 1; +} + +// native bool:bhl_hud_show(player, const key[], bool:show = true) +static cell bhl_hud_show(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[2], 0, nullptr); + int player = params[1]; + + if (!sb->HudShow(player, key, params[3] != 0)) + return LogHudError(amx, __func__, key, "unknown element, or player %d out of range or not connected", player); + + return 1; +} + +// native bool:bhl_hud_slot_color(const key[], slot, r, g, b, a = 255) +static cell bhl_hud_slot_color(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + const char *key = MF_GetAmxString(amx, params[1], 0, nullptr); + int slot = params[2]; + + if (!sb->HudSetSlotColor(key, slot, params[3], params[4], params[5], params[6])) + return LogHudError(amx, __func__, key, "unknown element, slot %d out of range, or the element would exceed %d bytes", slot, bhl::sb::MAX_MSG_SIZE); + + return 1; +} + +// native bool:bhl_hud_event(player, const key[], variant, life_ms = 0, const sprite[] = "", const sprite_text[] = "", any:...) +static cell bhl_hud_event(AMX *amx, cell *params, bhl::IScoreboardExt *sb) +{ + constexpr int FIXED_PARAMS = 6; + + const char *key = MF_GetAmxString(amx, params[2], 0, nullptr); + const char *sprite = MF_GetAmxString(amx, params[5], 1, nullptr); + const char *spriteText = MF_GetAmxString(amx, params[6], 2, nullptr); + int player = params[1]; + int variant = params[3]; + int argCount = (int)(params[0] / sizeof(cell)) - FIXED_PARAMS; + int args[bhl::sb::MAX_EVENT_INTS] = {}; + + if (argCount > bhl::sb::MAX_EVENT_INTS) + return LogHudError(amx, __func__, key, "%d numbers, more than %d", argCount, bhl::sb::MAX_EVENT_INTS); + + // Variadic args are passed by reference + for (int i = 0; i < argCount; i++) + args[i] = *MF_GetAmxAddr(amx, params[FIXED_PARAMS + 1 + i]); + + if (!sb->HudEvent(player, key, variant, params[4], args, argCount, sprite, spriteText)) + return LogHudError(amx, __func__, key, "unknown element or not a feed, variant %d out of range, or player %d out of range or not connected", variant, player); + + return 1; +} + AMX_NATIVE_INFO bugfixedapi_Exports[] = { { "bhl_is_api_ready", bhl_is_api_ready }, { "bhl_get_server_version", bhl_get_server_version }, @@ -190,6 +475,34 @@ AMX_NATIVE_INFO bugfixedapi_Exports[] = { { "bhl_show_motd_from_string", bhl_show_motd_from_string }, { "bhl_show_motd_from_file", bhl_show_motd_from_file }, { "bhl_set_player_score", bhl_set_player_score }, + { "bhl_sb_team", ScoreboardNative<&bhl::IScoreboardExt::GetTeamTarget, -1> }, + { "bhl_get_client_caps", bhl_get_client_caps }, + { "bhl_sb_available", bhl_sb_available }, + { "bhl_sb_reset", ScoreboardNative<&bhl::IScoreboardExt::Reset> }, + { "bhl_sb_config", ScoreboardNative<&bhl::IScoreboardExt::SetConfig> }, + { "bhl_sb_add_column", ScoreboardNative<&bhl::IScoreboardExt::AddColumn> }, + { "bhl_sb_add_badge", ScoreboardNative<&bhl::IScoreboardExt::AddBadge> }, + { "bhl_sb_set_int", ScoreboardNative<&bhl::IScoreboardExt::SetInt> }, + { "bhl_sb_set_text", ScoreboardNative<&bhl::IScoreboardExt::SetText> }, + { "bhl_sb_set_icon", ScoreboardNative<&bhl::IScoreboardExt::SetIcon> }, + { "bhl_sb_set_progress", ScoreboardNative<&bhl::IScoreboardExt::SetProgress> }, + { "bhl_sb_set_clock", ScoreboardNative<&bhl::IScoreboardExt::SetClock> }, + { "bhl_sb_clear", ScoreboardNative<&bhl::IScoreboardExt::Clear> }, + { "bhl_sb_list_resize", ScoreboardNative<&bhl::IScoreboardExt::ListResize> }, + { "bhl_sb_list_set_int", ScoreboardNative<&bhl::IScoreboardExt::ListSetInt> }, + { "bhl_sb_list_set_text", ScoreboardNative<&bhl::IScoreboardExt::ListSetText> }, + { "bhl_sb_list_set_icon", ScoreboardNative<&bhl::IScoreboardExt::ListSetIcon> }, + { "bhl_hud_add", ScoreboardNative }, + { "bhl_hud_place", ScoreboardNative }, + { "bhl_hud_color", ScoreboardNative }, + { "bhl_hud_bind", ScoreboardNative }, + { "bhl_hud_param", ScoreboardNative }, + { "bhl_hud_text", ScoreboardNative }, + { "bhl_hud_show", ScoreboardNative }, + { "bhl_hud_remove", ScoreboardNative<&bhl::IScoreboardExt::HudRemove> }, + { "bhl_hud_hide_std", ScoreboardNative<&bhl::IScoreboardExt::HudHideStd> }, + { "bhl_hud_slot_color", ScoreboardNative }, + { "bhl_hud_event", ScoreboardNative }, { nullptr, nullptr } }; @@ -224,7 +537,7 @@ void OnAmxxAttach() bhl::GetServerApiVersion(major, minor); LOG_ERROR(PLID, "Interface version mismatch."); LOG_ERROR(PLID, "\tGot: %d.%d", major, minor); - LOG_ERROR(PLID, "\tRequired: %d.%d", IBUGFIXEDSERVER_MAJOR, IBUGFIXEDSERVER_MINOR); + LOG_ERROR(PLID, "\tRequired: %d.x", IBUGFIXEDSERVER_MAJOR); } // Print final message @@ -238,9 +551,43 @@ void OnAmxxAttach() LOG_MESSAGE(PLID, "Got IBugfixedServer from server library."); LOG_MESSAGE(PLID, "BugfixedAPI AMXX module loaded successfully."); + + if (!bhl::IsScoreboardApiReady()) + { + int major = 0, minor = 0; + bhl::GetServerApiVersion(major, minor); + LOG_MESSAGE(PLID, "Server API %d.%d doesn't support the scoreboard and HUD extension (requires %d.%d). bhl_sb_* and bhl_hud_* natives will not function.", major, minor, IBUGFIXEDSERVER_MAJOR, bhl::SCOREBOARD_API_MINOR); + } } void OnAmxxDetach() { bhl::ShutdownServerApi(); } + +void OnPluginsLoaded() +{ + g_iClientCapsChangedFwd = MF_RegisterForward("bhl_client_caps_changed", ET_IGNORE, FP_CELL, FP_DONE); + g_bScoreboardErrorLogged = false; +} + +void StartFrame() +{ + if (bhl::IsScoreboardApiReady()) + { + int maxClients = std::min(gpGlobals->maxClients, (int)ARRAYSIZE(g_ClientCaps) - 1); + for (int i = 1; i <= maxClients; i++) + { + bhl::E_ClientCaps caps = bhl::serverapi()->GetClientCaps(i); + if (caps == g_ClientCaps[i]) + continue; + + g_ClientCaps[i] = caps; + + if (MF_IsPlayerIngame(i)) + MF_ExecuteForward(g_iClientCapsChangedFwd, static_cast(i)); + } + } + + RETURN_META(MRES_IGNORED); +} diff --git a/src/bugfixedapi_amxx/moduleconfig.h b/src/bugfixedapi_amxx/moduleconfig.h index bb6dcb12..7180e289 100644 --- a/src/bugfixedapi_amxx/moduleconfig.h +++ b/src/bugfixedapi_amxx/moduleconfig.h @@ -84,7 +84,7 @@ /** All plugins loaded * Do forward functions init here (MF_RegisterForward) */ -//#define FN_AMXX_PLUGINSLOADED OnPluginsLoaded +#define FN_AMXX_PLUGINSLOADED OnPluginsLoaded /** All plugins are about to be unloaded */ //#define FN_AMXX_PLUGINSUNLOADING OnPluginsUnloading @@ -136,7 +136,7 @@ // #define FN_ServerDeactivate ServerDeactivate /* pfnServerDeactivate() (wd) Server is leaving the map (shutdown or changelevel); SDK2 */ // #define FN_PlayerPreThink PlayerPreThink /* pfnPlayerPreThink() */ // #define FN_PlayerPostThink PlayerPostThink /* pfnPlayerPostThink() */ -// #define FN_StartFrame StartFrame /* pfnStartFrame() */ +#define FN_StartFrame StartFrame /* pfnStartFrame() */ // #define FN_ParmsNewLevel ParmsNewLevel /* pfnParmsNewLevel() */ // #define FN_ParmsChangeLevel ParmsChangeLevel /* pfnParmsChangeLevel() */ // #define FN_GetGameDescription GetGameDescription /* pfnGetGameDescription() Returns string describing current .dll. E.g. "TeamFotrress 2" "Half-Life" */ diff --git a/src/game/client/CMakeLists.txt b/src/game/client/CMakeLists.txt index 91038f1e..d070ebe2 100644 --- a/src/game/client/CMakeLists.txt +++ b/src/game/client/CMakeLists.txt @@ -111,6 +111,8 @@ set( SOURCE_FILES hud/message.h hud/scores.cpp hud/scores.h + hud/server_panel.cpp + hud/server_panel.h hud/spectator.cpp hud/spectator.h hud/speedometer.cpp @@ -143,6 +145,8 @@ set( SOURCE_FILES vgui/crosshair_image.h vgui/score_panel.cpp vgui/score_panel.h + vgui/score_panel_cells.cpp + vgui/score_panel_cells.h vgui/spectator_panel.cpp vgui/spectator_panel.h vgui/team_menu.cpp @@ -222,6 +226,10 @@ set( SOURCE_FILES rainbow.h results.cpp results.h + scoreboard_data.cpp + scoreboard_data.h + scoreboard_template.cpp + scoreboard_template.h sdl_rt.cpp sdl_rt.h studio_util.cpp diff --git a/src/game/client/hud.cpp b/src/game/client/hud.cpp index 7aef31ea..62cb78c4 100644 --- a/src/game/client/hud.cpp +++ b/src/game/client/hud.cpp @@ -47,6 +47,7 @@ #include "sdl_rt.h" #include "fog.h" #include "engine_builds.h" +#include "scoreboard_data.h" #if USE_UPDATER #include "updater/update_checker.h" @@ -78,6 +79,7 @@ #include "hud/jumpspeed.h" #include "hud/timer.h" #include "hud/strafeguide.h" +#include "hud/server_panel.h" // Adrenaline Gamer HUD Elements #include "hud/ag/ag_countdown.h" @@ -143,6 +145,7 @@ ConVar showtriggers("showtriggers", "0", 0, "Shows trigger brushes"); ConVar aghl_version("aghl_version", APP_VERSION, 0, "BugfixedHL version"); ConVar aghl_supports("aghl_supports", "0", 0, "Bitfield of features supported by this client"); +ConVar bhl_caps_userinfo("_bhl", "3", FCVAR_USERINFO, "Bitfield of BugfixedHL client capabilities, set automatically"); ConVar cl_enable_html_motd("cl_enable_html_motd", "1", FCVAR_BHL_ARCHIVE, "Enables/disables support for HTML MOTDs"); ConVar zoom_sensitivity_ratio("zoom_sensitivity_ratio", "1.2", FCVAR_ARCHIVE | FCVAR_BHL_ARCHIVE); @@ -376,6 +379,7 @@ void CHud::Init(void) RegisterHudElem(); RegisterHudElem(); RegisterHudElem(); + RegisterHudElem(); if (CHudRenderer::Get().IsAvailable()) { @@ -409,6 +413,7 @@ void CHud::Init(void) bhlcfg::Init(); CResults::Get().Init(); + CScoreboardData::Get().Init(); #if USE_UPDATER CHttpClient::Get(); @@ -442,6 +447,7 @@ void CHud::VidInit(void) } CSvcMessages::Get().VidInit(); + CScoreboardData::Get().VidInit(); // ---------- // Load Sprites @@ -541,6 +547,22 @@ void CHud::VidInit(void) for (CHudElem *i : m_HudList) i->VidInit(); + + UpdateCapsUserinfo(); +} + +static int GetClientCaps() +{ + bhl::E_ClientCaps caps = bhl::E_ClientCaps::None; + + // HUD elements read the store, so they need the data too + if (CScoreboardData::IsCustomEnabled() || CScoreboardData::IsHudEnabled()) + SetEnumFlag(caps, bhl::E_ClientCaps::ScoreboardV1); + + if (CScoreboardData::IsHudEnabled()) + SetEnumFlag(caps, bhl::E_ClientCaps::HudV1); + + return static_cast(caps); } void CHud::Frame(double time) @@ -554,6 +576,7 @@ void CHud::Frame(double time) CHudVoiceStatus::Get()->RunFrame(time); CResults::Get().Frame(); + CScoreboardData::Get().Frame(); #if USE_UPDATER CHttpClient::Get().RunFrame(); @@ -568,6 +591,12 @@ void CHud::Frame(double time) UpdateSupportsCvar(); } + if (GetClientCaps() != m_iCaps || strcmp(bhl_caps_userinfo.GetString(), m_szCaps)) + UpdateCapsUserinfo(); + + if (m_iCapsCheckFrame != 0 && m_iFrameCount >= m_iCapsCheckFrame) + CheckCapsUserinfo(); + while (m_NextFrameQueue.size()) { auto &i = m_NextFrameQueue.front(); @@ -872,6 +901,54 @@ void CHud::UpdateSupportsCvar() gEngfuncs.pfnClientCmd(buf); } +void CHud::UpdateCapsUserinfo() +{ + int caps = GetClientCaps(); + + if (caps != m_iCaps) + { + m_iCaps = caps; + snprintf(m_szCaps, sizeof(m_szCaps), "%x", static_cast(caps)); + m_iCapsCheckFrame = 0; + m_bCapsCheckFailed = false; + } + + if (strcmp(bhl_caps_userinfo.GetString(), m_szCaps)) + bhl_caps_userinfo.SetValue(m_szCaps); + + CScoreboardData::Get().SetClientCaps(static_cast(caps)); + + if (!m_bCapsCheckFailed && m_iCapsCheckFrame == 0) + { + m_bCapsSetinfoSent = false; + m_iCapsCheckFrame = m_iFrameCount + 1; + } +} + +void CHud::CheckCapsUserinfo() +{ + m_iCapsCheckFrame = 0; + + if (!strcmp(gEngfuncs.LocalPlayerInfo_ValueForKey(bhl_caps_userinfo.GetName()), m_szCaps)) + return; + + if (!m_bCapsSetinfoSent) + { + char buf[64]; + snprintf(buf, sizeof(buf), "setinfo %s %s\n", bhl_caps_userinfo.GetName(), m_szCaps); + gEngfuncs.pfnClientCmd(buf); + m_bCapsSetinfoSent = true; + + // The command runs from the command buffer, give it a full frame + m_iCapsCheckFrame = m_iFrameCount + 2; + } + else + { + ConPrintf(ConColor::Red, "Failed to put %s into userinfo, it may be full. The server will query the cvar instead.\n", bhl_caps_userinfo.GetName()); + m_bCapsCheckFailed = true; + } +} + EHudScale CHud::DetectMaxHudScale() { const HudScaleInfo *pMaxScaleInfo = nullptr; diff --git a/src/game/client/hud.h b/src/game/client/hud.h index 48493ed0..bdd27e16 100644 --- a/src/game/client/hud.h +++ b/src/game/client/hud.h @@ -313,9 +313,24 @@ class CHud bool m_bIsHTMLEnabled = false; int m_iFrameCount = 0; + int m_iCaps = -1; //!< Client caps written to _bhl, -1 before the first update + char m_szCaps[16] = {}; //!< m_iCaps as written to _bhl + int m_iCapsCheckFrame = 0; //!< Frame of the next check of _bhl in userinfo, 0 if none is pending + bool m_bCapsSetinfoSent = false; + bool m_bCapsCheckFailed = false; //!< _bhl can't be put into userinfo, don't retry until the caps change + void UpdateHudColors(); void UpdateSupportsCvar(); + /** + * Computes the client caps, writes them to _bhl and passes them to the scoreboard store + * (docs/scoreboard-protocol.md, 3.2). Writes nothing when _bhl already holds them. + */ + void UpdateCapsUserinfo(); + + //! Compares _bhl in userinfo with the caps, retries once with setinfo + void CheckCapsUserinfo(); + //! Detects the maximum supported HUD scale. EHudScale DetectMaxHudScale(); diff --git a/src/game/client/hud/jumpspeed.cpp b/src/game/client/hud/jumpspeed.cpp index 635762d5..283692e9 100644 --- a/src/game/client/hud/jumpspeed.cpp +++ b/src/game/client/hud/jumpspeed.cpp @@ -3,6 +3,7 @@ #include "cl_util.h" #include "parsemsg.h" #include "jumpspeed.h" +#include "scoreboard_data.h" extern ConVar hud_speedometer; extern ConVar hud_speedometer_below_cross; @@ -29,6 +30,10 @@ void CHudJumpspeed::Draw(float flTime) if (!hud_jumpspeed.GetBool()) return; + // The server hides only the bottom position + if (!hud_jumpspeed_below_cross.GetBool() && CScoreboardData::Get().IsStdPartHidden(bhl::sb::E_HudStd::JumpSpeed)) + return; + if (m_iOldSpeed != m_iSpeed) m_fFade = FADE_TIME; diff --git a/src/game/client/hud/scores.cpp b/src/game/client/hud/scores.cpp index 9004cecf..55586a56 100644 --- a/src/game/client/hud/scores.cpp +++ b/src/game/client/hud/scores.cpp @@ -25,6 +25,7 @@ #include "scores.h" #include "vgui/client_viewport.h" #include "hud/ag/ag_global.h" +#include "scoreboard_data.h" ConVar hud_scores("hud_scores", "0", FCVAR_BHL_ARCHIVE, "Maximum number of lines for HUD scoreboard, 0 to disable"); ConVar hud_scores_pos("hud_scores_pos", "30 50", FCVAR_BHL_ARCHIVE, "Position of HUD scoreboard, 'x y' in pixels"); @@ -32,6 +33,16 @@ ConVar hud_scores_alpha("hud_scores_alpha", "20", FCVAR_BHL_ARCHIVE, "Alpha of H DEFINE_HUD_ELEM(CHudScores); +//! Formats a line with the value of the Primary column of the scoreboard extension instead of frags +static void FormatPrimaryLine(char *buf, int bufSize, const CScoreboardData::Value &value, const char *name) +{ + wchar_t wszValue[64]; + char szValue[128]; + value.ToString(wszValue, sizeof(wszValue)); + Q_WStringToUTF8(wszValue, szValue, sizeof(szValue), STRINGCONVERT_REPLACE); + snprintf(buf, bufSize, "%-5s %s", szValue, name); +} + void CHudScores::Init() { m_iFlags |= HUD_ACTIVE; @@ -89,6 +100,9 @@ void CHudScores::Update() int iMaxLines = hud_scores.GetInt(); m_iLines = 0; + const CScoreboardData &sbData = CScoreboardData::Get(); + int iPrimaryCol = sbData.IsActive() ? sbData.FindPrimaryColumn() : -1; + if (gHUD.m_Teamplay) { std::fill(m_TeamData.begin(), m_TeamData.end(), TeamData()); @@ -131,6 +145,10 @@ void CHudScores::Update() // Sort teams based on the score std::sort(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + iTeamCount, [&](int ilhs, int irhs) { + // The same full order as the scoreboard + if (iPrimaryCol != -1) + return sbData.CompareTeams(ilhs, irhs) < 0; + const TeamData &lhs = m_TeamData[ilhs]; const TeamData &rhs = m_TeamData[irhs]; @@ -157,7 +175,11 @@ void CHudScores::Update() TeamData &team = m_TeamData[teamIdx]; HudScoresData &data = m_ScoresData[m_iLines]; - snprintf(buf, sizeof(buf), "%-5i %s", team.iFrags, GetTeamInfo(teamIdx)->GetDisplayName()); + if (iPrimaryCol != -1) + FormatPrimaryLine(buf, sizeof(buf), sbData.GetTeamValue(teamIdx, iPrimaryCol), GetTeamInfo(teamIdx)->GetDisplayName()); + else + snprintf(buf, sizeof(buf), "%-5i %s", team.iFrags, GetTeamInfo(teamIdx)->GetDisplayName()); + Q_UTF8ToWString(buf, data.wszScore, sizeof(data.wszScore), STRINGCONVERT_REPLACE); data.color = g_pViewport->GetTeamColor(teamIdx); m_iLines++; @@ -180,6 +202,10 @@ void CHudScores::Update() // Sort players std::sort(m_SortedPlayerIDs.begin(), m_SortedPlayerIDs.begin() + iPlayerCount, [&](int ilhs, int irhs) { + // The same full order as the scoreboard + if (iPrimaryCol != -1) + return sbData.ComparePlayers(ilhs, irhs) < 0; + CPlayerInfo *lhs = GetPlayerInfo(ilhs); CPlayerInfo *rhs = GetPlayerInfo(irhs); @@ -206,7 +232,11 @@ void CHudScores::Update() CPlayerInfo *pi = GetPlayerInfo(idx); HudScoresData &data = m_ScoresData[m_iLines]; - snprintf(buf, sizeof(buf), "%-5i %s", pi->GetFrags(), pi->GetDisplayName()); + if (iPrimaryCol != -1) + FormatPrimaryLine(buf, sizeof(buf), sbData.GetPlayerValue(idx, iPrimaryCol), pi->GetDisplayName()); + else + snprintf(buf, sizeof(buf), "%-5i %s", pi->GetFrags(), pi->GetDisplayName()); + Q_UTF8ToWString(buf, data.wszScore, sizeof(data.wszScore), STRINGCONVERT_REPLACE); data.color = gHUD.GetClientColor(idx, NoTeamColor::Orange); m_iLines++; diff --git a/src/game/client/hud/server_panel.cpp b/src/game/client/hud/server_panel.cpp new file mode 100644 index 00000000..406269ec --- /dev/null +++ b/src/game/client/hud/server_panel.cpp @@ -0,0 +1,1755 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hud.h" +#include "hud_renderer.h" +#include "triangleapi.h" +#include "hud/server_panel.h" +#include "vgui/client_viewport.h" +#include "vgui/hud_ammo.h" +#include "vgui/hud_battery.h" +#include "vgui/hud_health.h" +#include "vgui/score_panel_cells.h" + +//---------------------------------------------------------------------------------------------------- +// Layout and effect math (docs/scoreboard-protocol.md, 8.4, 8.7, 8.8, 8.13-8.16). Pixels; sizes are already +// scaled with P(). Times are seconds, durations are the ms of the params. +//---------------------------------------------------------------------------------------------------- +namespace +{ + +//! Side zones of the numbers row in widths of a digit: offset 10, suit icon 2 and number 3 of the armor +constexpr int NUMBERS_ROW_DIGITS = 15; + +//! Length of a Meter bar in dots when the dots param is 0 +constexpr int METER_BAR_DOTS = 10; + +constexpr double PI = 3.14159265358979323846; + +//! FNV-1a of the content signature +constexpr unsigned int HASH_BASIS = 2166136261u; +constexpr unsigned int HASH_PRIME = 16777619u; + +struct Box +{ + int x = 0, y = 0; + int wide = 0, tall = 0; +}; + +//! Row of the HL health, armor and ammo numbers; the side zones add the gap of an element +struct NumbersRow +{ + int iTop = 0; + int iTall = 0; + int iLeft = 0; //!< Right edge of the health and armor numbers + int iRight = 0; //!< Left edge of the ammo numbers +}; + +//! Resolves the auto anchor by the position, as set_hudmessage does +int GetAnchor(int pos, int anchor) +{ + if (anchor != bhl::sb::ANCHOR_AUTO) + return anchor; + + if (pos == bhl::sb::POS_CENTER) + return bhl::sb::ANCHOR_CENTER; + + return pos < 0 ? bhl::sb::ANCHOR_END : bhl::sb::ANCHOR_START; +} + +//! Horizontal anchor of a placed box: the side of the box that stays when its width changes +int GetBoxAnchor(const CScoreboardData::Element &el) +{ + if (el.place == bhl::sb::E_Place::ParentLeft) + return bhl::sb::ANCHOR_END; + + if (el.place == bhl::sb::E_Place::ParentRight) + return bhl::sb::ANCHOR_START; + + return GetAnchor(el.x, el.hAlign); +} + +//! Start of a box on an axis: the reference point of the position with the box's anchor on it +int PlaceOnAxis(int pos, int anchor, int screenSize, int size) +{ + int ref; + + if (pos == bhl::sb::POS_CENTER) + ref = screenSize / 2; + else if (pos < 0) + ref = static_cast((1.0 + static_cast(pos) / bhl::sb::POS_SCALE) * screenSize); + else + ref = static_cast(static_cast(pos) / bhl::sb::POS_SCALE * screenSize); + + switch (GetAnchor(pos, anchor)) + { + case bhl::sb::ANCHOR_CENTER: + return ref - size / 2; + case bhl::sb::ANCHOR_END: + return ref - size; + default: + return ref; + } +} + +//! Moves a box inside the screen like set_hudmessage: the start wins if it doesn't fit +int MoveInside(int pos, int size, int screenSize) +{ + if (pos + size > screenSize) + pos = screenSize - size; + + return std::max(pos, 0); +} + +/** + * Places a box of box.wide x box.tall and moves it inside the screen. + * @param gap P(el.iGap) + * @param parent Placed box of the parent, used by the parent places + */ +void PlaceBox(const CScoreboardData::Element &el, int gap, const Box &parent, const NumbersRow &row, int screenWide, int screenTall, Box &box) +{ + switch (el.place) + { + case bhl::sb::E_Place::ParentLeft: + case bhl::sb::E_Place::ParentRight: + box.x = el.place == bhl::sb::E_Place::ParentLeft ? parent.x - gap - box.wide : parent.x + parent.wide + gap; + box.y = parent.y + (parent.tall - box.tall) / 2; + break; + case bhl::sb::E_Place::Parent: + box.x = PlaceOnAxis(el.x, el.hAlign, screenWide, box.wide); + box.y = el.vAlign == bhl::sb::ANCHOR_END ? parent.y - gap - box.tall : parent.y + parent.tall + gap; + break; + case bhl::sb::E_Place::NumbersRow: + { + // The zones are tested where the box will be drawn + box.x = MoveInside(PlaceOnAxis(el.x, el.hAlign, screenWide, box.wide), box.wide, screenWide); + bool lifted = box.x < row.iLeft + gap || box.x + box.wide > row.iRight - gap; + box.y = lifted ? row.iTop - gap - box.tall : row.iTop + (row.iTall - box.tall) / 2; + break; + } + default: + box.x = PlaceOnAxis(el.x, el.hAlign, screenWide, box.wide); + box.y = PlaceOnAxis(el.y, el.vAlign, screenTall, box.tall); + break; + } + + box.x = MoveInside(box.x, box.wide, screenWide); + box.y = MoveInside(box.y, box.tall, screenTall); +} + +/** + * Orders the elements parents first (8.4). Leaves out Boxes, which are never parents: they cover their group + * after the layout. Leaves out the unplaced ones too: undefined, banner places, and parent places whose parent + * is undefined, a Box, has a banner place, is the element itself, is in a cycle or is unplaced. + * @param order Receives the ids of the placed elements + * @return Number of placed elements + */ +int GetLayoutOrder(const CScoreboardData &data, int *order) +{ + bool placed[bhl::sb::MAX_ELEMENTS] = {}; + int count = 0; + + // Each pass places the elements whose parent is placed: a chain has at most MAX_ELEMENTS links + for (int pass = 0; pass < bhl::sb::MAX_ELEMENTS; pass++) + { + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const CScoreboardData::Element &el = data.GetElement(id); + bool hasParent = el.iParent >= 0 && el.iParent < bhl::sb::MAX_ELEMENTS && placed[el.iParent]; + + if (!placed[id] && el.bValid && el.kind != bhl::sb::E_ElementKind::Box && !bhl::sb::IsBannerPlace(el.place) && (!bhl::sb::IsParentPlace(el.place) || hasParent)) + { + placed[id] = true; + order[count++] = id; + } + } + } + + return count; +} + +/** + * Box of a track marker above a cell of a Strip (8.8): n discs for n = 1 or 2, else a text of textWide. + * @param gap P(2): between the discs, and between the marker and the cell + */ +Box LayoutTrackMarker(int cellX, int cellWide, int cellY, int n, int disc, int gap, int textWide, int textTall) +{ + Box box; + box.wide = n <= 2 ? n * disc + (n - 1) * gap : textWide; + box.tall = n <= 2 ? disc : textTall; + box.x = cellX + (cellWide - box.wide) / 2; + box.y = cellY - gap - box.tall; + return box; +} + +/** + * Rows of a Board (8.14) out of count in the order: board_mode 0 the first rows; 1 also the own row after + * a separator (-1) when it isn't among them; 2 a window around the own row, clamped to the ends. + * @param own Own row or -1 + * @param out Receives up to rows + 2 row numbers, -1 for the separator + * @return Number of rows written + */ +int SelectBoardRows(int count, int own, int rows, int mode, int *out) +{ + int shown = std::min(rows, count); + int first = 0; + int n = 0; + + if (mode == static_cast(bhl::sb::E_BoardMode::Window) && own >= 0) + first = std::clamp(own - shown / 2, 0, count - shown); + + for (int i = first; i < first + shown; i++) + out[n++] = i; + + if (mode == static_cast(bhl::sb::E_BoardMode::TopAndOwn) && own >= shown) + { + out[n++] = -1; + out[n++] = own; + } + + return n; +} + +/** + * Columns of a Board: separated by gap, with the icon column of iconWide (0 for none) and a gap before the last one. + * @param x Receives the offsets of the columns + * @return Width of a row + */ +int LayoutBoardColumns(int count, const int *wide, int iconWide, int gap, int *x, int &iconX) +{ + int pos = 0; + iconX = 0; + + for (int i = 0; i < count; i++) + { + if (i == count - 1 && iconWide > 0) + { + iconX = pos; + pos += iconWide + gap; + } + + x[i] = pos; + pos += wide[i] + (i < count - 1 ? gap : 0); + } + + return pos; +} + +/** + * Splits text at TAB characters into up to maxColumns NUL-terminated columns; later TABs become spaces. + * @return Number of columns, at least 1 + */ +int SplitColumns(wchar_t *text, int *starts, int maxColumns) +{ + int count = 1; + starts[0] = 0; + + for (int i = 0; text[i]; i++) + { + if (text[i] != L'\t') + continue; + + if (count < maxColumns) + { + text[i] = L'\0'; + starts[count++] = i + 1; + } + else + { + text[i] = L' '; + } + } + + return count; +} + +//! Length of count rows, cells or dots of size pixels with gap between them +int GetStackLength(int count, int size, int gap) +{ + return count > 0 ? count * size + (count - 1) * gap : 0; +} + +//! True if the parent chain of element id reaches root, id included. A Box ends the chain like an undefined element. +bool IsInGroup(const CScoreboardData &data, int id, int root) +{ + for (int i = 0; i < bhl::sb::MAX_ELEMENTS && id >= 0 && id < bhl::sb::MAX_ELEMENTS; i++) + { + const CScoreboardData::Element &el = data.GetElement(id); + + if (id == root) + return true; + + if (!el.bValid || el.kind == bhl::sb::E_ElementKind::Box || !bhl::sb::IsParentPlace(el.place)) + return false; + + id = el.iParent; + } + + return false; +} + +//! Adds a box to bounds (x0, y0, x1, y1); an empty box adds nothing +void AddToBounds(int *bounds, int x, int y, int wide, int tall) +{ + if (wide <= 0 || tall <= 0) + return; + + bounds[0] = std::min(bounds[0], x); + bounds[1] = std::min(bounds[1], y); + bounds[2] = std::max(bounds[2], x + wide); + bounds[3] = std::max(bounds[3], y + tall); +} + +/** + * fade_ms factor (8.13): from `from` toward 1 (fadeIn) or 0 at 1 / fadeMs per ms; without fade_ms 1 or 0 at once. + * @param elapsed Time since the direction was set + */ +float GetFadeFactor(float from, bool fadeIn, float elapsed, int fadeMs) +{ + if (fadeMs <= 0) + return fadeIn ? 1.0f : 0.0f; + + float step = std::max(elapsed, 0.0f) * 1000.0f / fadeMs; + return fadeIn ? std::min(from + step, 1.0f) : std::max(from - step, 0.0f); +} + +//! flash_ms factor: 1 (white) at the change, down to 0 over flashMs +float GetFlashFactor(float elapsed, int flashMs) +{ + if (flashMs <= 0 || elapsed < 0) + return 0.0f; + + return std::max(1.0f - elapsed * 1000.0f / flashMs, 0.0f); +} + +//! warn_pulse_ms factor of the alpha while warning: 1 at the start of the warning +float GetPulseFactor(float elapsed, int periodMs) +{ + if (periodMs <= 0) + return 1.0f; + + return 0.55f + 0.45f * static_cast(std::cos(2 * PI * elapsed * 1000.0 / periodMs)); +} + +//! Alpha of a Feed line (8.15): fades in over fadeMs from its start and out over the last fadeMs of its life +float GetLineAlpha(float age, float life, int fadeMs) +{ + if (age < 0 || age >= life) + return 0.0f; + + if (fadeMs <= 0) + return 1.0f; + + float fade = fadeMs / 1000.0f; + return std::min({ 1.0f, age / fade, (life - age) / fade }); +} + +/** + * The line an announcer Feed (queue 1) shows: lines in arrival order, each from max(arrival, end of the + * previous one) for its life. anchorSeq, anchorStart and anchorEnd keep the last started line (all 0 for none), + * so evicting older lines from the ring doesn't move the later ones: lines before it are skipped. + * @param lines In arrival order, iSeq growing + * @return Line index or -1; anchorStart is then its start + */ +int FindAnnouncerLine(const CScoreboardData::HudLine *const *lines, const float *life, int count, float now, int &anchorSeq, float &anchorStart, float &anchorEnd) +{ + float end = anchorEnd; + + for (int i = 0; i < count; i++) + { + if (lines[i]->iSeq < anchorSeq) + continue; + + float lineStart = lines[i]->iSeq == anchorSeq ? anchorStart : std::max(lines[i]->flTime, end); + end = lineStart + life[i]; + + if (lineStart > now) + break; + + anchorSeq = lines[i]->iSeq; + anchorStart = lineStart; + anchorEnd = end; + + if (now < end) + return i; + } + + return -1; +} + +unsigned int HashInt(unsigned int hash, int value) +{ + for (int i = 0; i < 4; i++) + hash = (hash ^ ((static_cast(value) >> (8 * i)) & 0xFF)) * HASH_PRIME; + + return hash; +} + +unsigned int HashText(unsigned int hash, const wchar_t *text) +{ + for (; *text; text++) + hash = HashInt(hash, static_cast(*text)); + + return HashInt(hash, 0); +} + +//---------------------------------------------------------------------------------------------------- +// Drawing helpers +//---------------------------------------------------------------------------------------------------- + +constexpr int CIRCLE_TEXTURE_SIZE = 64; + +constexpr wchar_t MARKER_LEFT[] = L"\u2039"; +constexpr wchar_t MARKER_RIGHT[] = L"\u203A"; +constexpr wchar_t BOARD_SEPARATOR = 0x2026; +constexpr wchar_t TRACK_FORMAT[] = L"\u00D7%d"; + +//! P(v): proportional units of a 640x480 screen to pixels +int Scaled(int value) +{ + return vgui2::scheme()->GetProportionalScaledValue(value); +} + +int GetTextWide(vgui2::HFont font, const wchar_t *text) +{ + int wide = 0, tall = 0; + vgui2::surface()->GetTextSize(font, text, wide, tall); + return wide; +} + +/** + * The numbers row in coordinates of a panel at originX, originY (8.4): the classic numbers, + * or the health, battery and ammo panels with hud_custom 1. + */ +NumbersRow GetNumbersRow(int originX, int originY, int screenWide, int screenTall) +{ + NumbersRow row; + + if (hud_custom.GetBool()) + { + int hx, hy, hw, ht, bx, by, bw, bt, ax, ay, aw, at; + g_pViewport->GetHealthPanel()->GetBounds(hx, hy, hw, ht); + g_pViewport->GetBatteryPanel()->GetBounds(bx, by, bw, bt); + g_pViewport->GetAmmoPanel()->GetBounds(ax, ay, aw, at); + + int top = std::min({ hy, by, ay }); + row.iTop = top - originY; + row.iTall = std::max({ hy + ht, by + bt, ay + at }) - top; + row.iLeft = std::max(hx + hw, bx + bw) - originX; + row.iRight = ax - originX; + return row; + } + + int digitWide = gHUD.GetSpriteRect(gHUD.m_HUD_number_0).GetWidth(); + row.iTall = gHUD.m_iFontHeight; + row.iTop = screenTall - row.iTall - row.iTall / 2; + row.iLeft = NUMBERS_ROW_DIGITS * digitWide; + row.iRight = screenWide - NUMBERS_ROW_DIGITS * digitWide; + return row; +} + +//! Creates a white anti-aliased disc or ring texture from columns [x0; x1) of the circle +int CreateCircleTexture(bool ring, int x0, int x1) +{ + constexpr float radius = CIRCLE_TEXTURE_SIZE / 2.0f; + constexpr float ringWidth = CIRCLE_TEXTURE_SIZE / 6.0f; + int wide = x1 - x0; + std::vector rgba(wide * CIRCLE_TEXTURE_SIZE * 4, 255); + + for (int y = 0; y < CIRCLE_TEXTURE_SIZE; y++) + { + for (int x = x0; x < x1; x++) + { + float dist = std::hypot(x + 0.5f - radius, y + 0.5f - radius); + float alpha = clamp(radius - dist, 0.0f, 1.0f); + + if (ring) + alpha *= clamp(dist - (radius - ringWidth), 0.0f, 1.0f); + + rgba[(y * wide + x - x0) * 4 + 3] = static_cast(alpha * 255); + } + } + + int id = vgui2::surface()->CreateNewTextureID(true); + vgui2::surface()->DrawSetTextureRGBA(id, rgba.data(), wide, CIRCLE_TEXTURE_SIZE, true, false); + return id; +} + +void DrawTexture(int id, int x, int y, int wide, int tall, Color color) +{ + vgui2::surface()->DrawSetTexture(id); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawTexturedRect(x, y, x + wide, y + tall); +} + +/** + * DrawScoreSprite for the panel. With OpenGL, CHudRenderer leaves blending off after a sprite, + * so it is turned back on as VGUI2 sets it for the shapes drawn after the sprite. + */ +void DrawPanelSprite(int sprite, int x, int y, int wide, int tall, Color color) +{ + DrawScoreSprite(sprite, x, y, wide, tall, color); + + if (CHudRenderer::Get().IsAvailable()) + gEngfuncs.pTriAPI->RenderMode(kRenderTransTexture); +} + +Color ToColor(const unsigned char *rgba) +{ + return Color(rgba[0], rgba[1], rgba[2], rgba[3]); +} + +Color FlashColor(Color color, float k) +{ + auto flash = [k](int value) { return k > 0 ? value + static_cast((255 - value) * k + 0.5f) : value; }; + return Color(flash(color.r()), flash(color.g()), flash(color.b()), color.a()); +} + +//! The sprite of name, looked up only when name isn't cachedName: failures are cached too +int GetCachedSprite(const char *name, char (&cachedName)[bhl::sb::MAX_TEXT_LEN + 1], int &cachedSprite) +{ + if (strcmp(cachedName, name)) + { + V_strcpy_safe(cachedName, name); + cachedSprite = GetScoreSpriteIndex(name); + } + + return cachedSprite; +} + +} + +DEFINE_HUD_ELEM(CHudServerPanel); + +CHudServerPanel::CHudServerPanel() + : vgui2::Panel(NULL, "HudServerPanel") +{ + SetParent(g_pViewport); + SetPaintBackgroundEnabled(true); + SetMouseInputEnabled(false); + SetKeyBoardInputEnabled(false); + SetVisible(false); + + for (const bhl::sb::ParamInfo &info : bhl::sb::PARAM_INFO) + m_iParamDefaults[static_cast(info.id)] = info.iDefault; +} + +void CHudServerPanel::Init() +{ + m_iFlags |= HUD_ACTIVE; +} + +void CHudServerPanel::VidInit() +{ + m_iStripSpriteSerial = -1; + ResetScoreSpriteFiles(); + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + m_szIconSprites[id][0] = '\0'; + m_Effects[id] = EffectState(); + + // The rows keep sprite indexes + m_States[id].bDrawn = false; + m_pRows[id].reset(); + m_pGhostRows[id].reset(); + } +} + +void CHudServerPanel::Think() +{ + bool visible = UpdateLayout(); + + if (IsVisible() != visible) + { + SetVisible(visible); + + if (visible) + m_iFlags &= ~HUD_ACTIVE; // Think is called from VGUI while the panel is visible + else + m_iFlags |= HUD_ACTIVE; // Think from HUD to update visibility + } +} + +void CHudServerPanel::ApplySchemeSettings(vgui2::IScheme *pScheme) +{ + BaseClass::ApplySchemeSettings(pScheme); + + for (int i = 0; i < bhl::sb::FONT_COUNT; i++) + m_Fonts[i] = pScheme->GetFont(bhl::sb::FONT_NAMES[i], IsProportional()); +} + +void CHudServerPanel::ApplySettings(KeyValues *inResourceData) +{ + BaseClass::ApplySettings(inResourceData); + + for (const bhl::sb::ParamInfo &info : bhl::sb::PARAM_INFO) + m_iParamDefaults[static_cast(info.id)] = clamp(inResourceData->GetInt(info.pszName, info.iDefault), info.iMin, info.iMax); +} + +bool CHudServerPanel::UpdateLayout() +{ + for (ElementState &state : m_States) + state.bDrawn = false; + + float time = CScoreboardData::GetTime(); + + // No flash for what a Reset or full sync changes, and the announcers start over + if (m_iResetCount != m_Data.GetResetCount()) + { + m_iResetCount = m_Data.GetResetCount(); + + for (EffectState &fx : m_Effects) + { + fx.bHasSignature = false; + fx.anchor = AnnouncerAnchor(); + } + } + + if (!CScoreboardData::IsHudEnabled() || hud_draw.GetFloat() <= 0 || gHUD.m_iIntermission || (gHUD.m_iHideHUDDisplay & HIDEHUD_ALL)) + { + StopEffects(true); + return false; + } + + if (m_Data.GetVisibleMask() == 0 && !IsFading()) + { + StopEffects(false); + return false; + } + + UpdateStripSprites(); + SaveGhosts(); + + bool isParent[bhl::sb::MAX_ELEMENTS] = {}; + bool isPresent[bhl::sb::MAX_ELEMENTS] = {}; + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const CScoreboardData::Element &el = m_Data.GetElement(id); + + if (el.bValid && bhl::sb::IsParentPlace(el.place) && el.iParent >= 0 && el.iParent < bhl::sb::MAX_ELEMENTS) + isParent[el.iParent] = true; + } + + int order[bhl::sb::MAX_ELEMENTS]; + int count = GetLayoutOrder(m_Data, order); + int originX, originY, screenWide, screenTall; + GetBounds(originX, originY, screenWide, screenTall); + + NumbersRow row = GetNumbersRow(originX, originY, screenWide, screenTall); + bool isScoreboardOpen = g_pViewport->IsScoreBoardVisible(); + + for (int i = 0; i < count; i++) + { + int id = order[i]; + const CScoreboardData::Element &el = m_Data.GetElement(id); + ElementState &state = m_States[id]; + CScoreboardData::Subject subject; + + // The subject is needed even when the element is hidden: a parent's box counts anyway + bool hasSubject = m_Data.GetElementSubject(id, subject); + bool isShown = hasSubject && m_Data.IsElementVisible(id) && !(el.HasFlag(bhl::sb::E_ElementFlags::NoScoreboard) && isScoreboardOpen); + + if (!isShown && !isParent[id]) + continue; + + int gap = Scaled(el.iGap); + int freeWide = el.place == bhl::sb::E_Place::NumbersRow ? (row.iRight - gap) - (row.iLeft + gap) : INT_MAX; + bool hasContent = MeasureElement(id, el, subject, freeWide, state); + + // Only the parent places read the parent's box + const ElementState &parent = bhl::sb::IsParentPlace(el.place) ? m_States[el.iParent] : state; + Box box = { 0, 0, state.wide, state.tall }; + PlaceBox(el, gap, { parent.x, parent.y, parent.wide, parent.tall }, row, screenWide, screenTall, box); + + state.x = box.x; + state.y = box.y; + isPresent[id] = isShown && hasContent; + PlaceContent(el, state); + } + + bool isAnyDrawn = false; + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const CScoreboardData::Element &el = m_Data.GetElement(id); + + if (el.kind != bhl::sb::E_ElementKind::Box && UpdateEffects(id, el, isPresent[id], time)) + isAnyDrawn = true; + } + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const CScoreboardData::Element &el = m_Data.GetElement(id); + + if (el.kind != bhl::sb::E_ElementKind::Box) + continue; + + // The group: what the elements under the root draw, ghosts that fade out included + int bounds[4] = { INT_MAX, INT_MAX, INT_MIN, INT_MIN }; + float groupFade = 0; + + for (int member = 0; member < bhl::sb::MAX_ELEMENTS; member++) + { + const ElementState &memberState = m_States[member]; + + if (!memberState.bDrawn || memberState.kind == bhl::sb::E_ElementKind::Box || !IsInGroup(m_Data, member, el.iParent)) + continue; + + AddDrawnBounds(member, memberState, bounds); + groupFade = std::max(groupFade, m_Effects[member].flFade); + } + + // Placed when its root is + ElementState &state = m_States[id]; + CScoreboardData::Subject subject; + bool isPlaced = bhl::sb::IsParentPlace(el.place) && std::find(order, order + count, el.iParent) != order + count; + bool isPresentBox = isPlaced && m_Data.GetElementSubject(id, subject) && m_Data.IsElementVisible(id) + && !(el.HasFlag(bhl::sb::E_ElementFlags::NoScoreboard) && isScoreboardOpen) && bounds[0] < bounds[2]; + + if (isPresentBox) + { + int pad = Scaled(el.iGap); + MeasureElement(id, el, subject, INT_MAX, state); + state.x = bounds[0] - pad; + state.y = bounds[1] - pad; + state.wide = bounds[2] - bounds[0] + 2 * pad; + state.tall = bounds[3] - bounds[1] + 2 * pad; + } + + if (UpdateEffects(id, el, isPresentBox, time)) + { + state.flAlpha *= groupFade; + isAnyDrawn = true; + } + } + + return isAnyDrawn; +} + +bool CHudServerPanel::MeasureElement(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, int freeWide, ElementState &state) +{ + int font = static_cast(el.font); + Color rgb = el.HasFlag(bhl::sb::E_ElementFlags::HudColor) ? gHUD.GetHudColor(HudPart::Common, 0) : Color(el.r, el.g, el.b, 255); + + state = ElementState(); + state.kind = el.kind; + state.font = m_Fonts[font < bhl::sb::FONT_COUNT ? font : 0]; + state.iFontTall = vgui2::surface()->GetFontTall(state.font); + state.color = Color(rgb.r(), rgb.g(), rgb.b(), el.a); + state.tall = state.iFontTall; + + switch (el.kind) + { + case bhl::sb::E_ElementKind::Text: + state.iTextWide = m_Data.GetElementText(id, subject, state.wszText, sizeof(state.wszText)) ? GetTextWide(state.font, state.wszText) : 0; + state.wide = state.iTextWide; + return state.wszText[0] != L'\0'; + case bhl::sb::E_ElementKind::Meter: + return MeasureMeter(id, el, subject, state); + case bhl::sb::E_ElementKind::Strip: + return MeasureStrip(id, el, subject, freeWide, state); + case bhl::sb::E_ElementKind::Icon: + return MeasureIcon(id, el, subject, state); + case bhl::sb::E_ElementKind::Board: + return MeasureBoard(id, el, subject, state); + case bhl::sb::E_ElementKind::Feed: + return MeasureFeed(id, el, state); + default: + return false; + } +} + +bool CHudServerPanel::MeasureMeter(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state) +{ + CScoreboardData::Value value; + int dot = std::max(2, Scaled(GetParam(el, bhl::sb::E_Param::DotSize))); + state.tall = dot; + + if (!m_Data.GetElementValue(id, subject, value) || value.type != bhl::sb::E_ValueType::Progress || value.iMax <= 0) + return false; + + state.iMax = value.iMax; + state.iCur = clamp(value.iValue, 0, value.iMax); + state.iDotGap = Scaled(GetParam(el, bhl::sb::E_Param::DotGap)); + + int dots = GetParam(el, bhl::sb::E_Param::Dots); + int barDots = dots > 0 ? dots : METER_BAR_DOTS; + int barWide = Scaled(GetParam(el, bhl::sb::E_Param::BarWide)); + state.bDots = dots > 0 && state.iMax <= dots; + state.wide = !state.bDots && barWide > 0 ? barWide : GetStackLength(state.bDots ? state.iMax : barDots, dot, state.iDotGap); + state.iFillWide = state.iCur > 0 ? std::max(static_cast(static_cast(state.wide) * state.iCur / state.iMax), dot) : 0; + + // Form 1 (8.7): dots on a circle, a dot per unit while max fits the dots, else barDots of them filled to round(cur * barDots / max) + if (GetParam(el, bhl::sb::E_Param::Form) == static_cast(bhl::sb::E_MeterForm::Ring)) + { + state.bRing = true; + state.iDotSize = dot; + state.iRingDots = state.iMax <= dots ? state.iMax : barDots; + state.bDots = state.iRingDots == state.iMax; + state.iRingFilled = state.bDots ? state.iCur : static_cast((2LL * state.iCur * state.iRingDots + state.iMax) / (2LL * state.iMax)); + state.wide = std::max(3 * dot, static_cast(std::ceil(state.iRingDots * (dot + state.iDotGap) / PI)) + dot); + state.tall = state.wide; + } + + int counter = GetParam(el, bhl::sb::E_Param::Counter); + + if (counter == 2 || (counter == 1 && !state.bDots)) + state.iTextWide = m_Data.GetElementText(id, subject, state.wszText, sizeof(state.wszText)) ? GetTextWide(state.font, state.wszText) : 0; + + return true; +} + +bool CHudServerPanel::MeasureStrip(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, int freeWide, ElementState &state) +{ + const CScoreboardData::List *list = el.szList[0] ? m_Data.FindList(el.szList) : nullptr; + CScoreboardData::Value value; + bool hasValue = m_Data.GetElementValue(id, subject, value); + int count = 0; + + // A list key without such a list counts as no list (8.8) + if (list) + count = list->iCount; + else if (hasValue && value.type == bhl::sb::E_ValueType::Progress) + count = value.iMax; + + count = clamp(count, 0, bhl::sb::MAX_LIST_ITEMS); + + int position = 0; + bool hasPosition = hasValue && value.GetNumber(position); + + state.iMax = count; + state.iCellGap = Scaled(GetParam(el, bhl::sb::E_Param::CellGap)); + state.tall = Scaled(GetParam(el, bhl::sb::E_Param::CellTall)); + + // Without cells the strip has no width + if (count == 0) + return false; + + state.iCur = clamp(position, 1, count) - 1; + + int cellWide = GetParam(el, bhl::sb::E_Param::CellWide); + int cellMin = std::max(1, Scaled(std::min(GetParam(el, bhl::sb::E_Param::CellMinWide), cellWide))); + int cellMax = std::max(cellMin, Scaled(cellWide)); + int maxWide = GetParam(el, bhl::sb::E_Param::MaxWide); + int limit = maxWide > 0 ? Scaled(maxWide) : GetWide(); + int minWide = count * cellMin + (count - 1) * state.iCellGap; + + // On the numbers row the strip fits between the side zones unless it is lifted above them + if (el.place == bhl::sb::E_Place::NumbersRow && !(minWide > freeWide && freeWide < limit)) + limit = std::min(limit, freeWide); + + state.iCellWide = std::clamp((limit - (count - 1) * state.iCellGap) / count, cellMin, cellMax); + state.iShown = count; + + if (minWide > limit) + { + int marker = vgui2::surface()->GetCharacterWidth(state.font, MARKER_LEFT[0]) + state.iCellGap; + state.iShown = std::clamp((limit - 2 * marker + state.iCellGap) / std::max(cellMin + state.iCellGap, 1), 1, count); + state.iFirst = std::clamp(state.iCur - state.iShown / 2, 0, count - state.iShown); + } + + state.wide = GetStackLength(state.iShown, state.iCellWide, state.iCellGap); + state.bTrack = GetParam(el, bhl::sb::E_Param::Track) == 1; + + if (state.bTrack) + UpdateTrack(id, subject, count); + + return hasPosition; +} + +bool CHudServerPanel::MeasureIcon(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state) +{ + CScoreboardData::Value value; + + // Without an Icon value the element has no content, not even its text (8.3, 8.9) + if (!m_Data.GetElementValue(id, subject, value) || value.type != bhl::sb::E_ValueType::Icon) + return false; + + int iconTall = GetParam(el, bhl::sb::E_Param::IconTall); + int tall = iconTall > 0 ? Scaled(iconTall) : state.iFontTall; + int sprite = value.szSprite[0] ? GetCachedSprite(value.szSprite, m_szIconSprites[id], m_iIconSprites[id]) : -1; + const wrect_t &rc = GetScoreSpriteRect(sprite); + + if (rc.GetWidth() > 0 && rc.GetHeight() > 0 && tall > 0) + { + state.iSprite = sprite; + state.iIconWide = rc.GetWidth() * tall / rc.GetHeight(); + state.iIconTall = tall; + } + + state.iTextWide = m_Data.GetElementText(id, subject, state.wszText, sizeof(state.wszText)) ? GetTextWide(state.font, state.wszText) : 0; + + int gap = state.iSprite != -1 && state.wszText[0] ? Scaled(GetParam(el, bhl::sb::E_Param::IconGap)) : 0; + state.wide = state.iIconWide + gap + state.iTextWide; + state.tall = std::max(state.iIconTall, state.iFontTall); + return state.iSprite != -1 || state.wszText[0]; +} + +bool CHudServerPanel::MeasureBoard(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state) +{ + bool isList = el.szList[0] != '\0'; + const CScoreboardData::List *list = isList ? m_Data.FindList(el.szList) : nullptr; + + // In list mode @value is the item of the list named by the value ref + bool hasValueList = isList && el.valueRef.builtin == bhl::sb::E_Builtin::None && el.valueRef.szKey[0]; + const CScoreboardData::List *values = hasValueList ? m_Data.FindList(el.valueRef.szKey) : nullptr; + + CScoreboardData::Subject entities[MAX_PLAYERS]; + int count = 0; + int own = -1; + + if (isList) + { + CScoreboardData::Value select; + int number = 0; + count = list ? list->iCount : 0; + + if (subject.IsValid() && m_Data.GetRefValue(el.selectRef, subject, id, select) && select.GetNumber(number) && number >= 1 && number <= count) + own = number - 1; + } + else + { + count = m_Data.GetOrderedEntities(entities, MAX_PLAYERS); + const CScoreboardData::Subject *found = std::find(entities, entities + count, m_Data.GetRankedEntity(subject)); + own = subject.IsValid() && found != entities + count ? static_cast(found - entities) : -1; + } + + RowsState &rows = GetRows(id); + int picked[MAX_ROWS]; + int maxRows = std::min(GetParam(el, bhl::sb::E_Param::Rows), MAX_ROWS - 2); + rows.iCount = SelectBoardRows(count, own, maxRows, GetParam(el, bhl::sb::E_Param::BoardMode), picked); + rows.iOwn = -1; + rows.iColumns = 1; + rows.iStep = state.iFontTall + Scaled(GetParam(el, bhl::sb::E_Param::RowGap)); + + if (rows.iCount == 0) + return false; + + const bhl::sb::CTemplate *templates[2] = { m_Data.GetTemplate(id, 0), m_Data.GetTemplate(id, 1) }; + CScoreboardData::Value fills[MAX_ROWS]; + int maxInt = 0; + rows.iIconWide = 0; + std::fill(std::begin(rows.iColumnWide), std::end(rows.iColumnWide), 0); + std::fill(std::begin(rows.bColumnRight), std::end(rows.bColumnRight), true); + + for (int i = 0; i < rows.iCount; i++) + { + RowState &row = rows.rows[i]; + int index = picked[i]; + row.iVariant = 0; + row.iSprite = -1; + row.iIconWide = 0; + + if (index < 0) + { + row.wszText[0] = BOARD_SEPARATOR; + row.wszText[1] = L'\0'; + row.iColumns = 1; + row.iColumnStart[0] = 0; + row.iColumnWide[0] = GetTextWide(state.font, row.wszText); + rows.iColumnWide[0] = std::max(rows.iColumnWide[0], row.iColumnWide[0]); + continue; + } + + if (index == own) + { + rows.iOwn = i; + row.iVariant = templates[1] ? 1 : 0; + } + + CScoreboardData::Subject rowSubject = isList ? subject : entities[index]; + CScoreboardData::TemplateExtras extras; + extras.iIndex = index + 1; + + if (isList) + extras.pItem = &list->items[index]; + + if (hasValueList) + { + if (values && index < values->iCount) + fills[i] = values->items[index]; + + CScoreboardData::FormatValue(el.valueRef.format, fills[i]); + extras.pValue = &fills[i]; + } + else + { + m_Data.GetElementValue(id, rowSubject, fills[i]); + } + + row.wszText[0] = L'\0'; + + if (templates[row.iVariant]) + m_Data.EvaluateTemplate(*templates[row.iVariant], rowSubject, id, row.wszText, sizeof(row.wszText), &extras); + + row.iColumns = SplitColumns(row.wszText, row.iColumnStart, MAX_ROW_COLUMNS); + rows.iColumns = std::max(rows.iColumns, row.iColumns); + + for (int c = 0; c < row.iColumns; c++) + { + const wchar_t *text = row.wszText + row.iColumnStart[c]; + row.iColumnWide[c] = GetTextWide(state.font, text); + rows.iColumnWide[c] = std::max(rows.iColumnWide[c], row.iColumnWide[c]); + + // Only digits, spaces and + - . , / : % make a right-aligned column + rows.bColumnRight[c] = rows.bColumnRight[c] && wcsspn(text, L"0123456789 +-.,/:%") == wcslen(text); + } + + const CScoreboardData::Value &icon = isList ? list->items[index] : fills[i]; + + if (icon.type == bhl::sb::E_ValueType::Icon && icon.szSprite[0]) + { + SetRowIcon(row, icon.szSprite, state.iFontTall); + rows.iIconWide = std::max(rows.iIconWide, row.iIconWide); + } + + if (fills[i].type == bhl::sb::E_ValueType::Int) + maxInt = std::max(maxInt, fills[i].iValue); + } + + // fill_alpha bars: cur / max of a Progress, an Int over the largest Int of the rows + for (int i = 0; i < rows.iCount; i++) + { + const CScoreboardData::Value &value = fills[i]; + int maxValue = value.type == bhl::sb::E_ValueType::Progress ? value.iMax : (value.type == bhl::sb::E_ValueType::Int ? maxInt : 0); + rows.rows[i].flFill = value.iValue > 0 && maxValue > 0 ? std::min(static_cast(value.iValue) / maxValue, 1.0f) : 0.0f; + } + + state.wide = LayoutBoardColumns(rows.iColumns, rows.iColumnWide, rows.iIconWide, Scaled(GetParam(el, bhl::sb::E_Param::ColumnGap)), rows.iColumnX, rows.iIconX); + state.tall = GetStackLength(rows.iCount, state.iFontTall, rows.iStep - state.iFontTall); + return true; +} + +bool CHudServerPanel::MeasureFeed(int id, const CScoreboardData::Element &el, ElementState &state) +{ + const CScoreboardData::HudLine *lines[CScoreboardData::MAX_HUD_LINES]; + float lives[CScoreboardData::MAX_HUD_LINES]; + int count = m_Data.GetHudLines(id, lines); + float time = CScoreboardData::GetTime(); + float life = GetParam(el, bhl::sb::E_Param::LifeMs) / 1000.0f; + int fadeMs = GetParam(el, bhl::sb::E_Param::LineFadeMs); + + for (int i = 0; i < count; i++) + lives[i] = lines[i]->flLife > 0 ? lines[i]->flLife : life; + + int picked[MAX_ROWS]; + float alphas[MAX_ROWS]; + int shown = 0; + + if (GetParam(el, bhl::sb::E_Param::Queue) == 1) + { + AnnouncerAnchor &anchor = m_Effects[id].anchor; + int line = FindAnnouncerLine(lines, lives, count, time, anchor.iSeq, anchor.flStart, anchor.flEnd); + + if (line >= 0) + { + picked[shown] = line; + alphas[shown++] = GetLineAlpha(time - anchor.flStart, lives[line], fadeMs); + } + } + else + { + int maxLines = std::min(GetParam(el, bhl::sb::E_Param::Lines), MAX_ROWS); + + for (int i = count - 1; i >= 0 && shown < maxLines; i--) + { + float age = time - lines[i]->flTime; + + if (age < lives[i]) + { + picked[shown] = i; + alphas[shown++] = GetLineAlpha(age, lives[i], fadeMs); + } + } + } + + if (shown == 0) + return false; + + RowsState &rows = GetRows(id); + int iconGap = Scaled(4); + rows.iCount = shown; + rows.iStep = state.iFontTall + Scaled(GetParam(el, bhl::sb::E_Param::LineGap)); + + for (int i = 0; i < shown; i++) + { + const CScoreboardData::HudLine &line = *lines[picked[i]]; + RowState &row = rows.rows[i]; + memcpy(row.wszText, line.wszText, sizeof(row.wszText)); + row.iVariant = line.iVariant; + row.flAlpha = alphas[i]; + SetRowIcon(row, line.icon.szSprite, state.iFontTall); + + int textWide = GetTextWide(state.font, row.wszText); + row.iTextX = row.iIconWide > 0 && textWide > 0 ? row.iIconWide + iconGap : row.iIconWide; + row.iWide = row.iTextX + textWide; + state.wide = std::max(state.wide, row.iWide); + } + + state.tall = GetStackLength(shown, state.iFontTall, rows.iStep - state.iFontTall); + return true; +} + +void CHudServerPanel::PlaceContent(const CScoreboardData::Element &el, ElementState &state) +{ + state.iTextX = state.x; + state.iTextY = state.y + (state.tall - state.iFontTall) / 2; + state.iAnchor = GetBoxAnchor(el); + + if (state.bRing) + { + state.iTextX = state.x + (state.wide - state.iTextWide) / 2; + } + else if (el.kind == bhl::sb::E_ElementKind::Meter) + { + // The counter stands outside the box, so the anchored edge of the box stays in place + int gap = Scaled(GetParam(el, bhl::sb::E_Param::CounterGap)); + state.iTextX = state.iAnchor == bhl::sb::ANCHOR_END ? state.x - gap - state.iTextWide : state.x + state.wide + gap; + } + else if (el.kind == bhl::sb::E_ElementKind::Icon && state.iSprite != -1) + { + state.iTextX = state.x + state.iIconWide + Scaled(GetParam(el, bhl::sb::E_Param::IconGap)); + } +} + +void CHudServerPanel::UpdateStripSprites() +{ + if (m_iStripSpriteSerial == m_Data.GetSerial()) + return; + + m_iStripSpriteSerial = m_Data.GetSerial(); + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const CScoreboardData::Element &el = m_Data.GetElement(id); + const CScoreboardData::List *list = el.bValid && el.kind == bhl::sb::E_ElementKind::Strip && el.szList[0] ? m_Data.FindList(el.szList) : nullptr; + + for (int i = 0; i < bhl::sb::MAX_LIST_ITEMS; i++) + { + const CScoreboardData::Value *item = list && i < list->iCount ? &list->items[i] : nullptr; + bool hasIcon = item && item->type == bhl::sb::E_ValueType::Icon && item->szSprite[0]; + m_iStripSprites[id][i] = hasIcon ? GetScoreSpriteIndex(item->szSprite) : -1; + } + } +} + +void CHudServerPanel::SetRowIcon(RowState &row, const char *sprite, int tall) +{ + const wrect_t &rc = GetScoreSpriteRect(GetCachedSprite(sprite, row.szSpriteName, row.iSpriteOfName)); + bool isValid = rc.GetWidth() > 0 && rc.GetHeight() > 0; + row.iSprite = isValid ? row.iSpriteOfName : -1; + row.iIconWide = isValid ? rc.GetWidth() * tall / rc.GetHeight() : 0; +} + +void CHudServerPanel::UpdateTrack(int id, const CScoreboardData::Subject &subject, int count) +{ + unsigned char *counts = m_iTrackCounts[id]; + std::fill(counts, counts + bhl::sb::MAX_LIST_ITEMS, 0); + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CScoreboardData::Subject player = { i, 0 }; + CScoreboardData::Value value; + int position = 0; + + if (i == subject.iPlayer || !CScoreboardData::IsParticipant(i) || !m_Data.GetElementValue(id, player, value) || !value.GetNumber(position)) + continue; + + counts[clamp(position, 1, count) - 1]++; + } +} + +CHudServerPanel::RowsState &CHudServerPanel::GetRows(int id) +{ + if (!m_pRows[id]) + m_pRows[id] = std::make_unique(); + + return *m_pRows[id]; +} + +int CHudServerPanel::GetParam(const CScoreboardData::Element &el, bhl::sb::E_Param param) const +{ + int value = m_iParamDefaults[static_cast(param)]; + el.GetParam(param, value); + return value; +} + +void CHudServerPanel::SaveGhosts() +{ + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + EffectState &fx = m_Effects[id]; + + if (!fx.bDrawn || fx.iFadeMs <= 0) + continue; + + if (!m_pGhosts[id]) + m_pGhosts[id] = std::make_unique(); + + *m_pGhosts[id] = m_States[id]; + fx.bHasGhost = true; + + if (fx.kind == bhl::sb::E_ElementKind::Board || fx.kind == bhl::sb::E_ElementKind::Feed) + { + if (!m_pGhostRows[id]) + m_pGhostRows[id] = std::make_unique(); + + std::swap(m_pRows[id], m_pGhostRows[id]); + } + } +} + +void CHudServerPanel::StopEffects(bool keepPresence) +{ + for (EffectState &fx : m_Effects) + { + fx.bDrawn = false; + fx.flFadeFrom = 0; + fx.flFade = 0; + + if (!keepPresence) + fx.bPresent = false; + } +} + +bool CHudServerPanel::IsFading() const +{ + for (const EffectState &fx : m_Effects) + { + if (fx.iFadeMs > 0 && (fx.bDrawn || fx.flFade > 0)) + return true; + } + + return false; +} + +bool CHudServerPanel::UpdateEffects(int id, const CScoreboardData::Element &el, bool present, float time) +{ + EffectState &fx = m_Effects[id]; + ElementState &state = m_States[id]; + int removals = m_Data.GetElementRemovals(id); + + // Removal and redefinition with another kind are instant: the old element doesn't fade out + if (fx.kind != el.kind || fx.iRemovals != removals) + { + fx = EffectState(); + fx.kind = el.kind; + fx.iRemovals = removals; + } + + if (!el.bValid) + return false; + + CScoreboardData::Subject subject; + m_Data.GetElementSubject(id, subject); + + if (fx.subject != subject) + { + fx.subject = subject; + fx.bPresent = false; + fx.bHasSignature = false; + fx.flFlashTime = NEVER; + } + + int flashMs = GetParam(el, bhl::sb::E_Param::FlashMs); + int holdMs = GetParam(el, bhl::sb::E_Param::HoldMs); + bool appeared = present && !fx.bPresent; + fx.bPresent = present; + + if (appeared) + { + fx.flHoldTime = time; + fx.flFlashTime = NEVER; + fx.bWarn = false; + } + + if (present && (flashMs > 0 || holdMs > 0)) + { + unsigned int signature = GetSignature(id, subject, state); + + // A change while hidden is no flash: the element appears with it + if (fx.bHasSignature && signature != fx.iSignature && !appeared) + { + fx.flHoldTime = time; + fx.flFlashTime = fx.bDrawn ? time : NEVER; + } + + fx.iSignature = signature; + fx.bHasSignature = true; + } + + if (present) + { + int warnAt = GetParam(el, bhl::sb::E_Param::WarnAt); + CScoreboardData::Value value; + int number = 0; + bool warn = warnAt > 0 && m_Data.GetElementValue(id, subject, value) && value.GetNumber(number) && number <= warnAt; + + if (warn && !fx.bWarn) + fx.flWarnTime = time; + + fx.bWarn = warn; + } + + // hold_ms: drawn that long after the appearance or a change; always without it + bool drawn = present && (holdMs <= 0 || (time - fx.flHoldTime) * 1000.0f < holdMs); + + if (drawn != fx.bDrawn) + { + fx.flFadeFrom = GetFadeFactor(fx.flFadeFrom, fx.bDrawn, time - fx.flFadeTime, fx.iFadeMs); + fx.flFadeTime = time; + } + + fx.iFadeMs = GetParam(el, bhl::sb::E_Param::FadeMs); + fx.flFade = GetFadeFactor(fx.flFadeFrom, drawn, time - fx.flFadeTime, fx.iFadeMs); + fx.bDrawn = drawn; + + if (drawn) + { + // Color order (8.13): element color, variant slot, warn, flash + unsigned char rgba[4]; + + if (el.GetSlotColor(m_Data.GetElementVariant(id, subject), rgba)) + state.color = ToColor(rgba); + + if (fx.bWarn) + state.color = el.GetSlotColor(bhl::sb::SLOT_WARN, rgba) ? ToColor(rgba) : ToColor(bhl::sb::DEFAULT_WARN_COLOR); + + state.bWarn = fx.bWarn; + state.flFlash = GetFlashFactor(time - fx.flFlashTime, flashMs); + state.color = FlashColor(state.color, state.flFlash); + } + else if (fx.flFade > 0 && fx.bHasGhost) + { + state = *m_pGhosts[id]; + state.bGhost = true; + } + else + { + return false; + } + + float pulse = fx.bWarn ? GetPulseFactor(time - fx.flWarnTime, GetParam(el, bhl::sb::E_Param::WarnPulseMs)) : 1.0f; + state.flAlpha = fx.flFade * pulse; + state.bDrawn = true; + return true; +} + +unsigned int CHudServerPanel::GetSignature(int id, const CScoreboardData::Subject &subject, const ElementState &state) const +{ + unsigned int hash = HASH_BASIS; + + switch (state.kind) + { + case bhl::sb::E_ElementKind::Text: + hash = HashInt(hash, m_Data.GetElementVariant(id, subject)); + break; + case bhl::sb::E_ElementKind::Icon: + hash = HashInt(hash, state.iSprite); + break; + case bhl::sb::E_ElementKind::Meter: + case bhl::sb::E_ElementKind::Strip: + hash = HashInt(HashInt(hash, state.iCur), state.iMax); + break; + case bhl::sb::E_ElementKind::Board: + { + const RowsState &rows = *m_pRows[id]; + + for (int i = 0; i < rows.iCount; i++) + { + const RowState &row = rows.rows[i]; + + for (int c = 0; c < row.iColumns; c++) + hash = HashText(HashInt(hash, c), row.wszText + row.iColumnStart[c]); + } + + break; + } + default: + break; + } + + return state.wszText[0] ? HashText(hash, state.wszText) : hash; +} + +void CHudServerPanel::AddDrawnBounds(int id, const ElementState &state, int *bounds) const +{ + AddToBounds(bounds, state.x, state.y, state.wide, state.tall); + + if (state.kind == bhl::sb::E_ElementKind::Meter && state.wszText[0]) + AddToBounds(bounds, state.iTextX, state.iTextY, state.iTextWide, state.iFontTall); + + if (state.kind != bhl::sb::E_ElementKind::Strip) + return; + + int leftWide = vgui2::surface()->GetCharacterWidth(state.font, MARKER_LEFT[0]); + int rightWide = vgui2::surface()->GetCharacterWidth(state.font, MARKER_RIGHT[0]); + + if (state.iFirst > 0) + AddToBounds(bounds, state.x - state.iCellGap - leftWide, state.iTextY, leftWide, state.iFontTall); + + if (state.iFirst + state.iShown < state.iMax) + AddToBounds(bounds, state.x + state.wide + state.iCellGap, state.iTextY, rightWide, state.iFontTall); + + for (int i = 0; state.bTrack && i < state.iShown; i++) + { + int n = m_iTrackCounts[id][state.iFirst + i]; + wchar_t text[16]; + + if (n <= 0) + continue; + + V_snwprintf(text, std::size(text), TRACK_FORMAT, n); + Box box = LayoutTrackMarker(state.x + i * (state.iCellWide + state.iCellGap), state.iCellWide, state.y, n, std::max(2, Scaled(4)), Scaled(2), GetTextWide(state.font, text), state.iFontTall); + AddToBounds(bounds, box.x, box.y, box.wide, box.tall); + } +} + +Color CHudServerPanel::GetColor(const ElementState &state, Color color, int partAlpha) const +{ + float alpha = clamp(partAlpha, 0, 255) * color.a() / 255.0f * gHUD.GetHudTransparency() * state.flAlpha; + return Color(color.r(), color.g(), color.b(), static_cast(alpha)); +} + +Color CHudServerPanel::GetRowColor(const ElementState &state, const CScoreboardData::Element &el, int variant, int partAlpha) const +{ + unsigned char rgba[4]; + + if (state.bWarn || !el.GetSlotColor(variant, rgba)) + return GetColor(state, partAlpha); + + return GetColor(state, FlashColor(ToColor(rgba), state.flFlash), partAlpha); +} + +void CHudServerPanel::PaintBackground() +{ + // HACK ALERT: Text is drawn in Paint(), see CHudDeathNoticePanel::Paint() + if (m_iDotTexture == -1) + { + m_iDotTexture = CreateCircleTexture(false, 0, CIRCLE_TEXTURE_SIZE); + m_iRingTexture = CreateCircleTexture(true, 0, CIRCLE_TEXTURE_SIZE); + m_iCapTextures[0] = CreateCircleTexture(false, 0, CIRCLE_TEXTURE_SIZE / 2); + m_iCapTextures[1] = CreateCircleTexture(false, CIRCLE_TEXTURE_SIZE / 2, CIRCLE_TEXTURE_SIZE); + } + + // Boxes go under every other shape, and before any sprite turns blending off + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + if (m_States[id].bDrawn && m_States[id].kind == bhl::sb::E_ElementKind::Box) + PaintBox(m_States[id], m_Data.GetElement(id)); + } + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const ElementState &state = m_States[id]; + + if (!state.bDrawn) + continue; + + const CScoreboardData::Element &el = m_Data.GetElement(id); + + switch (state.kind) + { + case bhl::sb::E_ElementKind::Meter: + PaintMeter(state, el); + break; + case bhl::sb::E_ElementKind::Strip: + PaintStripCells(id, state, el); + break; + case bhl::sb::E_ElementKind::Icon: + DrawPanelSprite(state.iSprite, state.x, state.y + (state.tall - state.iIconTall) / 2, state.iIconWide, state.iIconTall, GetColor(state, 255)); + break; + case bhl::sb::E_ElementKind::Board: + PaintBoardShapes(id, state, el); + break; + case bhl::sb::E_ElementKind::Feed: + PaintFeed(id, state, el, false); + break; + default: + break; + } + } +} + +void CHudServerPanel::Paint() +{ + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + const ElementState &state = m_States[id]; + + if (!state.bDrawn) + continue; + + if (state.kind == bhl::sb::E_ElementKind::Strip) + PaintStripTexts(id, state, m_Data.GetElement(id)); + else if (state.kind == bhl::sb::E_ElementKind::Board) + PaintBoardTexts(id, state, m_Data.GetElement(id)); + else if (state.kind == bhl::sb::E_ElementKind::Feed) + PaintFeed(id, state, m_Data.GetElement(id), true); + else if (state.wszText[0]) + DrawCellText(state.font, state.iTextX, state.iTextY, GetColor(state, 255), state.wszText); + } +} + +void CHudServerPanel::PaintMeter(const ElementState &state, const CScoreboardData::Element &el) +{ + int dot = state.tall; + + if (state.bRing) + { + Color color = GetColor(state, 255); + double center = (state.wide - state.iDotSize) / 2.0; + + // Dot 0 on top, clockwise + for (int i = 0; i < state.iRingDots; i++) + { + double angle = -PI / 2 + 2 * PI * i / state.iRingDots; + int x = static_cast(std::floor(center + center * std::cos(angle) + 0.5)); + int y = static_cast(std::floor(center + center * std::sin(angle) + 0.5)); + DrawTexture(i < state.iRingFilled ? m_iDotTexture : m_iRingTexture, state.x + x, state.y + y, state.iDotSize, state.iDotSize, color); + } + + return; + } + + if (state.bDots) + { + Color color = GetColor(state, 255); + + for (int i = 0; i < state.iMax; i++) + DrawTexture(i < state.iCur ? m_iDotTexture : m_iRingTexture, state.x + i * (dot + state.iDotGap), state.y, dot, dot, color); + + return; + } + + DrawRoundedBar(state.x, state.y, state.wide, dot, GetColor(state, GetParam(el, bhl::sb::E_Param::AlphaEmpty))); + + if (state.iFillWide > 0) + DrawRoundedBar(state.x, state.y, state.iFillWide, dot, GetColor(state, 255)); +} + +void CHudServerPanel::PaintStripCells(int id, const ElementState &state, const CScoreboardData::Element &el) +{ + int alphaPassed = GetParam(el, bhl::sb::E_Param::AlphaPassed); + int alphaCurrent = GetParam(el, bhl::sb::E_Param::AlphaCurrent); + int alphaFuture = GetParam(el, bhl::sb::E_Param::AlphaFuture); + int alphaIconFuture = GetParam(el, bhl::sb::E_Param::AlphaIconFuture); + bool hasFrame = GetParam(el, bhl::sb::E_Param::Frame) != 0; + int padding = Scaled(GetParam(el, bhl::sb::E_Param::IconPadding)); + int step = state.iCellWide + state.iCellGap; + + for (int i = 0; i < state.iShown; i++) + { + int cell = state.iFirst + i; + int x = state.x + i * step; + int alpha = cell < state.iCur ? alphaPassed : (cell == state.iCur ? alphaCurrent : alphaFuture); + + vgui2::surface()->DrawSetColor(GetColor(state, alpha)); + vgui2::surface()->DrawFilledRect(x, state.y, x + state.iCellWide, state.y + state.tall); + + if (cell == state.iCur && hasFrame) + { + vgui2::surface()->DrawSetColor(GetColor(state, 255)); + vgui2::surface()->DrawOutlinedRect(x, state.y, x + state.iCellWide, state.y + state.tall); + } + } + + for (int i = 0; i < state.iShown; i++) + { + int cell = state.iFirst + i; + int sprite = m_iStripSprites[id][cell]; + const wrect_t &rc = GetScoreSpriteRect(sprite); + + if (sprite == -1 || rc.GetWidth() <= 0 || rc.GetHeight() <= 0) + continue; + + float scale = std::min(float(state.iCellWide - 2 * padding) / rc.GetWidth(), float(state.tall - 2 * padding) / rc.GetHeight()); + int wide = static_cast(rc.GetWidth() * scale); + int tall = static_cast(rc.GetHeight() * scale); + + if (wide <= 0 || tall <= 0) + continue; + + int x = state.x + i * step + (state.iCellWide - wide) / 2; + int y = state.y + (state.tall - tall) / 2; + DrawPanelSprite(sprite, x, y, wide, tall, GetColor(state, cell > state.iCur ? alphaIconFuture : 255)); + } + + if (state.bTrack) + PaintTrackMarkers(id, state, false); +} + +void CHudServerPanel::PaintStripTexts(int id, const ElementState &state, const CScoreboardData::Element &el) +{ + const CScoreboardData::List *list = el.szList[0] ? m_Data.FindList(el.szList) : nullptr; + int alphaIconFuture = GetParam(el, bhl::sb::E_Param::AlphaIconFuture); + int step = state.iCellWide + state.iCellGap; + + // Icon items are sprites: one the client doesn't have leaves its cell empty + for (int i = 0; list && i < state.iShown && state.iFirst + i < list->iCount; i++) + { + int cell = state.iFirst + i; + const CScoreboardData::Value &item = list->items[cell]; + + if (item.type == bhl::sb::E_ValueType::Icon || item.IsEmpty()) + continue; + + wchar_t text[bhl::sb::TEMPLATE_BUF_LEN]; + item.ToString(text, sizeof(text)); + + if (!text[0]) + continue; + + int x = state.x + i * step + (state.iCellWide - GetTextWide(state.font, text)) / 2; + DrawCellText(state.font, x, state.iTextY, GetColor(state, cell > state.iCur ? alphaIconFuture : 255), text); + } + + Color color = GetColor(state, 255); + + if (state.iFirst > 0) + DrawCellText(state.font, state.x - state.iCellGap - vgui2::surface()->GetCharacterWidth(state.font, MARKER_LEFT[0]), state.iTextY, color, MARKER_LEFT); + + if (state.iFirst + state.iShown < state.iMax) + DrawCellText(state.font, state.x + state.wide + state.iCellGap, state.iTextY, color, MARKER_RIGHT); + + if (state.bTrack) + PaintTrackMarkers(id, state, true); +} + +void CHudServerPanel::PaintTrackMarkers(int id, const ElementState &state, bool texts) +{ + int disc = std::max(2, Scaled(4)); + int gap = Scaled(2); + Color color = GetColor(state, 255); + + for (int i = 0; i < state.iShown; i++) + { + int n = m_iTrackCounts[id][state.iFirst + i]; + wchar_t text[16]; + + if (n <= 0 || (n > 2) != texts) + continue; + + V_snwprintf(text, std::size(text), TRACK_FORMAT, n); + Box box = LayoutTrackMarker(state.x + i * (state.iCellWide + state.iCellGap), state.iCellWide, state.y, n, disc, gap, GetTextWide(state.font, text), state.iFontTall); + + if (texts) + { + DrawCellText(state.font, box.x, box.y, color, text); + continue; + } + + for (int j = 0; j < n; j++) + DrawTexture(m_iDotTexture, box.x + j * (disc + gap), box.y, disc, disc, color); + } +} + +void CHudServerPanel::PaintBoardShapes(int id, const ElementState &state, const CScoreboardData::Element &el) +{ + const RowsState &rows = GetPaintRows(id, state); + int highlightAlpha = GetParam(el, bhl::sb::E_Param::HighlightAlpha); + int fillAlpha = GetParam(el, bhl::sb::E_Param::FillAlpha); + + for (int i = 0; i < rows.iCount; i++) + { + const RowState &row = rows.rows[i]; + int y = state.y + i * rows.iStep; + int fillWide = static_cast(state.wide * row.flFill); + + if (i == rows.iOwn && highlightAlpha > 0) + { + vgui2::surface()->DrawSetColor(GetColor(state, highlightAlpha)); + vgui2::surface()->DrawFilledRect(state.x, y, state.x + state.wide, y + state.iFontTall); + } + + if (fillAlpha > 0 && fillWide > 0) + { + vgui2::surface()->DrawSetColor(GetColor(state, fillAlpha)); + vgui2::surface()->DrawFilledRect(state.x, y, state.x + fillWide, y + state.iFontTall); + } + + if (row.iSprite != -1) + { + int x = state.x + rows.iIconX + (rows.iIconWide - row.iIconWide) / 2; + DrawPanelSprite(row.iSprite, x, y, row.iIconWide, state.iFontTall, GetRowColor(state, el, row.iVariant, 255)); + } + } +} + +void CHudServerPanel::PaintBoardTexts(int id, const ElementState &state, const CScoreboardData::Element &el) +{ + const RowsState &rows = GetPaintRows(id, state); + + for (int i = 0; i < rows.iCount; i++) + { + const RowState &row = rows.rows[i]; + Color color = GetRowColor(state, el, row.iVariant, 255); + + for (int c = 0; c < row.iColumns; c++) + { + const wchar_t *text = row.wszText + row.iColumnStart[c]; + + if (!text[0]) + continue; + + int x = state.x + rows.iColumnX[c] + (rows.bColumnRight[c] ? rows.iColumnWide[c] - row.iColumnWide[c] : 0); + DrawCellText(state.font, x, state.y + i * rows.iStep, color, text); + } + } +} + +void CHudServerPanel::PaintFeed(int id, const ElementState &state, const CScoreboardData::Element &el, bool texts) +{ + const RowsState &rows = GetPaintRows(id, state); + + for (int i = 0; i < rows.iCount; i++) + { + const RowState &row = rows.rows[i]; + int space = state.wide - row.iWide; + int x = state.x + (state.iAnchor == bhl::sb::ANCHOR_END ? space : (state.iAnchor == bhl::sb::ANCHOR_CENTER ? space / 2 : 0)); + int y = state.y + i * rows.iStep; + Color color = GetRowColor(state, el, row.iVariant, static_cast(row.flAlpha * 255 + 0.5f)); + + if (texts && row.wszText[0]) + DrawCellText(state.font, x + row.iTextX, y, color, row.wszText); + else if (!texts && row.iSprite != -1) + DrawPanelSprite(row.iSprite, x, y, row.iIconWide, state.iFontTall, color); + } +} + +void CHudServerPanel::PaintBox(const ElementState &state, const CScoreboardData::Element &el) +{ + unsigned char rgba[4]; + Color hudColor = gHUD.GetHudColor(HudPart::Common, 0); + Color accent = el.GetSlotColor(bhl::sb::SLOT_ACCENT, rgba) ? ToColor(rgba) : Color(hudColor.r(), hudColor.g(), hudColor.b(), 255); + int radius = Scaled(GetParam(el, bhl::sb::E_Param::Radius)); + int accentWide = Scaled(GetParam(el, bhl::sb::E_Param::AccentWide)); + int x1 = state.x + state.wide; + int y1 = state.y + state.tall; + + DrawRoundedBox(state.x, state.y, x1, y1, radius, GetColor(state, 255)); + + if (accentWide > 0) + DrawRoundedBox(state.x, state.y, x1, y1, radius, GetColor(state, accent, 255), state.x + accentWide); +} + +void CHudServerPanel::DrawRoundedBar(int x, int y, int wide, int tall, Color color) +{ + int radius = tall / 2; + wide = std::max(wide, 2 * radius); + + DrawTexture(m_iCapTextures[0], x, y, radius, tall, color); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x + radius, y, x + wide - radius, y + tall); + DrawTexture(m_iCapTextures[1], x + wide - radius, y, radius, tall, color); +} diff --git a/src/game/client/hud/server_panel.h b/src/game/client/hud/server_panel.h new file mode 100644 index 00000000..0829f22d --- /dev/null +++ b/src/game/client/hud/server_panel.h @@ -0,0 +1,259 @@ +#ifndef HUD_SERVER_PANEL_H +#define HUD_SERVER_PANEL_H +#include +#include +#include +#include "hud/base.h" +#include "scoreboard_data.h" + +/** + * HUD elements defined by the server: Text, Icon, Meter, Strip, Board, Feed and Box (docs/scoreboard-protocol.md, 8). + * One full-screen panel lays out every element from the store and draws them in two passes, each in id order: + * the shapes and sprites of all elements, then all texts (DrawFlushText turns off alpha blending, so texts go last). + * Boxes are drawn before every other shape. + * Kind params default to the values in HudServerPanel of HudLayoutBase.res, under the names of + * bhl::sb::PARAM_INFO; a param sent by the server wins. Sizes are proportional units of a 640x480 screen. + */ +class CHudServerPanel : public CHudElemBase, public vgui2::Panel +{ +public: + DECLARE_CLASS_SIMPLE(CHudServerPanel, vgui2::Panel); + + CHudServerPanel(); + + void Init() override; + void VidInit() override; + void Think() override; + void ApplySchemeSettings(vgui2::IScheme *pScheme) override; + void ApplySettings(KeyValues *inResourceData) override; + void PaintBackground() override; + void Paint() override; + +private: + //! Rows of a Board (the rows param, the separator and the own row) and lines of a Feed + static constexpr int MAX_ROWS = 18; + + //! Columns of a Board row: its text split at TAB characters + static constexpr int MAX_ROW_COLUMNS = 4; + + //! Time of an effect that never ran + static constexpr float NEVER = -1.0e30f; + + //! Box and drawing state of an element, computed every frame parents first (8.4) for elements that are drawn or are parents + struct ElementState + { + bool bDrawn = false; //!< Passes every rule of 8.3 and hold_ms, or fades out + bool bGhost = false; //!< The last drawn state of an element that fades out (fade_ms) + bhl::sb::E_ElementKind kind = bhl::sb::E_ElementKind::None; + int x = 0, y = 0; + int wide = 0, tall = 0; + Color color; //!< rgb and the alpha of the element, before the part alpha and hud_draw + float flAlpha = 1; //!< fade_ms and warn_pulse_ms; exactly 1 without them + float flFlash = 0; //!< flash_ms: how far rgb goes toward white, for the variant colors of rows + bool bWarn = false; //!< warn_at holds: color has the warn color, rows don't use their variant colors + vgui2::HFont font = vgui2::INVALID_FONT; + int iFontTall = 0; + int iAnchor = 0; //!< Horizontal anchor of the box: alignment of Feed lines + + //! Text, the counter of a Meter or the text after an Icon; "" if there is none + wchar_t wszText[bhl::sb::TEMPLATE_BUF_LEN] = {}; + int iTextWide = 0; + int iTextX = 0, iTextY = 0; //!< Text; also the line of the markers and texts of a Strip + + int iCur = 0; //!< Meter: cur clamped to [0, max]; Strip: current cell + int iMax = 0; //!< Meter: max; Strip: count + + // Meter (8.7) + bool bDots = false; //!< A dot per unit: the counter param 1 hides the counter + int iDotGap = 0; + int iFillWide = 0; + bool bRing = false; //!< form 1 + int iDotSize = 0; + int iRingDots = 0; + int iRingFilled = 0; + + // Strip (8.8) + int iCellWide = 0; + int iCellGap = 0; + int iShown = 0; + int iFirst = 0; + bool bTrack = false; //!< track 1: markers of the other players above the cells + + // Icon (8.9) + int iSprite = -1; + int iIconWide = 0, iIconTall = 0; + }; + + //! A row of a Board or a line of a Feed + struct RowState + { + wchar_t wszText[bhl::sb::TEMPLATE_BUF_LEN] = {}; //!< Board: the columns are separated by NULs + int iColumnStart[MAX_ROW_COLUMNS] = {}; + int iColumnWide[MAX_ROW_COLUMNS] = {}; + int iColumns = 0; + int iVariant = 0; //!< Template variant: its color slot applies + int iSprite = -1; + int iIconWide = 0; //!< The icon is as tall as the font + float flFill = 0; //!< Board: fill_alpha bar, part of the row width + float flAlpha = 1; //!< Feed: fade of the line + int iTextX = 0; //!< Feed: offset of the text in the line + int iWide = 0; //!< Feed: width of the line + + //! The last icon sprite name of the row and its index, failures too + char szSpriteName[bhl::sb::MAX_TEXT_LEN + 1] = {}; + int iSpriteOfName = -1; + }; + + //! Rows of a Board or lines of a Feed, allocated for elements of these kinds + struct RowsState + { + int iCount = 0; + int iOwn = -1; //!< Board: the highlighted row + int iStep = 0; //!< Font height and the row or line gap + int iColumns = 0; + int iColumnX[MAX_ROW_COLUMNS] = {}; //!< Offsets in the box + int iColumnWide[MAX_ROW_COLUMNS] = {}; + bool bColumnRight[MAX_ROW_COLUMNS] = {}; + int iIconX = 0; + int iIconWide = 0; + RowState rows[MAX_ROWS]; + }; + + //! A line of an announcer Feed and its interval, all 0 for none + struct AnnouncerAnchor + { + int iSeq = 0; //!< CScoreboardData::HudLine::iSeq + float flStart = 0; + float flEnd = 0; + }; + + //! Effects of an element (8.13), kept between frames + struct EffectState + { + bhl::sb::E_ElementKind kind = bhl::sb::E_ElementKind::None; //!< Another kind resets the effects + int iRemovals = 0; //!< CScoreboardData::GetElementRemovals(): a removal resets the effects + CScoreboardData::Subject subject; //!< Another subject resets the content signature + bool bPresent = false; //!< Shown with content, before hold_ms + bool bDrawn = false; //!< Also the direction of the fade since flFadeTime + bool bHasGhost = false; //!< m_pGhosts holds the last drawn state + bool bHasSignature = false; + unsigned int iSignature = 0; //!< Hash of what is drawn + float flHoldTime = NEVER; //!< Appearance or content change + float flFlashTime = NEVER; + bool bWarn = false; + float flWarnTime = NEVER; + float flFadeFrom = 0; + float flFadeTime = 0; + int iFadeMs = 0; + float flFade = 0; //!< Fade factor of this frame + AnnouncerAnchor anchor; //!< Announcer Feeds (queue 1): the last started line, so evicting older lines doesn't move the later ones + }; + + //! Param defaults by bhl::sb::E_Param, from HudLayoutBase.res and clamped to bhl::sb::PARAM_INFO + int m_iParamDefaults[bhl::sb::MAX_PARAM_ID + 1] = {}; + + //! Fonts by bhl::sb::E_Font, from bhl::sb::FONT_NAMES of the scheme + vgui2::HFont m_Fonts[bhl::sb::FONT_COUNT] = {}; + + const CScoreboardData &m_Data = CScoreboardData::Get(); + ElementState m_States[bhl::sb::MAX_ELEMENTS]; + + //! Sprite indexes of the list items of Strip elements, valid while the store serial is m_iStripSpriteSerial + int m_iStripSprites[bhl::sb::MAX_ELEMENTS][bhl::sb::MAX_LIST_ITEMS] = {}; + int m_iStripSpriteSerial = -1; + + //! Sprite of the value of Icon elements and its name: the value follows the subject, not the store serial + char m_szIconSprites[bhl::sb::MAX_ELEMENTS][bhl::sb::MAX_TEXT_LEN + 1] = {}; + int m_iIconSprites[bhl::sb::MAX_ELEMENTS] = {}; + + EffectState m_Effects[bhl::sb::MAX_ELEMENTS]; + std::unique_ptr m_pGhosts[bhl::sb::MAX_ELEMENTS]; + std::unique_ptr m_pRows[bhl::sb::MAX_ELEMENTS]; + std::unique_ptr m_pGhostRows[bhl::sb::MAX_ELEMENTS]; //!< Rows of the ghost: swapped with m_pRows, not copied + + //! Markers of a Strip with track 1: players other than the subject by cell + unsigned char m_iTrackCounts[bhl::sb::MAX_ELEMENTS][bhl::sb::MAX_LIST_ITEMS] = {}; + + //! CScoreboardData::GetResetCount() seen last: after a Reset the content signatures start over + int m_iResetCount = -1; + + int m_iDotTexture = -1; + int m_iRingTexture = -1; + int m_iCapTextures[2] = { -1, -1 }; //!< Left and right halves of a disc: caps of a rounded bar + + //! Lays out every element. Returns true if any is drawn. + bool UpdateLayout(); + + /** + * Content and size of the box (8.6-8.9). + * @param freeWide Width between the side zones of the numbers row for a Strip on it + * @return true if the element has content (8.3 rule 7) + */ + bool MeasureElement(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, int freeWide, ElementState &state); + bool MeasureMeter(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state); + bool MeasureStrip(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, int freeWide, ElementState &state); + bool MeasureIcon(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state); + bool MeasureBoard(int id, const CScoreboardData::Element &el, const CScoreboardData::Subject &subject, ElementState &state); + bool MeasureFeed(int id, const CScoreboardData::Element &el, ElementState &state); + + //! Anchor of the placed box and positions of its texts: with the end (right) anchor the Meter counter goes to the left + void PlaceContent(const CScoreboardData::Element &el, ElementState &state); + + void UpdateStripSprites(); + void SetRowIcon(RowState &row, const char *sprite, int tall); + void UpdateTrack(int id, const CScoreboardData::Subject &subject, int count); + + //! Rows of a Board or Feed, allocated on first use + RowsState &GetRows(int id); + + //! Rows to draw: those of the ghost for a ghost + const RowsState &GetPaintRows(int id, const ElementState &state) const { return state.bGhost ? *m_pGhostRows[id] : *m_pRows[id]; } + + /** + * Keeps the state of the elements drawn in the last frame that have fade_ms, + * so an element that stops being drawn fades out as it was drawn. + */ + void SaveGhosts(); + + //! Global cutoffs: nothing fades out. keepPresence keeps hold_ms and the signatures running. + void StopEffects(bool keepPresence); + + //! True if an element with fade_ms is drawn or fades out + bool IsFading() const; + + /** + * Effects of an element (8.13) after its layout: hold_ms, fade_ms, flash_ms, warn_at and the variant colors. + * Resets them when the kind or the subject changes. + * @param present Shown and has content + * @return true if the element is drawn this frame, or its ghost while it fades out + */ + bool UpdateEffects(int id, const CScoreboardData::Element &el, bool present, float time); + + //! Hash of what the element draws (8.13, flash_ms) + unsigned int GetSignature(int id, const CScoreboardData::Subject &subject, const ElementState &state) const; + + //! Adds the box of the element and the parts it draws outside it to bounds (x0, y0, x1, y1) + void AddDrawnBounds(int id, const ElementState &state, int *bounds) const; + + //! The server's param or the default + int GetParam(const CScoreboardData::Element &el, bhl::sb::E_Param param) const; + + //! Color for a part of the element (8.5): part * a / 255 * hud_draw, with the fade and pulse + Color GetColor(const ElementState &state, int partAlpha) const { return GetColor(state, state.color, partAlpha); } + Color GetColor(const ElementState &state, Color color, int partAlpha) const; + + //! Color of a Board row or a Feed line: the color slot of its variant unless the element warns + Color GetRowColor(const ElementState &state, const CScoreboardData::Element &el, int variant, int partAlpha) const; + + void PaintMeter(const ElementState &state, const CScoreboardData::Element &el); + void PaintStripCells(int id, const ElementState &state, const CScoreboardData::Element &el); + void PaintStripTexts(int id, const ElementState &state, const CScoreboardData::Element &el); + void PaintTrackMarkers(int id, const ElementState &state, bool texts); + void PaintBoardShapes(int id, const ElementState &state, const CScoreboardData::Element &el); + void PaintBoardTexts(int id, const ElementState &state, const CScoreboardData::Element &el); + void PaintFeed(int id, const ElementState &state, const CScoreboardData::Element &el, bool texts); + void PaintBox(const ElementState &state, const CScoreboardData::Element &el); + void DrawRoundedBar(int x, int y, int wide, int tall, Color color); +}; + +#endif diff --git a/src/game/client/hud/speedometer.cpp b/src/game/client/hud/speedometer.cpp index 842e2eef..a6bbac4f 100644 --- a/src/game/client/hud/speedometer.cpp +++ b/src/game/client/hud/speedometer.cpp @@ -3,6 +3,7 @@ #include "cl_util.h" #include "parsemsg.h" #include "speedometer.h" +#include "scoreboard_data.h" extern ConVar hud_jumpspeed; extern ConVar hud_jumpspeed_below_cross; @@ -28,6 +29,10 @@ void CHudSpeedometer::Draw(float time) if (!hud_speedometer.GetBool()) return; + // The server hides only the bottom position + if (!hud_speedometer_below_cross.GetBool() && CScoreboardData::Get().IsStdPartHidden(bhl::sb::E_HudStd::Speedometer)) + return; + if (m_iOldSpeed != m_iSpeed) m_fFade = FADE_TIME; diff --git a/src/game/client/hud/timer.cpp b/src/game/client/hud/timer.cpp index e38ff4e9..d21c0444 100644 --- a/src/game/client/hud/timer.cpp +++ b/src/game/client/hud/timer.cpp @@ -19,6 +19,7 @@ #include "net.h" #include "demo.h" #include "demo_api.h" +#include "scoreboard_data.h" #define NET_API gEngfuncs.pNetAPI @@ -578,7 +579,7 @@ void CHudTimer::Draw(float fTime) // Draw timer float timeleft = m_flSynced ? (int)(m_flEndTime - currentTime) + 1 : (int)(m_flEndTime - m_flEffectiveTime); - int hud_timer = (int)m_pCvarHudTimer->value; + int hud_timer = CScoreboardData::Get().IsStdPartHidden(bhl::sb::E_HudStd::Timer) ? 0 : (int)m_pCvarHudTimer->value; int ypos = ScreenHeight * TIMER_Y; switch (hud_timer) { @@ -603,7 +604,7 @@ void CHudTimer::Draw(float fTime) } // Draw next map - int hud_nextmap = (int)m_pCvarHudNextmap->value; + int hud_nextmap = CScoreboardData::Get().IsStdPartHidden(bhl::sb::E_HudStd::NextMap) ? 0 : (int)m_pCvarHudNextmap->value; if (m_szNextmap[0] && timeleft < 60 && timeleft >= 0 && m_flEndTime > 0 && (hud_nextmap == 2 || (hud_nextmap == 1 && timeleft >= 37))) { snprintf(text, sizeof(text), "Nextmap is %s", m_szNextmap); @@ -627,6 +628,10 @@ void CHudTimer::Draw(float fTime) } else if (m_flCustomTimerEnd[i] > currentTime) { + // Only the display is hidden: the sound at the end still plays + if (CScoreboardData::Get().IsStdPartHidden(bhl::sb::E_HudStd::CustomTimers)) + continue; + timeleft = (int)(m_flCustomTimerEnd[i] - currentTime) + 1; sprintf(text, "Timer %d", (int)timeleft); // Output to screen diff --git a/src/game/client/hud_renderer.cpp b/src/game/client/hud_renderer.cpp index cd104601..1c2e3584 100644 --- a/src/game/client/hud_renderer.cpp +++ b/src/game/client/hud_renderer.cpp @@ -52,6 +52,11 @@ void CHudRenderer::SpriteDrawAdditive(int frame, int x, int y, const wrect_t *pr s_Instance.DrawSprite(frame, x, y, -1, -1, prc, SpriteDrawMode::Additive); } +void CHudRenderer::SpriteDrawAdditiveScaled(int frame, float x, float y, float width, float height, const wrect_t *prc) +{ + s_Instance.DrawSprite(frame, x, y, width, height, prc, SpriteDrawMode::Additive); +} + void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode) { if (m_hPic <= 0) @@ -61,12 +66,12 @@ void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float he } // This function is based on Xash3D code - if (width == -1 && height == -1) - { - // assume we get sizes from image - width = gEngfuncs.pfnSPR_Width(m_hPic, frame); - height = gEngfuncs.pfnSPR_Height(m_hPic, frame); - } + float drawWidth = width; + float drawHeight = height; + + // assume we get sizes from image + width = gEngfuncs.pfnSPR_Width(m_hPic, frame); + height = gEngfuncs.pfnSPR_Height(m_hPic, frame); float s[2], t[2]; @@ -98,6 +103,12 @@ void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float he s[1] = t[1] = 1.0f; } + if (drawWidth != -1 || drawHeight != -1) + { + width = drawWidth; + height = drawHeight; + } + const model_t *spriteModel = gEngfuncs.GetSpritePointer(m_hPic); if (!spriteModel) diff --git a/src/game/client/hud_renderer.h b/src/game/client/hud_renderer.h index 8031768c..b7965a4b 100644 --- a/src/game/client/hud_renderer.h +++ b/src/game/client/hud_renderer.h @@ -14,6 +14,9 @@ class CHudRenderer static void SpriteDraw(int frame, int x, int y, const wrect_t *prc); static void SpriteDrawAdditive(int frame, int x, int y, const wrect_t *prc); + //! Draws rectangle prc of the sprite stretched to width x height + static void SpriteDrawAdditiveScaled(int frame, float x, float y, float width, float height, const wrect_t *prc); + private: enum class SpriteDrawMode { @@ -24,6 +27,7 @@ class CHudRenderer HSPRITE m_hPic = 0; uint8_t m_SpriteColor[4]; + //! width and height of -1 draw the rectangle in its own size void DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode); }; diff --git a/src/game/client/scoreboard_data.cpp b/src/game/client/scoreboard_data.cpp new file mode 100644 index 00000000..cc64f438 --- /dev/null +++ b/src/game/client/scoreboard_data.cpp @@ -0,0 +1,1605 @@ +#include +#include +#include +#include +#include +#include +#include +#include "hud.h" +#include "cl_util.h" +#include "pm_shared.h" +#include "scoreboard_data.h" + +using namespace bhl::sb; + +static_assert(TARGET_PLAYER_LAST - TARGET_PLAYER_FIRST + 1 <= MAX_PLAYERS, "player targets must fit m_PlayerValues"); +static_assert(TARGET_TEAM_LAST - TARGET_TEAM_BASE <= MAX_TEAMS, "team targets must fit m_TeamValues"); +static_assert(MAX_TEAMS <= MAX_PLAYERS, "ranked teams must fit Ranking::entities"); + +ConVar hud_scoreboard_custom("hud_scoreboard_custom", "1", FCVAR_ARCHIVE, "Show the custom scoreboard when the server sends one"); +ConVar hud_server_elements("hud_server_elements", "1", FCVAR_BHL_ARCHIVE, "Draw HUD elements defined by the server"); + +//----------------------------------------------------- +// CMsgReader +//----------------------------------------------------- +class CScoreboardData::CMsgReader +{ +public: + CMsgReader(const void *pBuf, int iSize) + : m_pBuf(static_cast(pBuf)) + , m_iSize(iSize > 0 ? iSize : 0) + { + } + + int GetRemaining() const { return m_iSize - m_iPos; } + + //! Reads a little-endian integer of 1, 2 or 4 bytes, sign-extended if bSigned + bool ReadInt(int &out, int size, bool bSigned) + { + if (GetRemaining() < size) + return false; + + unsigned int value = 0; + + for (int i = size - 1; i >= 0; i--) + value = (value << 8) | m_pBuf[m_iPos + i]; + + if (bSigned && size < 4 && (value >> (8 * size - 1))) + value |= ~0u << (8 * size); + + out = static_cast(value); + m_iPos += size; + return true; + } + + bool ReadByte(int &out) { return ReadInt(out, 1, false); } + bool ReadWord(int &out) { return ReadInt(out, 2, false); } + bool ReadShort(int &out) { return ReadInt(out, 2, true); } + bool ReadLong(int &out) { return ReadInt(out, 4, true); } + + /** + * Reads a NUL-terminated string, cut to the buffer on a UTF-8 boundary. + * @param bStripColors Removes color codes (4.2): every string but template texts and refs + * @return false if the payload ends before the NUL; buf is then "" + */ + bool ReadString(char *buf, int bufSize, bool bStripColors = true) + { + int len = 0; + bool bTruncated = false; + bool bTerminated = false; + + while (GetRemaining() > 0) + { + char c = static_cast(m_pBuf[m_iPos]); + m_iPos++; + + if (c == '\0') + { + bTerminated = true; + break; + } + + if (len < bufSize - 1) + buf[len++] = c; + else + bTruncated = true; + } + + buf[bTerminated ? len : 0] = '\0'; + + if (bTruncated) + Q_UnicodeRepair(buf, STRINGCONVERT_SKIP); + + if (bStripColors) + RemoveColorCodesInPlace(buf); + + return bTerminated; + } + + //! Returns a reader of the next len bytes and skips them. len must not exceed GetRemaining(). + CMsgReader ReadBlock(int len) + { + CMsgReader block(m_pBuf + m_iPos, len); + m_iPos += len; + return block; + } + +private: + const unsigned char *m_pBuf = nullptr; + int m_iSize = 0; + int m_iPos = 0; +}; + +namespace +{ + +const CScoreboardData::Value s_EmptyValue = CScoreboardData::Value(); +const CScoreboardData::Column s_EmptyColumn = CScoreboardData::Column(); +const CScoreboardData::Element s_EmptyElement = CScoreboardData::Element(); + +//! Returns < 0 if a goes before b. Empty values go after filled ones and numbers before texts in both directions. +int CompareValues(const CScoreboardData::Value &a, const CScoreboardData::Value &b, bool bAscending) +{ + if (a.IsEmpty() || b.IsEmpty()) + return static_cast(a.IsEmpty()) - static_cast(b.IsEmpty()); + + int numA = 0; + int numB = 0; + bool bIsNumA = a.GetNumber(numA); + bool bIsNumB = b.GetNumber(numB); + int result = 0; + + if (bIsNumA != bIsNumB) + return bIsNumA ? -1 : 1; + + if (bIsNumA) + { + result = (numA > numB) - (numA < numB); + } + else + { + result = Q_stricmp(a.szText, b.szText); + + if (result == 0) + result = Q_stricmp(a.szSprite, b.szSprite); + } + + return bAscending ? result : -result; +} + +bool IsTeamNumber(int team) +{ + return team >= 1 && team <= MAX_TEAMS; +} + +//! Team number of a connected player, 0 otherwise +int GetPlayerTeamNumber(int client) +{ + CPlayerInfo *pi = GetPlayerInfoSafe(client); + return pi ? pi->GetTeamNumber() : 0; +} + +//! Frags and deaths as the scoreboard shows them: ScoreInfo of a player (0 for an empty slot), TeamScore of a team if it overrides them, else the sums of its players +void GetEntityScore(const CScoreboardData::Subject &entity, int &frags, int &deaths) +{ + CPlayerInfo *pi = entity.IsTeam() ? nullptr : GetPlayerInfoSafe(entity.iPlayer); + frags = pi ? pi->GetFrags() : 0; + deaths = pi ? pi->GetDeaths() : 0; + + if (!IsTeamNumber(entity.iTeam)) + return; + + CTeamInfo *ti = GetTeamInfo(entity.iTeam); + + if (ti->IsScoreOverriden()) + { + frags = ti->GetFrags(); + deaths = ti->GetDeaths(); + return; + } + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *player = GetPlayerInfoSafe(i); + + if (player && player->GetTeamNumber() == entity.iTeam) + { + frags += player->GetFrags(); + deaths += player->GetDeaths(); + } + } +} + +//! Participants, or teams with participants, by number; out needs MAX_PLAYERS entries +int CollectEntities(bool bTeams, CScoreboardData::Subject *out) +{ + bool bTeamHasParticipants[MAX_TEAMS + 1] = {}; + int count = 0; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + int team = GetPlayerTeamNumber(i); + + if (!CScoreboardData::IsParticipant(i)) + continue; + + if (!bTeams) + out[count++] = { i, 0 }; + else if (IsTeamNumber(team)) + bTeamHasParticipants[team] = true; + } + + for (int i = 1; i <= MAX_TEAMS && bTeams; i++) + { + if (bTeamHasParticipants[i]) + out[count++] = { 0, i }; + } + + return count; +} + +int ClampToInt(long long value) +{ + return static_cast(clamp(value, INT_MIN, INT_MAX)); +} + +//! The display name without color codes, never looked up as a token (8.10) +bool WritePlayerName(int client, wchar_t *buf, int bufSizeBytes) +{ + CPlayerInfo *pi = GetPlayerInfoSafe(client); + + if (!pi) + return false; + + char name[128]; + RemoveColorCodes(pi->GetDisplayName(), name, sizeof(name)); + Q_UTF8ToWString(name, buf, bufSizeBytes, STRINGCONVERT_REPLACE); + return true; +} + +//! The team name as the scoreboard team header shows it. False for a team without players. +bool WriteTeamName(int team, wchar_t *buf, int bufSizeBytes) +{ + if (!IsTeamNumber(team)) + return false; + + bool bHasPlayers = false; + + for (int i = 1; i <= MAX_PLAYERS && !bHasPlayers; i++) + bHasPlayers = GetPlayerTeamNumber(i) == team; + + if (!bHasPlayers) + return false; + + char name[128]; + RemoveColorCodes(GetTeamInfo(team)->GetDisplayName(), name, sizeof(name)); + const wchar_t *localized = name[0] == '#' ? g_pVGuiLocalize->Find(name) : nullptr; + + if (localized) + V_wcsncpy(buf, localized, bufSizeBytes); + else + Q_UTF8ToWString(name, buf, bufSizeBytes, STRINGCONVERT_REPLACE); + + return true; +} + +//! Display name of an Icon value (10.3): BHL_Weapon_ for standard HL sprites, else the localized text +void GetIconName(const CScoreboardData::Value &value, wchar_t *buf, int bufSizeBytes) +{ + if (!strncmp(value.szSprite, "d_", 2)) + { + char token[64]; + snprintf(token, sizeof(token), "BHL_Weapon_%s", value.szSprite + 2); + const wchar_t *name = g_pVGuiLocalize->Find(token); + + if (name) + { + V_wcsncpy(buf, name, bufSizeBytes); + return; + } + } + + CScoreboardData::LocalizeString(value.szText, buf, bufSizeBytes); +} + +//! A stored value as a template shows it (8.10, "Values are written as") +bool ValueToTemplate(const CScoreboardData::Value &value, TemplateValue &out) +{ + value.ToString(out.wszText, sizeof(out.wszText)); + out.bIsNumber = value.GetNumber(out.iNumber); + out.iMs = value.GetClockMs(); + out.bClockDown = value.type == E_ValueType::Clock && IsEnumFlagSet(value.clockFlags, E_ClockFlags::Down); + return !value.IsEmpty(); +} + +//! The first arg of type Icon or nullptr +const CScoreboardData::Value *FindIconArg(const CScoreboardData::Value *args, int count) +{ + for (int i = 0; i < count; i++) + { + if (args[i].type == E_ValueType::Icon) + return &args[i]; + } + + return nullptr; +} + +//! The default counter of a Meter without variant 0 (8.7) +const CTemplate &GetMeterCounterTemplate() +{ + static CTemplate s_Counter; + + if (!s_Counter.IsSet()) + s_Counter.Parse(L"{@value:cur} / {@value:max}"); + + return s_Counter; +} + +//! Values of templates for one subject and element +class CStoreTemplateContext : public ITemplateContext +{ +public: + CStoreTemplateContext(const CScoreboardData &data, const CScoreboardData::Subject &subject, int elementId, const CScoreboardData::TemplateExtras *pExtras) + : m_Data(data) + , m_Subject(subject) + , m_iElementId(elementId) + , m_pExtras(pExtras) + { + } + + bool GetValue(const TemplateRef &ref, TemplateValue &out) override + { + if (!m_pExtras || ref.bFirstRow) + return m_Data.ResolveRef(ref, m_Subject, m_iElementId, out); + + const CScoreboardData::TemplateExtras &extras = *m_pExtras; + const CScoreboardData::Value *value = nullptr; + CScoreboardData::Value index; + + switch (ref.builtin) + { + case E_Builtin::Value: + if (!extras.pValue) + return m_Data.ResolveRef(ref, m_Subject, m_iElementId, out); + + value = extras.pValue; + break; + case E_Builtin::Item: + value = extras.pItem; + break; + case E_Builtin::Index: + index.type = extras.iIndex > 0 ? E_ValueType::Int : E_ValueType::None; + index.iValue = extras.iIndex; + value = &index; + break; + case E_Builtin::A: + case E_Builtin::B: + case E_Builtin::C: + case E_Builtin::D: + { + int arg = static_cast(ref.builtin) - static_cast(E_Builtin::A); + value = extras.pArgs && arg < extras.iArgCount ? &extras.pArgs[arg] : nullptr; + break; + } + case E_Builtin::Icon: + value = extras.pArgs ? FindIconArg(extras.pArgs, extras.iArgCount) : nullptr; + break; + default: + return m_Data.ResolveRef(ref, m_Subject, m_iElementId, out); + } + + CScoreboardData::Value formatted = value ? *value : CScoreboardData::Value(); + out = TemplateValue(); + return CScoreboardData::FormatValue(ref.format, formatted) && ValueToTemplate(formatted, out); + } + + bool GetPlayerName(int idx, wchar_t *buf, int bufLen) override + { + return WritePlayerName(idx, buf, bufLen * static_cast(sizeof(wchar_t))); + } + + bool GetTeamName(int team, wchar_t *buf, int bufLen) override + { + return WriteTeamName(team, buf, bufLen * static_cast(sizeof(wchar_t))); + } + +private: + const CScoreboardData &m_Data; + CScoreboardData::Subject m_Subject; + int m_iElementId = -1; + const CScoreboardData::TemplateExtras *m_pExtras = nullptr; +}; + +CScoreboardData s_ScoreboardData; + +} + +//----------------------------------------------------- +// Value, Column, Element +//----------------------------------------------------- +int CScoreboardData::Value::GetClockMs() const +{ + if (!IsRunningClock()) + return iValue; + + double elapsed = std::max((static_cast(GetTime()) - flClockTime) * 1000.0, 0.0); + + if (IsEnumFlagSet(clockFlags, E_ClockFlags::Down)) + return static_cast(std::max(0.0, iValue - elapsed)); + + return static_cast(std::min(static_cast(INT_MAX), iValue + elapsed)); +} + +bool CScoreboardData::Value::GetNumber(int &out) const +{ + switch (type) + { + case E_ValueType::Int: + case E_ValueType::Progress: + out = iValue; + return true; + case E_ValueType::Clock: + out = GetClockSeconds(GetClockMs(), IsEnumFlagSet(clockFlags, E_ClockFlags::Down)); + return true; + default: + return false; + } +} + +void CScoreboardData::Value::ToString(wchar_t *buf, int bufSizeBytes) const +{ + int bufLen = bufSizeBytes / static_cast(sizeof(wchar_t)); + + switch (type) + { + case E_ValueType::Int: + V_snwprintf(buf, bufLen, L"%d", iValue); + break; + case E_ValueType::Text: + LocalizeString(szText, buf, bufSizeBytes); + break; + case E_ValueType::Icon: + GetIconName(*this, buf, bufSizeBytes); + break; + case E_ValueType::Progress: + if (iMax == 0) + V_snwprintf(buf, bufLen, L"%d", iValue); + else + V_snwprintf(buf, bufLen, L"%d/%d", iValue, iMax); + break; + case E_ValueType::Clock: + { + int seconds = 0; + GetNumber(seconds); + FormatTime(seconds, buf, bufLen); + break; + } + default: + buf[0] = L'\0'; + break; + } +} + +int CScoreboardData::Column::GetAlign() const +{ + int align = (static_cast(flags) >> 1) & 3; + return align == 3 ? 0 : align; +} + +bool CScoreboardData::Element::GetParam(E_Param param, int &value) const +{ + int id = static_cast(param); + + if (id < 0 || id > MAX_PARAM_ID || !(iParamMask & (1ULL << id))) + return false; + + value = params[id]; + return true; +} + +bool CScoreboardData::Element::GetSlotColor(int slot, unsigned char out[4]) const +{ + if (slot < 0 || slot >= MAX_COLOR_SLOTS || !(iColorMask & (1u << slot))) + return false; + + memcpy(out, colors[slot], sizeof(colors[slot])); + return true; +} + +//----------------------------------------------------- +// CScoreboardData +//----------------------------------------------------- +CScoreboardData &CScoreboardData::Get() +{ + return s_ScoreboardData; +} + +void CScoreboardData::Init() +{ + ::HookMessage(MSG_NAME, [](const char *pszName, int iSize, void *pbuf) { + return CScoreboardData::Get().MsgFunc_BhlScore(pszName, iSize, pbuf); + }); +} + +void CScoreboardData::VidInit() +{ + Clear(); + m_bWaitForReset = false; + std::fill(std::begin(m_bPlayerConnected), std::end(m_bPlayerConnected), false); +} + +void CScoreboardData::Frame() +{ + m_iFrame++; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + bool bIsConnected = GetPlayerInfo(i)->IsConnected(); + + if (m_bPlayerConnected[i] && !bIsConnected) + { + std::fill_n(m_PlayerValues[i], MAX_COLUMNS, Value()); + m_iSerial++; + } + + m_bPlayerConnected[i] = bIsConnected; + } +} + +bool CScoreboardData::IsCustomEnabled() +{ + return hud_scoreboard_custom.GetBool(); +} + +bool CScoreboardData::IsHudEnabled() +{ + return hud_server_elements.GetBool(); +} + +void CScoreboardData::SetClientCaps(bhl::E_ClientCaps caps) +{ + bool bHasScoreboard = IsEnumFlagSet(caps, bhl::E_ClientCaps::ScoreboardV1); + + if (bHasScoreboard == m_bAcceptMessages) + return; + + m_bAcceptMessages = bHasScoreboard; + m_bWaitForReset = bHasScoreboard; + + if (!bHasScoreboard) + Clear(); +} + +float CScoreboardData::GetTime() +{ + return gEngfuncs.GetClientTime(); +} + +const CScoreboardData::Column &CScoreboardData::GetColumn(int id) const +{ + if (id < 0 || id >= MAX_COLUMNS) + return s_EmptyColumn; + + return m_Columns[id]; +} + +int CScoreboardData::FindColumn(const char *key) const +{ + for (int i = 0; i < MAX_COLUMNS; i++) + { + if (m_Columns[i].bValid && !strcmp(m_Columns[i].szKey, key)) + return i; + } + + return -1; +} + +int CScoreboardData::FindPrimaryColumn() const +{ + for (int i = 0; i < MAX_COLUMNS; i++) + { + const Column &column = m_Columns[i]; + + if (column.bValid && column.IsPrimary() && !column.IsHidden() && !column.IsBuiltin() && !column.IsBadge()) + return i; + } + + return -1; +} + +int CScoreboardData::GetBadgeColumns(int host, int *ids, int maxIds) const +{ + const Column &hostColumn = GetColumn(host); + + if (!hostColumn.bValid || hostColumn.IsHidden() || hostColumn.IsBuiltin() || hostColumn.IsBadge()) + return 0; + + int count = 0; + + for (int i = 0; i < MAX_COLUMNS && count < maxIds; i++) + { + const Column &column = m_Columns[i]; + + if (column.bValid && column.IsBadge() && column.iHost == host && !column.IsHidden()) + ids[count++] = i; + } + + return count; +} + +const CScoreboardData::Value &CScoreboardData::GetGlobalValue(int col) const +{ + if (col < 0 || col >= MAX_COLUMNS) + return s_EmptyValue; + + return m_GlobalValues[col]; +} + +const CScoreboardData::Value &CScoreboardData::GetPlayerValue(int client, int col) const +{ + if (client < 1 || client > MAX_PLAYERS || col < 0 || col >= MAX_COLUMNS || !GetPlayerInfo(client)->IsConnected()) + return s_EmptyValue; + + return m_PlayerValues[client][col]; +} + +const CScoreboardData::Value &CScoreboardData::GetTeamValue(int team, int col) const +{ + if (!IsTeamNumber(team) || col < 0 || col >= MAX_COLUMNS) + return s_EmptyValue; + + return m_TeamValues[team][col]; +} + +const CScoreboardData::List *CScoreboardData::FindList(const char *key) const +{ + for (const List &list : m_Lists) + { + if (list.bValid && !strcmp(list.szKey, key)) + return &list; + } + + return nullptr; +} + +bool CScoreboardData::HasRunningClock() const +{ + if (m_iRunningClockSerial == m_iSerial) + return m_bHasRunningClock; + + auto fnHasClock = [](const Value *values, int count) { + return std::any_of(values, values + count, [](const Value &value) { return value.IsRunningClock(); }); + }; + + bool bHasClock = fnHasClock(m_GlobalValues, MAX_COLUMNS); + + for (int i = 1; i <= MAX_PLAYERS && !bHasClock; i++) + bHasClock = fnHasClock(m_PlayerValues[i], MAX_COLUMNS); + + for (int i = 1; i <= MAX_TEAMS && !bHasClock; i++) + bHasClock = fnHasClock(m_TeamValues[i], MAX_COLUMNS); + + for (int i = 0; i < MAX_LISTS && !bHasClock; i++) + bHasClock = fnHasClock(m_Lists[i].items, m_Lists[i].iCount); + + m_iRunningClockSerial = m_iSerial; + m_bHasRunningClock = bHasClock; + return bHasClock; +} + +//----------------------------------------------------- +// Order and places +//----------------------------------------------------- +bool CScoreboardData::IsParticipant(int client) +{ + CPlayerInfo *pi = GetPlayerInfoSafe(client); + return pi && !pi->IsSpectator(); +} + +int CScoreboardData::CompareEntities(const Subject &a, const Subject &b) const +{ + if (a == b) + return 0; + + for (int i = 0; i < m_iSortColumnCount; i++) + { + int col = m_SortColumns[i]; + int result = CompareValues(GetEntityValue(a, col), GetEntityValue(b, col), m_Columns[col].IsSortAscending()); + + if (result != 0) + return result; + } + + int fragsA, deathsA, fragsB, deathsB; + GetEntityScore(a, fragsA, deathsA); + GetEntityScore(b, fragsB, deathsB); + + if (fragsA != fragsB) + return fragsA > fragsB ? -1 : 1; + + if (deathsA != deathsB) + return deathsA < deathsB ? -1 : 1; + + // One of the two numbers is always 0 + return a.iPlayer + a.iTeam < b.iPlayer + b.iTeam ? -1 : 1; +} + +int CScoreboardData::GetPlace(const Subject &entity) const +{ + Subject entities[MAX_PLAYERS]; + int count = CollectEntities(entity.IsTeam(), entities); + int col = GetFirstSortColumn(); + + if (std::find(entities, entities + count, entity) == entities + count || (col != -1 && GetEntityValue(entity, col).IsEmpty())) + return 0; + + int frags, deaths; + GetEntityScore(entity, frags, deaths); + int place = 1; + + for (int i = 0; i < count; i++) + { + int otherFrags, otherDeaths; + GetEntityScore(entities[i], otherFrags, otherDeaths); + + if (col == -1 ? otherFrags > frags : CompareValues(GetEntityValue(entities[i], col), GetEntityValue(entity, col), m_Columns[col].IsSortAscending()) < 0) + place++; + } + + return place; +} + +int CScoreboardData::GetOrderedEntities(Subject *out, int max) const +{ + const Ranking &r = GetRanking(); + int count = max > 0 ? min(r.iCount, max) : 0; + std::copy(r.entities, r.entities + count, out); + return count; +} + +CScoreboardData::Subject CScoreboardData::GetRankedEntity(const Subject &subject) const +{ + if (subject.IsTeam() || !subject.iPlayer || !IsTeamMode()) + return subject; + + // A player without a team has no ranked entity in team mode + int team = GetPlayerTeamNumber(subject.iPlayer); + return { 0, IsTeamNumber(team) ? team : 0 }; +} + +CScoreboardData::Builtins CScoreboardData::GetBuiltins(const Subject &subject) const +{ + for (const BuiltinsCacheEntry &entry : m_BuiltinsCache) + { + if (entry.iFrame == m_iFrame && entry.iSerial == m_iSerial && entry.subject == subject) + return entry.builtins; + } + + BuiltinsCacheEntry &entry = m_BuiltinsCache[m_iNextBuiltinsCache]; + m_iNextBuiltinsCache = (m_iNextBuiltinsCache + 1) % BUILTINS_CACHE_SIZE; + entry.iFrame = m_iFrame; + entry.iSerial = m_iSerial; + entry.subject = subject; + entry.builtins = ComputeBuiltins(subject); + return entry.builtins; +} + +const CScoreboardData::Ranking &CScoreboardData::GetRanking() const +{ + Ranking &r = m_Ranking; + + if (r.iFrame == m_iFrame && r.iSerial == m_iSerial) + return r; + + r = Ranking(); + r.iFrame = m_iFrame; + r.iSerial = m_iSerial; + + int sortCol = GetFirstSortColumn(); + r.iCount = CollectEntities(true, r.entities); + + // 6.4: with sort keys the team cells decide, without them the players' teams + for (int i = 0; i < r.iCount && !r.bTeamMode; i++) + r.bTeamMode = sortCol == -1 || !GetTeamValue(r.entities[i].iTeam, sortCol).IsEmpty(); + + if (!r.bTeamMode) + r.iCount = CollectEntities(false, r.entities); + + if (sortCol != -1) + r.iSign = m_Columns[sortCol].IsSortAscending() ? -1 : 1; + + std::sort(r.entities, r.entities + r.iCount, [this](const Subject &a, const Subject &b) { + return CompareEntities(a, b) < 0; + }); + + for (int i = 0; i < r.iCount; i++) + r.bHasNumber[i] = GetEntityNumber(r.entities[i], sortCol, r.numbers[i]); + + if (r.iCount > 0) + r.firstRow = r.entities[0]; + + return r; +} + +CScoreboardData::Builtins CScoreboardData::ComputeBuiltins(const Subject &subject) const +{ + Builtins b; + const Ranking &r = GetRanking(); + int frags = 0; + int deaths = 0; + b.Set(E_Builtin::Total, r.iCount); + + if (subject.IsTeam() ? !IsTeamNumber(subject.iTeam) : !GetPlayerInfoSafe(subject.iPlayer)) + return b; + + GetEntityScore(subject, frags, deaths); + b.Set(E_Builtin::Frags, frags); + b.Set(E_Builtin::Deaths, deaths); + + int own = static_cast(std::find(r.entities, r.entities + r.iCount, GetRankedEntity(subject)) - r.entities); + + if (own == r.iCount || !r.bHasNumber[own]) + return b; + + b.Set(E_Builtin::Score, r.numbers[own]); + + long long ownNumber = static_cast(r.numbers[own]) * r.iSign; + long long best = ownNumber; + long long gap = 0; + long long lead = -1; + int rival = -1; + int place = 1; + bool bTied = false; + + for (int i = 0; i < r.iCount; i++) + { + if (i == own || !r.bHasNumber[i]) + continue; + + long long number = static_cast(r.numbers[i]) * r.iSign; + + if (number > best) + best = number; + + if (number > ownNumber) + { + place++; + + // Among equal gaps the last one in the scoreboard order: the row right above the subject + long long diff = number - ownNumber; + + if (rival == -1 || diff < gap || (diff == gap && CompareEntities(r.entities[i], r.entities[rival]) > 0)) + { + rival = i; + gap = diff; + } + } + else if (number == ownNumber) + { + bTied = true; + } + else if (lead == -1 || ownNumber - number < lead) + { + lead = ownNumber - number; + } + } + + b.Set(E_Builtin::Place, place); + b.Set(E_Builtin::Behind, ClampToInt(best - ownNumber)); + + // 0 no rivals, 1 a rival ahead, 2 tied for the first place, 3 leading + b.Set(E_Builtin::State, rival != -1 ? 1 : (bTied ? 2 : (lead != -1 ? 3 : 0))); + + if (rival != -1) + { + b.rival = r.entities[rival]; + b.Set(E_Builtin::Gap, ClampToInt(gap)); + b.Set(E_Builtin::Pass, ClampToInt(gap + 1)); + } + else if (bTied || lead != -1) + { + b.Set(E_Builtin::Lead, bTied ? 0 : ClampToInt(lead)); + } + + return b; +} + +bool CScoreboardData::GetEntityNumber(const Subject &entity, int sortCol, int &out) const +{ + if (sortCol != -1) + return GetEntityValue(entity, sortCol).GetNumber(out); + + int deaths; + GetEntityScore(entity, out, deaths); + return true; +} + +//----------------------------------------------------- +// HUD elements +//----------------------------------------------------- +const CScoreboardData::Element &CScoreboardData::GetElement(int id) const +{ + if (id < 0 || id >= MAX_ELEMENTS) + return s_EmptyElement; + + return m_Elements[id]; +} + +CScoreboardData::Subject CScoreboardData::GetViewerSubject() const +{ + CPlayerInfo *pi = GetThisPlayerInfo(); + int client = 0; + + // OBS_ROAMING and OBS_MAP_FREE look at nobody + if (g_iUser1 == OBS_NONE) + client = pi ? pi->GetIndex() : 0; + else if (g_iUser1 == OBS_CHASE_LOCKED || g_iUser1 == OBS_CHASE_FREE || g_iUser1 == OBS_IN_EYE || g_iUser1 == OBS_MAP_CHASE) + client = g_iUser2; + + return { IsParticipant(client) ? client : 0, 0 }; +} + +bool CScoreboardData::GetElementSubject(int id, Subject &out) const +{ + const Element &element = GetElement(id); + out = Subject(); + + if (!element.bValid) + return false; + + if (element.HasFlag(E_ElementFlags::Leader)) + { + out = GetFirstRow(); + return out.IsValid(); + } + + out = GetViewerSubject(); + return out.IsValid() || !element.HasFlag(E_ElementFlags::Subject); +} + +const CScoreboardData::Value &CScoreboardData::GetSubjectValue(const Subject &subject, int col) const +{ + const Value &value = GetPlayerValue(subject.iPlayer, col); + + if (!value.IsEmpty()) + return value; + + // The player's team cells, in team mode or not (8.10); a team subject starts here + const Value &teamValue = GetTeamValue(subject.iPlayer ? GetPlayerTeamNumber(subject.iPlayer) : subject.iTeam, col); + return teamValue.IsEmpty() ? GetGlobalValue(col) : teamValue; +} + +const TemplateRef *CScoreboardData::GetValueRef(int elementId) const +{ + const Element &element = GetElement(elementId); + + if (!element.bValid || !element.valueRef.IsSet() || element.valueRef.builtin == E_Builtin::Value) + return nullptr; + + return &element.valueRef; +} + +bool CScoreboardData::GetRefValue(const TemplateRef &ref, const Subject &subject, int elementId, Value &out) const +{ + const TemplateRef *valueRef = ref.builtin == E_Builtin::Value ? GetValueRef(elementId) : nullptr; + Subject target = ref.bFirstRow ? GetFirstRow() : subject; + out = Value(); + + if (!ref.IsSet() || ref.builtin == E_Builtin::Unknown || (ref.bFirstRow && !target.IsValid())) + return false; + + // One level only. With -1 a nested "@value" can't resolve, so this never recurses further. + if (valueRef) + { + GetRefValue(*valueRef, target, -1, out); + } + else if (ref.builtin == E_Builtin::None) + { + out = GetSubjectValue(target, FindColumn(ref.szKey)); + } + else + { + Builtins b = GetBuiltins(target); + out.type = b.Has(ref.builtin) ? E_ValueType::Int : E_ValueType::None; + out.iValue = b.Get(ref.builtin); + } + + return !out.IsEmpty() && FormatValue(ref.format, out); +} + +bool CScoreboardData::ResolveRef(const TemplateRef &ref, const Subject &subject, int elementId, TemplateValue &out) const +{ + const TemplateRef *valueRef = ref.builtin == E_Builtin::Value ? GetValueRef(elementId) : nullptr; + const TemplateRef &inner = valueRef ? *valueRef : ref; + Value value; + out = TemplateValue(); + + if (inner.builtin != E_Builtin::Name && inner.builtin != E_Builtin::Rival) + return GetRefValue(ref, subject, elementId, value) && ValueToTemplate(value, out); + + // Names are text, never a stored value or a number (8.10); the rival is nobody unless @state is 1 + Subject target = (ref.bFirstRow || inner.bFirstRow) ? GetFirstRow() : subject; + Subject named = inner.builtin == E_Builtin::Rival ? GetBuiltins(target).rival : target; + return ref.format == E_RefFormat::None && inner.format == E_RefFormat::None + && (named.IsTeam() ? WriteTeamName(named.iTeam, out.wszText, sizeof(out.wszText)) : WritePlayerName(named.iPlayer, out.wszText, sizeof(out.wszText))); +} + +bool CScoreboardData::GetElementValue(int id, const Subject &subject, Value &out) const +{ + return GetRefValue(GetElement(id).valueRef, subject, id, out); +} + +bool CScoreboardData::FormatValue(E_RefFormat format, Value &value) +{ + if (format == E_RefFormat::None) + return true; + + bool bIsProgress = value.type == E_ValueType::Progress; + int number = format == E_RefFormat::Cur ? value.iValue : (format == E_RefFormat::Max ? value.iMax : (value.iMax > value.iValue ? value.iMax - value.iValue : 0)); + value = Value(); + + if (!bIsProgress) + return false; + + value.type = E_ValueType::Int; + value.iValue = number; + return true; +} + +int CScoreboardData::GetElementVariant(int id, const Subject &subject) const +{ + const Element &element = GetElement(id); + + if (!element.bValid) + return -1; + + switch (element.kind) + { + case E_ElementKind::Icon: + case E_ElementKind::Meter: + return 0; + case E_ElementKind::Text: + break; + default: + return -1; + } + + int variant = 0; + + if (element.selectRef.IsSet()) + { + Value value; + + if (!GetRefValue(element.selectRef, subject, id, value) || !value.GetNumber(variant)) + return -1; + } + + return GetTemplate(id, variant) ? variant : -1; +} + +bool CScoreboardData::GetElementText(int id, const Subject &subject, wchar_t *buf, int bufSizeBytes) const +{ + buf[0] = L'\0'; + int variant = GetElementVariant(id, subject); + const CTemplate *tpl = GetTemplate(id, variant); + + // A Meter without variant 0 shows the default counter (8.7) + if (!tpl && variant >= 0 && m_Elements[id].kind == E_ElementKind::Meter) + tpl = &GetMeterCounterTemplate(); + + return tpl && EvaluateTemplate(*tpl, subject, id, buf, bufSizeBytes); +} + +const CTemplate *CScoreboardData::GetTemplate(int id, int variant) const +{ + if (id < 0 || id >= MAX_ELEMENTS || variant < 0 || variant >= MAX_VARIANTS || !m_Templates[id][variant].IsSet()) + return nullptr; + + return &m_Templates[id][variant]; +} + +bool CScoreboardData::EvaluateTemplate(const CTemplate &tpl, const Subject &subject, int elementId, wchar_t *buf, int bufSizeBytes, const TemplateExtras *pExtras) const +{ + CStoreTemplateContext ctx(*this, subject, elementId, pExtras); + return tpl.Evaluate(ctx, buf, bufSizeBytes / static_cast(sizeof(wchar_t))); +} + +int CScoreboardData::GetHudLines(int elementId, const HudLine **out) const +{ + int count = 0; + + for (int i = 0; i < MAX_HUD_LINES; i++) + { + const HudLine &line = m_HudLines[(m_iNextHudLine + i) % MAX_HUD_LINES]; + + if (line.iElement == elementId) + out[count++] = &line; + } + + return count; +} + +int CScoreboardData::GetBannerRow(E_Place place, wchar_t *buf, int bufSizeBytes) const +{ + buf[0] = L'\0'; + + for (int i = 0; i < MAX_ELEMENTS; i++) + { + const Element &element = m_Elements[i]; + Subject subject; + + if (element.kind != E_ElementKind::Text || element.place != place || !IsElementVisible(i) || !GetElementSubject(i, subject)) + continue; + + if (GetElementText(i, subject, buf, bufSizeBytes)) + return i; + } + + return -1; +} + +//----------------------------------------------------- +// Text helpers +//----------------------------------------------------- +void CScoreboardData::LocalizeString(const char *str, wchar_t *buf, int bufSizeBytes) +{ + if (IsClientToken(str)) + { + const wchar_t *localized = g_pVGuiLocalize->Find(str); + + if (localized) + { + V_wcsncpy(buf, localized, bufSizeBytes); + return; + } + + str++; + } + + Q_UTF8ToWString(str, buf, bufSizeBytes, STRINGCONVERT_REPLACE); +} + +//----------------------------------------------------- +// Messages +//----------------------------------------------------- +void CScoreboardData::Clear() +{ + m_bConfigReceived = false; + m_ConfigFlags = E_ConfigFlags::None; + m_szTitle[0] = '\0'; + m_szTag[0] = '\0'; + + std::fill(std::begin(m_Columns), std::end(m_Columns), Column()); + std::fill(std::begin(m_GlobalValues), std::end(m_GlobalValues), Value()); + + for (Value *values : m_PlayerValues) + std::fill_n(values, MAX_COLUMNS, Value()); + + for (Value *values : m_TeamValues) + std::fill_n(values, MAX_COLUMNS, Value()); + + std::fill(std::begin(m_Lists), std::end(m_Lists), List()); + + for (int i = 0; i < MAX_ELEMENTS; i++) + RemoveElement(i); + + m_iVisibleMask = 0; + m_iHiddenStdParts = 0; + m_iSortColumnCount = 0; + m_iSerial++; + m_iSchemaSerial++; + m_iResetCount++; +} + +void CScoreboardData::UpdateSortColumns() +{ + m_iSortColumnCount = 0; + + for (int i = 0; i < MAX_COLUMNS; i++) + { + const Column &column = m_Columns[i]; + + if (column.bValid && !column.IsBuiltin() && !column.IsBadge() && column.GetSortPriority() > 0) + m_SortColumns[m_iSortColumnCount++] = i; + } + + std::stable_sort(m_SortColumns, m_SortColumns + m_iSortColumnCount, [this](int a, int b) { + return m_Columns[a].GetSortPriority() < m_Columns[b].GetSortPriority(); + }); +} + +CScoreboardData::Value *CScoreboardData::GetTargetValues(int target) +{ + if (target == TARGET_GLOBAL) + return m_GlobalValues; + + if (target >= TARGET_PLAYER_FIRST && target <= TARGET_PLAYER_LAST) + return m_PlayerValues[target - TARGET_PLAYER_FIRST + 1]; + + if (target >= TARGET_TEAM_FIRST && target <= TARGET_TEAM_LAST) + return m_TeamValues[target - TARGET_TEAM_BASE]; + + return nullptr; +} + +void CScoreboardData::RemoveElement(int id) +{ + m_Elements[id] = Element(); + m_iElementRemovals[id]++; + + for (CTemplate &tpl : m_Templates[id]) + tpl.Clear(); + + for (HudLine &line : m_HudLines) + { + if (line.iElement == id) + line = HudLine(); + } +} + +int CScoreboardData::MsgFunc_BhlScore(const char *pszName, int iSize, void *pbuf) +{ + if (!m_bAcceptMessages || !pbuf) + return 1; + + CMsgReader reader(pbuf, iSize); + int op = 0; + + if (!reader.ReadByte(op)) + return 1; + + // After ScoreboardV1 came back only a full sync, which starts with Reset, may fill the store + if (m_bWaitForReset && op != static_cast(E_Op::Reset)) + return 1; + + // Indexed by E_Op; other ops are reserved and ignored + using FnRead = void (CScoreboardData::*)(CMsgReader &reader); + static constexpr FnRead s_Readers[] = { + &CScoreboardData::ReadReset, &CScoreboardData::ReadConfig, &CScoreboardData::ReadColumn, + &CScoreboardData::ReadValues, &CScoreboardData::ReadList, &CScoreboardData::ReadElement, + &CScoreboardData::ReadTemplate, &CScoreboardData::ReadHudState, &CScoreboardData::ReadEvent + }; + static_assert(std::size(s_Readers) == static_cast(E_Op::Event) + 1, "every op needs a reader"); + + if (op < static_cast(std::size(s_Readers))) + (this->*s_Readers[op])(reader); + + return 1; +} + +void CScoreboardData::ReadReset(CMsgReader &) +{ + Clear(); + m_bWaitForReset = false; +} + +void CScoreboardData::ReadConfig(CMsgReader &reader) +{ + int flags = 0; + + if (!reader.ReadWord(flags)) + return; + + // A missing title or tag is "" + reader.ReadString(m_szTitle, sizeof(m_szTitle)); + reader.ReadString(m_szTag, sizeof(m_szTag)); + m_bConfigReceived = true; + m_ConfigFlags = static_cast(flags & static_cast(E_ConfigFlags::All)); + m_iSerial++; + m_iSchemaSerial++; +} + +void CScoreboardData::ReadColumn(CMsgReader &reader) +{ + int id = 0; + int display = 0; + int flags = 0; + int host = NO_ID; + Column column; + + if (!reader.ReadByte(id) || !reader.ReadByte(display) || !reader.ReadWord(flags) || !reader.ReadByte(column.iWidth) || !reader.ReadByte(column.iSort) + || !reader.ReadString(column.szKey, sizeof(column.szKey)) || id >= MAX_COLUMNS) + return; + + // A missing title is "", a missing host is NO_ID + reader.ReadString(column.szTitle, sizeof(column.szTitle)); + reader.ReadByte(host); + + column.bValid = true; + column.display = display <= static_cast(E_Display::Badge) ? static_cast(display) : E_Display::Text; + column.flags = static_cast(flags & static_cast(E_ColumnFlags::All)); + column.iHost = column.IsBadge() && host < MAX_COLUMNS ? host : -1; + m_Columns[id] = column; + UpdateSortColumns(); + m_iSerial++; + m_iSchemaSerial++; +} + +bool CScoreboardData::ReadValue(CMsgReader &reader, Value &value, int &type) +{ + int len = 0; + value = Value(); + + if (!reader.ReadByte(type) || !reader.ReadByte(len) || len > reader.GetRemaining()) + return false; + + CMsgReader payload = reader.ReadBlock(len); + bool bValid = false; + + switch (static_cast(type)) + { + case E_ValueType::Int: + bValid = (len == 1 || len == 2 || len == 4) && payload.ReadInt(value.iValue, len, true); + break; + case E_ValueType::Text: + bValid = len <= MAX_TEXT_LEN + 1 && payload.ReadString(value.szText, sizeof(value.szText)); + break; + case E_ValueType::Icon: + bValid = len <= 2 * (MAX_TEXT_LEN + 1) && payload.ReadString(value.szSprite, sizeof(value.szSprite)) && payload.ReadString(value.szText, sizeof(value.szText)); + break; + case E_ValueType::Progress: + bValid = (len == 2 || len == 4) && payload.ReadInt(value.iValue, len / 2, false) && payload.ReadInt(value.iMax, len / 2, false); + break; + case E_ValueType::Clock: + { + int flags = 0; + bValid = len == CLOCK_VALUE_LEN && payload.ReadLong(value.iValue) && payload.ReadByte(flags); + value.clockFlags = static_cast(flags & static_cast(E_ClockFlags::All)); + value.flClockTime = GetTime(); + break; + } + default: + break; + } + + if (bValid) + value.type = static_cast(type); + else + value = Value(); + + return true; +} + +void CScoreboardData::ReadValues(CMsgReader &reader) +{ + int target = 0; + + if (!reader.ReadByte(target)) + return; + + Value *values = GetTargetValues(target); + int col = 0; + int type = 0; + Value value; + + // A message that ends inside a cell keeps the cells already applied + while (values && reader.ReadByte(col) && ReadValue(reader, value, type)) + { + if (col == ALL_COLUMNS && type == static_cast(E_ValueType::None)) + { + std::fill_n(values, MAX_COLUMNS, Value()); + m_iSerial++; + } + else if (col < MAX_COLUMNS) + { + values[col] = value; + m_iSerial++; + } + } +} + +void CScoreboardData::ReadList(CMsgReader &reader) +{ + int id = 0; + int total = 0; + int start = 0; + char key[MAX_KEY_LEN + 1]; + + if (!reader.ReadByte(id) || !reader.ReadByte(total) || !reader.ReadByte(start) || !reader.ReadString(key, sizeof(key)) || id >= MAX_LISTS) + return; + + List &list = m_Lists[id]; + m_iSerial++; + + if (total == 0) + { + list = List(); + return; + } + + if (!list.bValid || strcmp(list.szKey, key)) + { + list = List(); + list.bValid = true; + V_strcpy_safe(list.szKey, key); + } + + total = min(total, MAX_LIST_ITEMS); + + for (int i = total; i < list.iCount; i++) + list.items[i] = Value(); + + list.iCount = total; + + for (int i = start; reader.GetRemaining() > 0; i++) + { + int type = 0; + Value value; + + if (!ReadValue(reader, value, type)) + break; + + if (i < total) + list.items[i] = value; + } +} + +void CScoreboardData::ReadElement(CMsgReader &reader) +{ + int id = 0; + int kind = 0; + + if (!reader.ReadByte(id) || !reader.ReadByte(kind)) + return; + + // None or an unknown kind removes + if (!IsKnownKind(kind)) + { + if (id < MAX_ELEMENTS) + { + RemoveElement(id); + m_iSerial++; + } + + return; + } + + Element element; + int flags = 0; + int align = 0; + int place = 0; + int parent = 0; + int font = 0; + + if (id >= MAX_ELEMENTS || !reader.ReadWord(flags) || !reader.ReadShort(element.x) || !reader.ReadShort(element.y) || !reader.ReadByte(align) + || !reader.ReadByte(place) || !reader.ReadByte(parent) || !reader.ReadByte(element.iGap) || !reader.ReadByte(element.r) + || !reader.ReadByte(element.g) || !reader.ReadByte(element.b) || !reader.ReadByte(element.a) || !reader.ReadByte(font)) + return; + + element.bValid = true; + element.kind = static_cast(kind); + element.flags = static_cast(flags & static_cast(E_ElementFlags::All)); + element.hAlign = align & 3; + element.vAlign = (align >> 2) & 3; + element.place = place <= static_cast(E_Place::ParentRight) ? static_cast(place) : E_Place::Screen; + element.iParent = IsParentPlace(element.place) && parent < MAX_ELEMENTS ? parent : -1; + element.font = font < FONT_COUNT ? static_cast(font) : E_Font::Text; + + // Refs are parsed in full, so a ref longer than MAX_REF_LEN stays invalid + char str[MAX_MSG_SIZE + 1]; + reader.ReadString(str, sizeof(str), false); + ParseRef(str, element.selectRef); + + reader.ReadString(str, sizeof(str), false); + ParseRef(str, element.valueRef); + + // A list key that no list can have counts as no list + reader.ReadString(str, sizeof(str), false); + + if (strlen(str) <= static_cast(MAX_KEY_LEN)) + V_strcpy_safe(element.szList, str); + + // Every param is read, so that the color block after them is found + int count = 0; + reader.ReadByte(count); + + for (int i = 0; i < count && reader.GetRemaining() >= 3; i++) + { + int param = 0; + int value = 0; + reader.ReadByte(param); + reader.ReadShort(value); + + const ParamInfo *info = FindParamInfo(element.kind, param); + + if (!info) + continue; + + element.params[param] = clamp(value, info->iMin, info->iMax); + element.iParamMask |= 1ULL << param; + } + + int colors = 0; + reader.ReadByte(colors); + + for (int i = 0; i < colors && reader.GetRemaining() >= 5; i++) + { + int slot = 0; + int rgba[4] = {}; + reader.ReadByte(slot); + + for (int &component : rgba) + reader.ReadByte(component); + + if (slot >= MAX_COLOR_SLOTS) + continue; + + for (int j = 0; j < 4; j++) + element.colors[slot][j] = static_cast(rgba[j]); + + element.iColorMask |= 1u << slot; + } + + m_Elements[id] = element; + m_iSerial++; +} + +void CScoreboardData::ReadTemplate(CMsgReader &reader) +{ + int id = 0; + int variant = 0; + char text[MAX_MSG_SIZE + 1]; + + if (!reader.ReadByte(id) || !reader.ReadByte(variant) || !reader.ReadString(text, sizeof(text), false) || id >= MAX_ELEMENTS + || variant >= MAX_VARIANTS || !m_Elements[id].bValid) + return; + + CTemplate &tpl = m_Templates[id][variant]; + const wchar_t *localized = IsClientToken(text) ? g_pVGuiLocalize->Find(text) : nullptr; + + // The text of a client token is parsed, never looked up again (8.10) + if (localized) + tpl.Parse(localized); + else if (text[0]) + tpl.Parse(text); + else + tpl.Clear(); + + m_iSerial++; +} + +void CScoreboardData::ReadHudState(CMsgReader &reader) +{ + int visible = 0; + int hide = 0; + + if (!reader.ReadLong(visible)) + return; + + reader.ReadWord(hide); + m_iVisibleMask = static_cast(visible); + m_iHiddenStdParts = static_cast(hide) & static_cast(E_HudStd::All); + m_iSerial++; +} + +void CScoreboardData::ReadEvent(CMsgReader &reader) +{ + int id = 0; + int variant = 0; + int life = 0; + int count = 0; + + if (!reader.ReadByte(id) || !reader.ReadByte(variant) || !reader.ReadWord(life) || !reader.ReadByte(count)) + return; + + const CTemplate *tpl = GetTemplate(id, variant); + + if (!tpl || m_Elements[id].kind != E_ElementKind::Feed) + return; + + // An arg of an unknown type keeps its position as an empty value + Value args[MAX_EVENT_ARGS]; + int argCount = min(count, MAX_EVENT_ARGS); + + for (int i = 0; i < argCount; i++) + { + int type = 0; + + if (!ReadValue(reader, args[i], type)) + return; + } + + TemplateExtras extras; + extras.pArgs = args; + extras.iArgCount = argCount; + const Value *icon = FindIconArg(args, argCount); + + HudLine line; + Subject subject; + GetElementSubject(id, subject); + + if (!EvaluateTemplate(*tpl, subject, id, line.wszText, sizeof(line.wszText), &extras) && (!icon || !icon->szSprite[0])) + return; + + line.iElement = id; + line.iSeq = ++m_iLastHudLineSeq; + line.iVariant = variant; + line.flTime = GetTime(); + line.flLife = life / 1000.0f; + + if (icon) + line.icon = *icon; + + m_HudLines[m_iNextHudLine] = line; + m_iNextHudLine = (m_iNextHudLine + 1) % MAX_HUD_LINES; +} diff --git a/src/game/client/scoreboard_data.h b/src/game/client/scoreboard_data.h new file mode 100644 index 00000000..fc771016 --- /dev/null +++ b/src/game/client/scoreboard_data.h @@ -0,0 +1,535 @@ +#ifndef SCOREBOARD_DATA_H +#define SCOREBOARD_DATA_H +#include +#include +#include +#include "cdll_dll.h" +#include "scoreboard_template.h" + +/** + * Client store of the scoreboard and HUD extension (docs/scoreboard-protocol.md, 6.1). + * Receives "BhlScore" messages and keeps the schema, cells, lists, elements, templates and the HUD state. + * Computes the order, places, team mode, subjects and built-in values, and evaluates templates. + * Read by the scoreboard, hud_scores, HudServerPanel and the standard HUD parts. + * + * Text buffers of this class are sized in bytes (bufSizeBytes), like Q_UTF8ToWString. + */ +class CScoreboardData +{ +public: + struct Value + { + bhl::sb::E_ValueType type = bhl::sb::E_ValueType::None; + int iValue = 0; //!< Int value, Progress cur, Clock ms when it arrived + int iMax = 0; //!< Progress max + bhl::sb::E_ClockFlags clockFlags = bhl::sb::E_ClockFlags::None; + float flClockTime = 0; //!< GetTime() when a Clock arrived + char szText[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Text value or Icon text + char szSprite[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Icon sprite name from hud.txt + + bool IsEmpty() const { return type == bhl::sb::E_ValueType::None; } + + bool IsRunningClock() const { return type == bhl::sb::E_ValueType::Clock && IsEnumFlagSet(clockFlags, bhl::sb::E_ClockFlags::Run); } + + //! Current value of a Clock in ms (4.3): runs from flClockTime, a countdown stops at 0 + int GetClockMs() const; + + //! Number of the value (4.3): Int, Progress cur or Clock seconds. False for other types. + bool GetNumber(int &out) const; + + /** + * Text of the value (8.10, "Values are written as"): the number, the localized text, + * the icon name (10.3), "cur/max" or "cur" if max is 0, a Clock as m:ss. "" for None. + */ + void ToString(wchar_t *buf, int bufSizeBytes) const; + }; + + struct Column + { + bool bValid = false; + bhl::sb::E_Display display = bhl::sb::E_Display::Text; //!< Unknown displays are Text + bhl::sb::E_ColumnFlags flags = bhl::sb::E_ColumnFlags::None; + int iWidth = 0; //!< Proportional units, 0 for the default + int iSort = 0; //!< Raw sort byte + int iHost = -1; //!< Badge: id of the column the badge follows, -1 if none + char szKey[bhl::sb::MAX_KEY_LEN + 1] = {}; + char szTitle[bhl::sb::MAX_COLUMN_TITLE_LEN + 1] = {}; + + int GetSortPriority() const { return iSort & bhl::sb::SORT_PRIORITY_MASK; } + bool IsSortAscending() const { return (iSort & bhl::sb::SORT_ASC) != 0; } + bool IsHidden() const { return IsEnumFlagSet(flags, bhl::sb::E_ColumnFlags::Hidden); } + bool IsPrimary() const { return IsEnumFlagSet(flags, bhl::sb::E_ColumnFlags::Primary); } + bool IsMarkLast() const { return IsEnumFlagSet(flags, bhl::sb::E_ColumnFlags::MarkLast); } + bool IsBuiltin() const { return display == bhl::sb::E_Display::Builtin; } + bool IsBadge() const { return display == bhl::sb::E_Display::Badge; } + + //! Returns 0 (left), 1 (center) or 2 (right); 3 is left + int GetAlign() const; + }; + + struct List + { + bool bValid = false; + char szKey[bhl::sb::MAX_KEY_LEN + 1] = {}; + int iCount = 0; + Value items[bhl::sb::MAX_LIST_ITEMS]; + }; + + //! Definition of a HUD element (4.3). Templates are kept apart: an Element never changes them. + struct Element + { + bool bValid = false; + bhl::sb::E_ElementKind kind = bhl::sb::E_ElementKind::None; + bhl::sb::E_ElementFlags flags = bhl::sb::E_ElementFlags::None; + int x = 0; //!< 1/8192 of the screen width, bhl::sb::POS_CENTER is the center + int y = 0; //!< 1/8192 of the screen height + int hAlign = bhl::sb::ANCHOR_AUTO; + int vAlign = bhl::sb::ANCHOR_AUTO; + bhl::sb::E_Place place = bhl::sb::E_Place::Screen; //!< Unknown places are Screen + int iParent = -1; //!< Element id for the parent places, -1 if none + int iGap = 0; //!< Proportional units + int r = 255, g = 255, b = 255, a = 255; + bhl::sb::E_Font font = bhl::sb::E_Font::Text; //!< Unknown fonts are Text + char szList[bhl::sb::MAX_KEY_LEN + 1] = {}; + bhl::sb::TemplateRef selectRef; //!< Parsed Element.select, not set if it is "" + bhl::sb::TemplateRef valueRef; //!< Parsed Element.value, not set if it is "" + uint64_t iParamMask = 0; //!< Bit per param id that the server sent + int params[bhl::sb::MAX_PARAM_ID + 1] = {}; //!< Clamped values by param id + unsigned int iColorMask = 0; //!< Bit per color slot that the server sent + unsigned char colors[bhl::sb::MAX_COLOR_SLOTS][4] = {}; //!< rgba by slot + + bool HasFlag(bhl::sb::E_ElementFlags flag) const { return IsEnumFlagSet(flags, flag); } + + //! Returns true and the value if the server sent the param, otherwise value is left as it is: HudServerPanel passes in its default from HudLayoutBase.res + bool GetParam(bhl::sb::E_Param param, int &value) const; + + //! Returns true and the rgba if the server sent the color slot (4.3, 8.5) + bool GetSlotColor(int slot, unsigned char out[4]) const; + }; + + /** + * Whose data an element shows (8.2): a player, a team (the first row in team mode) or nobody. + * Also used for the ranked entities of 6.4: a participant or a team. + */ + struct Subject + { + int iPlayer = 0; //!< Player index, 0 for a team or nobody + int iTeam = 0; //!< Team number of a team subject, 0 otherwise + + bool IsValid() const { return iPlayer != 0 || iTeam != 0; } + bool IsTeam() const { return iTeam != 0; } + bool operator==(const Subject &other) const { return iPlayer == other.iPlayer && iTeam == other.iTeam; } + bool operator!=(const Subject &other) const { return !(*this == other); } + }; + + //! Built-in numbers of a subject (8.11) by E_Builtin, computed once per frame. A missing one has no bit in iMask. + struct Builtins + { + int numbers[static_cast(bhl::sb::E_Builtin::Deaths) + 1] = {}; + unsigned int iMask = 0; + Subject rival; //!< Nearest rival ahead when @state is 1: @rival + + void Set(bhl::sb::E_Builtin builtin, int value) + { + numbers[static_cast(builtin)] = value; + iMask |= 1u << static_cast(builtin); + } + + bool Has(bhl::sb::E_Builtin builtin) const { return ((iMask >> static_cast(builtin)) & 1u) != 0; } + + //! The number, 0 if it is missing + int Get(bhl::sb::E_Builtin builtin) const { return Has(builtin) ? numbers[static_cast(builtin)] : 0; } + }; + + //! Values of the built-ins that only some templates have (8.10): Board rows and events + struct TemplateExtras + { + const Value *pItem = nullptr; //!< @item + int iIndex = 0; //!< @index when > 0 + const Value *pValue = nullptr; //!< Replaces the value that @value reads, with the format of the element's value ref applied (FormatValue) + const Value *pArgs = nullptr; //!< @a-@d by position, @icon is the first Icon + int iArgCount = 0; + }; + + //! Feed lines kept over all elements + static constexpr int MAX_HUD_LINES = 32; + + //! A line of a Feed element from an Event message (4.3) + struct HudLine + { + int iElement = -1; //!< -1 for an unused slot + int iSeq = 0; //!< Grows with every line over all elements and is never reset: the announcer schedule of HudServerPanel + int iVariant = 0; + float flTime = 0; //!< GetTime() when it arrived + float flLife = 0; //!< Seconds, 0 for the element's life_ms + Value icon; //!< The first Icon arg, empty without one + wchar_t wszText[bhl::sb::TEMPLATE_BUF_LEN] = {}; //!< The template evaluated on arrival + }; + + static CScoreboardData &Get(); + + CScoreboardData() = default; + CScoreboardData(const CScoreboardData &) = delete; + CScoreboardData &operator=(const CScoreboardData &) = delete; + + //! Hooks BhlScore. Called from CHud::Init. + void Init(); + + //! Clears everything and ends a wait for Reset (SetClientCaps). Called from CHud::VidInit. + void VidInit(); + + //! Clears cells of players that left, starts a new frame for the caches. Called from CHud::Frame. + void Frame(); + + //---------------------------------------------------------------------------------------------------- + // Client settings and caps (3.2) + //---------------------------------------------------------------------------------------------------- + + //! hud_scoreboard_custom: show the custom scoreboard when the server sends one + static bool IsCustomEnabled(); + + //! hud_server_elements: draw HUD elements and honour hidden standard parts + static bool IsHudEnabled(); + + /** + * Called by CHud::UpdateCapsUserinfo with the caps it writes to _bhl. + * When ScoreboardV1 is cleared the store is cleared as on Reset, and messages are dropped + * while it stays cleared. Before the first call the store accepts messages. + * + * After ScoreboardV1 comes back, every message except Reset is dropped until a Reset arrives + * or VidInit runs. A full sync always starts with Reset, and a server that missed the toggle + * (a Query source re-reads _bhl only every 10 s) must not fill the empty store with plain deltas. + */ + void SetClientCaps(bhl::E_ClientCaps caps); + + //! Client time in seconds that Clock values run on + static float GetTime(); + + //---------------------------------------------------------------------------------------------------- + // Schema (4.3, 6.2) + //---------------------------------------------------------------------------------------------------- + + //! True when a Config arrived after the last Reset or VidInit and IsCustomEnabled(): the custom scoreboard is shown + bool IsActive() const { return m_bConfigReceived && IsCustomEnabled(); } + + //! True when IsActive() and the config hides the standard column + bool IsStdColumnHidden(bhl::sb::E_ConfigFlags flag) const { return IsActive() && IsEnumFlagSet(m_ConfigFlags, flag); } + + const char *GetTitle() const { return m_szTitle; } + const char *GetTag() const { return m_szTag; } + + //! @param id Column id [0; MAX_COLUMNS); other ids give an invalid column + const Column &GetColumn(int id) const; + + //! Returns column id or -1 + int FindColumn(const char *key) const; + + //! Returns id of the first Primary column (lowest id) that is not Hidden, Builtin or Badge, or -1 (6.5) + int FindPrimaryColumn() const; + + /** + * Badge columns drawn after the cells of host, in id order (6.7). Leaves out Hidden badges. + * Returns 0 if host is missing, hidden, Builtin or a Badge column. + * @return Number of ids written + */ + int GetBadgeColumns(int host, int *ids, int maxIds) const; + + //! Returns id of the first sort key column or -1 + int GetFirstSortColumn() const { return m_iSortColumnCount > 0 ? m_SortColumns[0] : -1; } + + //---------------------------------------------------------------------------------------------------- + // Cells and lists + //---------------------------------------------------------------------------------------------------- + + //! Values of absent or disconnected targets are empty + const Value &GetGlobalValue(int col) const; + const Value &GetPlayerValue(int client, int col) const; + const Value &GetTeamValue(int team, int col) const; + + //! Returns nullptr if there is no such list + const List *FindList(const char *key) const; + + //! True if a cell or list item holds a running Clock + bool HasRunningClock() const; + + //---------------------------------------------------------------------------------------------------- + // Order and places (6.4) + //---------------------------------------------------------------------------------------------------- + + //! Connected and not a spectator; bots count + static bool IsParticipant(int client); + + /** + * Full order of players: the sort keys, then frags descending, deaths ascending, then the index. + * Empty cells go after filled ones. + * @return < 0 if a goes before b, > 0 if after; 0 only for a == b + */ + int ComparePlayers(int a, int b) const { return CompareEntities({ a, 0 }, { b, 0 }); } + + //! Full order of teams by team cells, then team frags descending, deaths ascending, then the number + int CompareTeams(int a, int b) const { return CompareEntities({ 0, a }, { 0, b }); } + + /** + * Place in the rank column among participants: by the first sort key only, equal values share + * a place (1, 1, 3); without sort keys by frags. 0 if the player is not a participant or his + * first-key cell is empty. + */ + int GetPlayerPlace(int client) const { return GetPlace({ client, 0 }); } + + //! Place in the rank column among teams with participants, the same way + int GetTeamPlace(int team) const { return GetPlace({ 0, team }); } + + //! True if the ranked entities are the teams with participants (6.4) + bool IsTeamMode() const { return GetRanking().bTeamMode; } + + //! First row of the order: a team in team mode, otherwise a participant; invalid without participants + Subject GetFirstRow() const { return GetRanking().firstRow; } + + /** + * The ranked entities (6.4) in the scoreboard order: teams with participants in team mode, otherwise participants. + * @return Number of entities written, at most max + */ + int GetOrderedEntities(Subject *out, int max) const; + + //! The ranked entity of a subject: his team in team mode, otherwise the subject itself + Subject GetRankedEntity(const Subject &subject) const; + + //! Built-in values of a subject, computed once per frame for each subject (8.11) + Builtins GetBuiltins(const Subject &subject) const; + + //---------------------------------------------------------------------------------------------------- + // HUD elements (8) + //---------------------------------------------------------------------------------------------------- + + //! @param id Element id [0; MAX_ELEMENTS); other ids give an invalid element + const Element &GetElement(int id) const; + + //! Raw HudState.visible: bit per element id + unsigned int GetVisibleMask() const { return m_iVisibleMask; } + + //! True if the element is defined and its bit is set in HudState.visible + bool IsElementVisible(int id) const { return GetElement(id).bValid && (m_iVisibleMask & (1u << id)); } + + //! True if the server hides the standard HUD part and IsHudEnabled() (8.12) + bool IsStdPartHidden(bhl::sb::E_HudStd part) const { return (m_iHiddenStdParts & static_cast(part)) && IsHudEnabled(); } + + //! Subject of the viewer (8.2): the local player, the observed player or nobody + Subject GetViewerSubject() const; + + /** + * Subject of an element: the first row with Leader, otherwise the viewer's subject. + * @return false if the element must not be drawn: Subject without a subject, Leader without + * participants (8.3 rule 4, 6.8) + */ + bool GetElementSubject(int id, Subject &out) const; + + /** + * The ITemplateContext::GetValue of the store, for a subject; "@value" reads the value ref of element + * elementId (-1 for none). A cell of the player, then of his team, then global (a team subject starts + * with its team cells, nobody reads global cells only), or a built-in value; built-in numbers come as Int. + */ + bool ResolveRef(const bhl::sb::TemplateRef &ref, const Subject &subject, int elementId, bhl::sb::TemplateValue &out) const; + + //! A ref as a stored value: ResolveRef without names, which are missing here + bool GetRefValue(const bhl::sb::TemplateRef &ref, const Subject &subject, int elementId, Value &out) const; + + /** + * Value of the element's value ref for drawing a Meter, an Icon or a Strip. + * Returns the stored value unchanged; only the ref's own cur/max/left format is applied, which makes an Int. + * A Meter needs a Progress, an Icon needs an Icon. A Strip takes its position with Value::GetNumber + * and, without a list or with a list that doesn't exist, its count from Progress iMax. + * Built-in numbers come as Int. @name, @rival and a value ref that is itself "@value" are missing. + * @return false if the value is missing + */ + bool GetElementValue(int id, const Subject &subject, Value &out) const; + + /** + * Applies the cur, max or left format of a ref to a value as GetElementValue does: a Progress becomes an Int, + * any other value becomes empty. None leaves the value as it is. + * @return false if the format emptied the value + */ + static bool FormatValue(bhl::sb::E_RefFormat format, Value &value); + + /** + * Variant of an element (8.10, Variants): Text by the number of select as GetRefValue gives it + * ("" is 0), Icon and Meter 0, Strip none. + * @return 0-7, or -1 if the select value is missing or out of range, or the variant has no template + */ + int GetElementVariant(int id, const Subject &subject) const; + + /** + * Text of an element for a subject: Text its chosen variant, Icon variant 0, Meter its counter + * (variant 0, or "{@value:cur} / {@value:max}" when variant 0 has no template); Strip none. + * @return false if the text is empty (buf is "") + */ + bool GetElementText(int id, const Subject &subject, wchar_t *buf, int bufSizeBytes) const; + + //! Template of a variant, nullptr if the variant has no text + const bhl::sb::CTemplate *GetTemplate(int id, int variant) const; + + /** + * Evaluates any template for a subject in the context of element elementId (-1 for none). + * @param pExtras @item, @index, @a-@d, @icon and the value of @value of a Board row or an event; refs with '^' resolve without them + */ + bool EvaluateTemplate(const bhl::sb::CTemplate &tpl, const Subject &subject, int elementId, wchar_t *buf, int bufSizeBytes, const TemplateExtras *pExtras = nullptr) const; + + /** + * Lines of a Feed element that are kept, oldest first, up to MAX_HUD_LINES. + * Lines don't expire here: HudServerPanel drops them by their life. The next message may replace them. + * @return Number of lines written + */ + int GetHudLines(int elementId, const HudLine **out) const; + + /** + * Banner row (6.8): the lowest-id Text element of the place (BannerTop or BannerBottom) that is visible in HudState, + * passes the Subject and Leader rules and has a non-empty text; hud_server_elements and the rest of 8.3 don't apply. + * @return Element id with its text in buf, or -1 with buf "" + */ + int GetBannerRow(bhl::sb::E_Place place, wchar_t *buf, int bufSizeBytes) const; + + //---------------------------------------------------------------------------------------------------- + // Change counters for redraws + //---------------------------------------------------------------------------------------------------- + + //! Incremented on every change of the store + int GetSerial() const { return m_iSerial; } + + //! Incremented on every change of the config or columns + int GetSchemaSerial() const { return m_iSchemaSerial; } + + //! Incremented when the store is cleared: Reset (a full sync starts with it), VidInit and the loss of ScoreboardV1 + int GetResetCount() const { return m_iResetCount; } + + //! Incremented on every removal of the element id, also by Clear + int GetElementRemovals(int id) const { return m_iElementRemovals[id]; } + + //---------------------------------------------------------------------------------------------------- + // Text helpers + //---------------------------------------------------------------------------------------------------- + + /** + * Converts a UTF-8 string of the protocol to wide (4.2): a string that is exactly a client + * token is localized, a missing token is shown without '#'. Other strings, "#1" too, stay as they are. + */ + static void LocalizeString(const char *str, wchar_t *buf, int bufSizeBytes); + +private: + bool m_bConfigReceived = false; + bool m_bAcceptMessages = true; //!< False while the client caps have no ScoreboardV1 + bool m_bWaitForReset = false; //!< ScoreboardV1 came back: only Reset is accepted until one arrives + bhl::sb::E_ConfigFlags m_ConfigFlags = bhl::sb::E_ConfigFlags::None; + char m_szTitle[bhl::sb::MAX_TITLE_LEN + 1] = {}; + char m_szTag[bhl::sb::MAX_TAG_LEN + 1] = {}; + int m_iSerial = 0; + int m_iSchemaSerial = 0; + int m_iResetCount = 0; + int m_iElementRemovals[bhl::sb::MAX_ELEMENTS] = {}; + int m_iFrame = 0; //!< Incremented by Frame(), invalidates the per-frame caches + + Column m_Columns[bhl::sb::MAX_COLUMNS]; + Value m_GlobalValues[bhl::sb::MAX_COLUMNS]; + Value m_PlayerValues[MAX_PLAYERS + 1][bhl::sb::MAX_COLUMNS]; + Value m_TeamValues[MAX_TEAMS + 1][bhl::sb::MAX_COLUMNS]; + List m_Lists[bhl::sb::MAX_LISTS]; + + Element m_Elements[bhl::sb::MAX_ELEMENTS]; + bhl::sb::CTemplate m_Templates[bhl::sb::MAX_ELEMENTS][bhl::sb::MAX_VARIANTS]; + unsigned int m_iVisibleMask = 0; + unsigned int m_iHiddenStdParts = 0; + + int m_SortColumns[bhl::sb::MAX_COLUMNS] = {}; //!< Ids of the sort key columns in priority order (ties by id): priority > 0, not Builtin or Badge, Hidden included + int m_iSortColumnCount = 0; + bool m_bPlayerConnected[MAX_PLAYERS + 1] = {}; //!< Connection state seen by the last Frame + + //! Ranked entities of a frame (6.4, 8.11), computed on first use + struct Ranking + { + int iFrame = -1; + int iSerial = -1; + bool bTeamMode = false; + int iSign = 1; //!< -1 if the first sort key is ascending + Subject firstRow; + int iCount = 0; + Subject entities[MAX_PLAYERS]; //!< Participants, or teams with participants in team mode + bool bHasNumber[MAX_PLAYERS] = {}; + int numbers[MAX_PLAYERS] = {}; + }; + + struct BuiltinsCacheEntry + { + int iFrame = -1; + int iSerial = -1; + Subject subject; + Builtins builtins; + }; + + //! Subjects whose built-in values are kept per frame: the viewer's, the leader and the rows of a Board + static constexpr int BUILTINS_CACHE_SIZE = 16; + + mutable Ranking m_Ranking; + mutable BuiltinsCacheEntry m_BuiltinsCache[BUILTINS_CACHE_SIZE]; + mutable int m_iNextBuiltinsCache = 0; + mutable int m_iRunningClockSerial = -1; //!< m_iSerial when m_bHasRunningClock was computed + mutable bool m_bHasRunningClock = false; + + HudLine m_HudLines[MAX_HUD_LINES]; //!< A ring: events are not state and change no serial + int m_iNextHudLine = 0; //!< Slot of the next line, the oldest one when the ring is full + int m_iLastHudLineSeq = 0; + + //! Reads the payload of a BhlScore message + class CMsgReader; + + //! Clears everything as on Reset + void Clear(); + void UpdateSortColumns(); + + //! Returns MAX_COLUMNS values of the protocol target or nullptr + Value *GetTargetValues(int target); + + //! Removes an element, its templates and its Feed lines; its visibility bit stays + void RemoveElement(int id); + + const Ranking &GetRanking() const; + Builtins ComputeBuiltins(const Subject &subject) const; + int GetPlace(const Subject &entity) const; + + //! Number of a ranked entity (6.4): its first-key number, or its frags without sort keys + bool GetEntityNumber(const Subject &entity, int sortCol, int &out) const; + + //! ComparePlayers or CompareTeams for two entities of the same kind + int CompareEntities(const Subject &a, const Subject &b) const; + + const Value &GetEntityValue(const Subject &entity, int col) const { return entity.IsTeam() ? GetTeamValue(entity.iTeam, col) : GetPlayerValue(entity.iPlayer, col); } + + //! Cell of a subject (8.10): the player's, his team's, then global; a team subject starts with its team + const Value &GetSubjectValue(const Subject &subject, int col) const; + + //! Value ref of an element, nullptr without one or when it is "@value" itself + const bhl::sb::TemplateRef *GetValueRef(int elementId) const; + + int MsgFunc_BhlScore(const char *pszName, int iSize, void *pbuf); + void ReadReset(CMsgReader &reader); + void ReadConfig(CMsgReader &reader); + void ReadColumn(CMsgReader &reader); + void ReadValues(CMsgReader &reader); + void ReadList(CMsgReader &reader); + void ReadElement(CMsgReader &reader); + void ReadTemplate(CMsgReader &reader); + void ReadHudState(CMsgReader &reader); + + /** + * Adds a line to a Feed element: its variant's template is evaluated once, for the element's subject, + * with the args. Ignored for another kind, a variant without a template, a broken message, or when + * the text is empty and there is no icon sprite. + */ + void ReadEvent(CMsgReader &reader); + + /** + * Reads "type len payload" (4.3). A value of an unknown type, with a wrong len or a broken + * payload is returned empty. + * @return false if the message ends inside the value + */ + static bool ReadValue(CMsgReader &reader, Value &value, int &type); +}; + +#endif diff --git a/src/game/client/scoreboard_template.cpp b/src/game/client/scoreboard_template.cpp new file mode 100644 index 00000000..fdf3f5e9 --- /dev/null +++ b/src/game/client/scoreboard_template.cpp @@ -0,0 +1,644 @@ +#include +#include +#include +#include +#include +#include "scoreboard_template.h" + +namespace bhl::sb +{ + +namespace +{ + + //! VGUI2 text is UTF-16 on Windows and UTF-32 elsewhere + constexpr bool WIDE_IS_UTF16 = sizeof(wchar_t) == 2; + + constexpr wchar_t ELLIPSIS = 0x2026; + constexpr unsigned int REPLACEMENT_CHAR = 0xFFFD; + constexpr int MAX_FORMS = 3; + + //! Names of the built-ins after '@', indexed by E_Builtin from Place on + constexpr const char *BUILTIN_NAMES[] = { "place", "total", "state", "rival", "gap", "pass", "lead", "behind", "score", "frags", + "deaths", "name", "value", "item", "index", "a", "b", "c", "d", "icon" }; + static_assert(std::size(BUILTIN_NAMES) == static_cast(E_Builtin::Icon) - static_cast(E_Builtin::Place) + 1, "every built-in needs a name"); + + E_Builtin FindBuiltin(const char *name) + { + for (size_t i = 0; i < std::size(BUILTIN_NAMES); i++) + { + if (!strcmp(BUILTIN_NAMES[i], name)) + return static_cast(static_cast(E_Builtin::Place) + i); + } + + return E_Builtin::Unknown; + } + + bool IsAsciiLower(unsigned int c) + { + return c >= 'a' && c <= 'z'; + } + + bool IsAsciiDigit(unsigned int c) + { + return c >= '0' && c <= '9'; + } + + bool IsKeyChar(unsigned int c) + { + return IsAsciiLower(c) || IsAsciiDigit(c) || c == '_'; + } + + //! Number of wchar_t in the code point at text[0]: 2 for a UTF-16 surrogate pair + size_t GetCodePointSize(const wchar_t *text, size_t len) + { + return WIDE_IS_UTF16 && len >= 2 && text[0] >= 0xD800 && text[0] <= 0xDBFF && text[1] >= 0xDC00 && text[1] <= 0xDFFF ? 2 : 1; + } + + //! Size in wchar_t of the first count code points of text + size_t GetCodePointsSize(const wchar_t *text, size_t len, int count) + { + size_t size = 0; + + for (int i = 0; i < count && size < len; i++) + size += GetCodePointSize(text + size, len - size); + + return size; + } + + bool IsColorCodeAt(const std::wstring &text, size_t pos) + { + return text[pos] == L'^' && pos + 1 < text.size() && text[pos + 1] >= L'0' && text[pos + 1] <= L'9'; + } + + //! Appends text[begin..end) without color codes (4.2) + void AppendWithoutColors(std::wstring &out, const std::wstring &text, size_t begin, size_t end) + { + for (size_t i = begin; i < end; i++) + { + if (IsColorCodeAt(text, i) && i + 1 < end) + i++; + else + out.push_back(text[i]); + } + } + + void AppendCodePoint(std::wstring &out, unsigned int cp) + { + if (WIDE_IS_UTF16 && cp > 0xFFFF) + { + cp -= 0x10000; + out.push_back(static_cast(0xD800 + (cp >> 10))); + out.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + else + { + out.push_back(static_cast(cp)); + } + } + + //! Decodes UTF-8; every invalid sequence becomes U+FFFD + std::wstring Utf8ToWide(const char *text) + { + std::wstring out; + const unsigned char *p = reinterpret_cast(text); + + while (*p) + { + unsigned int c = *p; + unsigned int cp = REPLACEMENT_CHAR; + int extra = 0; + unsigned int lower = 0x80; + unsigned int upper = 0xBF; + + if (c < 0x80) + { + cp = c; + } + else if (c >= 0xC2 && c <= 0xDF) + { + cp = c & 0x1F; + extra = 1; + } + else if (c >= 0xE0 && c <= 0xEF) + { + cp = c & 0x0F; + extra = 2; + lower = c == 0xE0 ? 0xA0 : 0x80; + upper = c == 0xED ? 0x9F : 0xBF; + } + else if (c >= 0xF0 && c <= 0xF4) + { + cp = c & 0x07; + extra = 3; + lower = c == 0xF0 ? 0x90 : 0x80; + upper = c == 0xF4 ? 0x8F : 0xBF; + } + + p++; + + for (int i = 0; i < extra; i++) + { + unsigned int next = *p; + + // Only the first continuation byte has a narrower range + if (next < (i == 0 ? lower : 0x80) || next > (i == 0 ? upper : 0xBF)) + { + cp = REPLACEMENT_CHAR; + break; + } + + cp = (cp << 6) | (next & 0x3F); + p++; + } + + if (c >= 0x80 && extra == 0) + cp = REPLACEMENT_CHAR; + + AppendCodePoint(out, cp); + } + + return out; + } + + //! ms in whole units, rounded up while a clock counts down and down otherwise + int DivideClock(int ms, int unit, bool bDown) + { + int quotient = ms / unit; + int remainder = ms % unit; + return bDown ? quotient + (remainder > 0) : quotient - (remainder < 0); + } + + /** + * Appends whole code points to a buffer of bufLen wchar_t, up to MAX_EVAL_LEN UTF-16 units. + * Text that doesn't fit is dropped, a surrogate pair is never split. + */ + class CTextWriter + { + public: + CTextWriter(wchar_t *buf, int bufLen) + : m_pBuf(buf) + , m_iBufLen(bufLen) + { + m_pBuf[0] = L'\0'; + } + + void Append(const wchar_t *text, size_t len) + { + size_t pos = 0; + + while (pos < len && !m_bTruncated) + { + size_t size = GetCodePointSize(text + pos, len - pos); + + // A code point above U+FFFF takes two UTF-16 units, also where wchar_t is UTF-32 + int units = static_cast(text[pos]) > 0xFFFF ? 2 : static_cast(size); + + if (m_iLen + static_cast(size) > m_iBufLen - 1 || m_iUnits + units > MAX_EVAL_LEN) + { + m_bTruncated = true; + break; + } + + for (size_t i = 0; i < size; i++) + m_pBuf[m_iLen++] = text[pos + i]; + + m_iUnits += units; + pos += size; + } + + m_pBuf[m_iLen] = L'\0'; + } + + void Append(const wchar_t *text) + { + Append(text, wcslen(text)); + } + + void Append(wchar_t c) + { + Append(&c, 1); + } + + void AppendNumber(int n) + { + wchar_t buf[16]; + swprintf(buf, std::size(buf), L"%d", n); + Append(buf); + } + + bool IsTruncated() const { return m_bTruncated; } + + private: + wchar_t *m_pBuf = nullptr; + int m_iBufLen = 0; + int m_iLen = 0; + int m_iUnits = 0; + bool m_bTruncated = false; + }; + + //! Writes a word form: '#' is the number, "##" a literal '#' (the signed number) + void WriteForm(const std::wstring &form, int number, CTextWriter &out) + { + for (size_t i = 0; i < form.size(); i++) + { + if (form[i] != L'#') + { + out.Append(form[i]); + } + else if (i + 1 < form.size() && form[i + 1] == L'#') + { + out.Append(L'#'); + i++; + } + else + { + out.AppendNumber(number); + } + } + } + + //! Writes milliseconds as m:ss.cc, from one hour as h:mm:ss.cc, below 0 as 0:00.00 (format time2) + void FormatTime2(int ms, bool bDown, wchar_t *buf, int bufLen) + { + int hundredths = std::max(DivideClock(ms, 10, bDown), 0); + wchar_t text[16]; + FormatTime(hundredths / 100, text, static_cast(std::size(text))); + swprintf(buf, bufLen, L"%ls.%02d", text, hundredths % 100); + } + + //! Index of the word form (10.2) for the absolute value of n, with formCount forms (1-3) + int GetWordForm(int n, int formCount) + { + unsigned int value = n < 0 ? 0u - static_cast(n) : static_cast(n); + + if (formCount <= 1) + return 0; + + if (formCount == 2) + return value == 1 ? 0 : 1; + + if (value % 10 == 1 && value % 100 != 11) + return 0; + + if (value % 10 >= 2 && value % 10 <= 4 && (value % 100 < 12 || value % 100 > 14)) + return 1; + + return 2; + } + +} + +//---------------------------------------------------------------------------------------------------- +// Refs +//---------------------------------------------------------------------------------------------------- +void ParseRef(const char *text, TemplateRef &out) +{ + out = TemplateRef(); + + if (!text || !text[0]) + return; + + if (!IsValidRef(text)) + { + out.builtin = E_Builtin::Unknown; + return; + } + + // A valid ref is a placeholder without its braces, '?', word forms and other formats + std::wstring source = L"{" + std::wstring(text, text + strlen(text)) + L"}"; + CTemplate tpl; + tpl.Parse(source.c_str()); + out = tpl.GetPlaceholderRef(0); +} + +//---------------------------------------------------------------------------------------------------- +// CTemplate +//---------------------------------------------------------------------------------------------------- +bool CTemplate::Parse(const char *text) +{ + if (!text) + text = ""; + + // A missing token is shown as its name (8.10) + return Parse(Utf8ToWide(IsClientToken(text) ? text + 1 : text).c_str()); +} + +bool CTemplate::Parse(const wchar_t *text) +{ + Clear(); + m_bSet = true; + + std::wstring src = text ? text : L""; + size_t len = src.size(); + size_t pos = 0; + std::wstring literal; + + while (pos < len && !HasError()) + { + wchar_t c = src[pos]; + + if ((c == L'{' || c == L'}') && pos + 1 < len && src[pos + 1] == c) + { + literal.push_back(c); + pos += 2; + } + else if (c == L'{') + { + size_t end = src.find(L'}', pos + 1); + + if (end == std::wstring::npos) + { + // After a '{' without a closing '}' the rest is literal + AppendWithoutColors(literal, src, pos, len); + break; + } + + if (ParsePlaceholder(src, pos, end, literal)) + { + pos = end + 1; + } + else + { + literal.push_back(c); + pos++; + } + } + else if (IsColorCodeAt(src, pos)) + { + pos += 2; + } + else + { + literal.push_back(c); + pos++; + } + } + + m_Tail.swap(literal); + return !HasError(); +} + +bool CTemplate::ParsePlaceholder(const std::wstring &text, size_t begin, size_t end, std::wstring &literal) +{ + Placeholder ph; + size_t pos = begin + 1; + + if (pos < end && text[pos] == L'^') + { + ph.ref.bFirstRow = true; + pos++; + } + + bool bBuiltin = pos < end && text[pos] == L'@'; + + if (bBuiltin) + pos++; + + size_t nameBegin = pos; + + while (pos < end && (bBuiltin ? IsAsciiLower(text[pos]) : IsKeyChar(text[pos]))) + pos++; + + size_t nameLen = pos - nameBegin; + + if (nameLen < 1 || nameLen > static_cast(bBuiltin ? MAX_BUILTIN_NAME_LEN : MAX_KEY_LEN)) + return false; + + if (pos < end && text[pos] == L'?') + { + ph.bOptional = true; + pos++; + } + + std::vector formats; + + while (pos < end && text[pos] == L':') + { + std::string format; + + for (pos++; pos < end && (IsAsciiLower(text[pos]) || IsAsciiDigit(text[pos])); pos++) + format.push_back(static_cast(text[pos])); + + if (format.empty()) + return false; + + formats.push_back(format); + } + + int formCount = 0; + + while (pos < end && text[pos] == L'|') + { + size_t formBegin = ++pos; + pos = std::min(text.find_first_of(L"|{", pos), end); + + if (pos < end && text[pos] == L'{') + return false; + + if (formCount < MAX_FORMS) + AppendWithoutColors(ph.forms[formCount], text, formBegin, pos); + + formCount++; + } + + if (pos != end) + return false; + + // The syntax matches: from here on every problem is a parse error, not a literal + for (size_t i = 0; i < nameLen; i++) + ph.ref.szKey[i] = static_cast(text[nameBegin + i]); + + ph.ref.builtin = bBuiltin ? FindBuiltin(ph.ref.szKey) : E_Builtin::None; + + auto fnError = [this]() { + m_bError = true; + return true; + }; + + if (m_Placeholders.size() >= static_cast(MAX_PLACEHOLDERS)) + return fnError(); + + for (size_t i = 0; i < formats.size(); i++) + { + const std::string &format = formats[i]; + + if (std::find(formats.begin(), formats.begin() + i, format) != formats.begin() + i) + return fnError(); + + if (format == "cur" || format == "max" || format == "left") + { + if (ph.ref.format != E_RefFormat::None) + return fnError(); + + ph.ref.format = format == "cur" ? E_RefFormat::Cur : (format == "max" ? E_RefFormat::Max : E_RefFormat::Left); + } + else if (format == "time" || format == "time2" || format == "name" || format == "team") + { + if (ph.textFormat != E_TextFormat::None) + return fnError(); + + if (format == "time") + ph.textFormat = E_TextFormat::Time; + else if (format == "time2") + ph.textFormat = E_TextFormat::Time2; + else if (format == "name") + ph.textFormat = E_TextFormat::Name; + else + ph.textFormat = E_TextFormat::Team; + } + else if (format.find_first_not_of("0123456789") == std::string::npos) + { + if (ph.iCut != 0) + return fnError(); + + long cut = strtol(format.c_str(), nullptr, 10); + + if (cut < 1 || cut > MAX_CUT) + return fnError(); + + ph.iCut = static_cast(cut); + } + else + { + ph.bUnknownFormat = true; + } + } + + if (formCount > 0) + { + if (ph.textFormat != E_TextFormat::None) + return fnError(); + + ph.textFormat = E_TextFormat::Forms; + ph.iFormCount = formCount < MAX_FORMS ? formCount : MAX_FORMS; + } + + ph.literal.swap(literal); + m_Placeholders.push_back(ph); + return true; +} + +const TemplateRef &CTemplate::GetPlaceholderRef(int i) const +{ + static const TemplateRef s_EmptyRef; + + if (i < 0 || i >= static_cast(m_Placeholders.size())) + return s_EmptyRef; + + return m_Placeholders[i].ref; +} + +bool CTemplate::WriteValue(const Placeholder &ph, ITemplateContext &ctx, wchar_t *buf, int bufLen, bool &bTruncated) +{ + CTextWriter out(buf, bufLen); + TemplateValue value; + wchar_t text[TEMPLATE_BUF_LEN]; + text[0] = L'\0'; + bTruncated = false; + + // Every text format takes a number + if (ph.bUnknownFormat || ph.ref.builtin == E_Builtin::Unknown || !ctx.GetValue(ph.ref, value) || (ph.textFormat != E_TextFormat::None && !value.bIsNumber)) + return false; + + switch (ph.textFormat) + { + case E_TextFormat::None: + out.Append(value.wszText); + break; + case E_TextFormat::Forms: + WriteForm(ph.forms[GetWordForm(value.iNumber, ph.iFormCount)], value.iNumber, out); + break; + case E_TextFormat::Time: + FormatTime(value.iNumber, text, TEMPLATE_BUF_LEN); + break; + case E_TextFormat::Time2: + FormatTime2(value.iMs, value.bClockDown, text, TEMPLATE_BUF_LEN); + break; + case E_TextFormat::Name: + if (!ctx.GetPlayerName(value.iNumber, text, TEMPLATE_BUF_LEN)) + return false; + + break; + case E_TextFormat::Team: + if (!ctx.GetTeamName(value.iNumber, text, TEMPLATE_BUF_LEN)) + return false; + + break; + } + + out.Append(text); + bTruncated = out.IsTruncated(); + return true; +} + +bool CTemplate::Evaluate(ITemplateContext &ctx, wchar_t *buf, int bufLen) const +{ + if (!buf || bufLen <= 0) + return false; + + CTextWriter out(buf, bufLen); + + if (!m_bSet || HasError()) + return false; + + for (const Placeholder &ph : m_Placeholders) + { + wchar_t text[TEMPLATE_BUF_LEN]; + bool bTruncated = false; + out.Append(ph.literal.data(), ph.literal.size()); + + if (!WriteValue(ph, ctx, text, TEMPLATE_BUF_LEN, bTruncated)) + { + if (ph.bOptional) + continue; + + buf[0] = L'\0'; + return false; + } + + size_t len = wcslen(text); + size_t size = ph.iCut > 0 ? GetCodePointsSize(text, len, ph.iCut) : len; + + // Only the TABs of the template separate the columns of a Board row (8.14) + std::replace(text, text + size, L'\t', L' '); + out.Append(text, size); + + if (ph.iCut > 0 && (bTruncated || size < len)) + out.Append(ELLIPSIS); + } + + out.Append(m_Tail.data(), m_Tail.size()); + + // Line breaks are drawn as spaces (8.6) + std::replace_if(buf, buf + wcslen(buf), [](wchar_t c) { return c == L'\r' || c == L'\n'; }, L' '); + return buf[0] != L'\0'; +} + +//---------------------------------------------------------------------------------------------------- +// Helpers +//---------------------------------------------------------------------------------------------------- +bool IsClientToken(const char *str) +{ + if (!str || str[0] != '#' || !str[1] || IsAsciiDigit(str[1])) + return false; + + return strspn(str + 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") == strlen(str + 1); +} + +int GetClockSeconds(int ms, bool bDown) +{ + return DivideClock(ms, 1000, bDown); +} + +void FormatTime(int seconds, wchar_t *buf, int bufLen) +{ + seconds = std::max(seconds, 0); + + if (seconds >= 3600) + swprintf(buf, bufLen, L"%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60); + else + swprintf(buf, bufLen, L"%d:%02d", seconds / 60, seconds % 60); +} + +} diff --git a/src/game/client/scoreboard_template.h b/src/game/client/scoreboard_template.h new file mode 100644 index 00000000..d425cfbd --- /dev/null +++ b/src/game/client/scoreboard_template.h @@ -0,0 +1,218 @@ +#ifndef SCOREBOARD_TEMPLATE_H +#define SCOREBOARD_TEMPLATE_H +#include +#include +#include + +/** + * Templates of HUD elements (docs/scoreboard-protocol.md, 8.10). + * + * A pure unit: it doesn't use VGUI2, the engine or client globals, so a host test can link it alone. + * Values and names come through ITemplateContext. + * + * Text is wchar_t, like VGUI2 text: UTF-16 on Windows, UTF-32 on Linux. + * Unlike the store API, buffer sizes here are counts of wchar_t, not bytes. + * A buffer of TEMPLATE_BUF_LEN always holds a full result (255 UTF-16 units) on both platforms. + */ +namespace bhl::sb +{ + +constexpr int TEMPLATE_BUF_LEN = MAX_EVAL_LEN + 1; + +//! Built-in values of refs (8.11); BUILTIN_NAMES in scoreboard_template.cpp lists the names of Place to Icon in this order +enum class E_Builtin +{ + None = 0, //!< Not a built-in: the ref names a column key + Unknown, //!< "@name" this client doesn't know, or an invalid ref: the value is always missing + Place, + Total, + State, + Rival, + Gap, + Pass, + Lead, + Behind, + Score, + Frags, + Deaths, + Name, + Value, + + // Only in a context that has them (TemplateExtras of CScoreboardData::EvaluateTemplate), missing elsewhere + Item, //!< List item of a Board row + Index, //!< Number of a Board row, 1-based + A, //!< Event args 0-3 by position + B, + C, + D, + Icon, //!< First Icon arg of an event +}; + +//! Format of a ref that makes a number of a Progress +enum class E_RefFormat +{ + None = 0, + Cur, + Max, + Left, //!< max(max - cur, 0) +}; + +/** + * A parsed ref: "[^](key|@name)", with the format cur, max or left. + * In a placeholder the format comes from its format list, in Element.select and Element.value + * from the ":cur", ":max" or ":left" suffix. + */ +struct TemplateRef +{ + bool bFirstRow = false; //!< "^": read for the first row (6.4) instead of the subject + E_Builtin builtin = E_Builtin::None; + char szKey[MAX_KEY_LEN + 1] = {}; //!< Column key; for a built-in its name without '@' + E_RefFormat format = E_RefFormat::None; + + //! False for a cleared ref ("" in Element.select and Element.value) + bool IsSet() const { return builtin != E_Builtin::None || szKey[0]; } +}; + +/** + * Parses a ref of Element.select or Element.value (4.3). "" clears out. + * An invalid ref is stored as E_Builtin::Unknown, so its value is always missing. + */ +void ParseRef(const char *text, TemplateRef &out); + +//! A value resolved by ITemplateContext +struct TemplateValue +{ + wchar_t wszText[TEMPLATE_BUF_LEN] = {}; //!< The value written without a text format (8.10): a number, cur/max, a Clock as time, a localized text, an icon name, a player or team name + bool bIsNumber = false; //!< Int, Progress or Clock (4.3): only they take a text format + int iNumber = 0; //!< Int, Progress cur or Clock seconds + int iMs = 0; //!< For time2: the Int, the Progress cur or the current value of a Clock + bool bClockDown = false; //!< A Clock that counts down: its seconds and time2 are rounded up +}; + +//! Source of the values of a template, implemented by the client store for one subject and element +class ITemplateContext +{ +public: + virtual ~ITemplateContext() = default; + + /** + * Resolves a ref (8.10): a cell of the subject, its team or the whole game, or a built-in value; + * for the first row if ref.bFirstRow. + * ref.format is applied: cur, max and left make an Int of a Progress, other types are missing. + * Text cells come localized, Icon cells as their name (10.3), Clock cells with their current value. + * Names (@name, @rival) are display names without color codes, never looked up as tokens. + * + * "@value" is the element's own value ref, resolved at most one level: its own format first, then + * ref.format. When the value ref is itself "@value", with or without '^' or a format, the value + * is missing, so a self-reference can't recurse. + * @return false if the value is missing + */ + virtual bool GetValue(const TemplateRef &ref, TemplateValue &out) = 0; + + /** + * Display name of player idx without color codes, for the name format. Never looked up as a token. + * @param bufLen Size of buf in wchar_t + * @return false if the slot has no player + */ + virtual bool GetPlayerName(int idx, wchar_t *buf, int bufLen) = 0; + + //! Name of team number team (as in ScoreInfo) as the team header shows it, without color codes, for the team format; false if there is no such team + virtual bool GetTeamName(int team, wchar_t *buf, int bufLen) = 0; +}; + +/** + * A template parsed once into literals and placeholders, evaluated every frame. + * Grammar, formats, the missing-value rule and the limits follow 8.10 and 10.2. + */ +class CTemplate +{ +public: + /** + * Parses a template that came from the server (UTF-8, not color-stripped). A client token (IsClientToken) + * gives its name without '#' as a literal: the caller parses the text of a token it finds instead (4.2). + * Color codes ^0-^9 are dropped from literals and word forms. + * @return false on a parse error: the template then evaluates to "" + */ + bool Parse(const char *text); + + //! Parses a wide text, never looked up as a token + bool Parse(const wchar_t *text); + + //! Removes the template: IsSet() becomes false + void Clear() { *this = CTemplate(); } + + //! True after Parse, even with a parse error + bool IsSet() const { return m_bSet; } + + bool HasError() const { return m_bError; } + + const TemplateRef &GetPlaceholderRef(int i) const; + + /** + * Evaluates the template. Line breaks become spaces, the result is cut to 255 UTF-16 units. + * @param buf Receives the text; "" if a value is missing (without '?'), on a parse error + * or when the template isn't set + * @param bufLen Size of buf in wchar_t + * @return true if the text is not empty + */ + bool Evaluate(ITemplateContext &ctx, wchar_t *buf, int bufLen) const; + +private: + enum class E_TextFormat + { + None = 0, + Time, + Time2, + Name, + Team, + Forms, + }; + + struct Placeholder + { + std::wstring literal; //!< Text before the placeholder: braces unescaped, color codes dropped + TemplateRef ref; //!< With the format cur, max or left + bool bOptional = false; //!< '?': a missing value is written as "" + bool bUnknownFormat = false; //!< An unknown format makes the value always missing + E_TextFormat textFormat = E_TextFormat::None; + int iCut = 0; //!< Code points, 0 if not cut + int iFormCount = 0; //!< Word forms in use, 0-3 + std::wstring forms[3]; //!< Word forms as written, with '#' and "##" + }; + + bool m_bSet = false; + bool m_bError = false; + std::vector m_Placeholders; + std::wstring m_Tail; //!< Text after the last placeholder + + /** + * Parses text[begin..end], a '{' and the first '}' after it, and appends the placeholder, which + * takes literal as the text before it. Sets m_bError on a parse error. + * @return false if it is not a placeholder: the '{' is then a literal + */ + bool ParsePlaceholder(const std::wstring &text, size_t begin, size_t end, std::wstring &literal); + + /** + * Writes the value of a placeholder with its formats except the cut. + * @param bTruncated Set if the text didn't fit + * @return false if the value is missing + */ + static bool WriteValue(const Placeholder &ph, ITemplateContext &ctx, wchar_t *buf, int bufLen, bool &bTruncated); +}; + +//---------------------------------------------------------------------------------------------------- +// Helpers shared with the store +//---------------------------------------------------------------------------------------------------- + +//! True if str is exactly a client token: '#' followed by [A-Za-z_][A-Za-z0-9_]* (4.2) +bool IsClientToken(const char *str); + +//! Number of a Clock in whole seconds: rounded up while it counts down, down otherwise (4.3) +int GetClockSeconds(int ms, bool bDown); + +//! Writes seconds as m:ss, from one hour as h:mm:ss, below 0 as 0:00 (format time) +void FormatTime(int seconds, wchar_t *buf, int bufLen); + +} + +#endif diff --git a/src/game/client/vgui/score_panel.cpp b/src/game/client/vgui/score_panel.cpp index 27818042..dddad994 100644 --- a/src/game/client/vgui/score_panel.cpp +++ b/src/game/client/vgui/score_panel.cpp @@ -1,11 +1,15 @@ #include +#include +#include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -14,6 +18,7 @@ #include "cl_voice_status.h" #include "client_vgui.h" #include "client_steam_context.h" +#include "scoreboard_data.h" #include "hud/chat.h" #include "hud/text_message.h" #include "vgui/client_viewport.h" @@ -127,8 +132,104 @@ class CPlayerImage : public vgui2::IImage bool m_bIsMuted = false; }; +/** + * Draws a text on the line of a label of the header like that label: vertically centered, cut to wide. + * @return Width of the drawn text + */ +int PaintHeaderText(vgui2::Label *pLabel, int x, int wide, Color color, const wchar_t *text) +{ + vgui2::HFont font = pLabel->GetFont(); + wchar_t buf[bhl::sb::TEMPLATE_BUF_LEN]; + V_wcsncpy(buf, text, sizeof(buf)); + int textWide = FitCellText(font, buf, wide); + + if (buf[0]) + DrawCellText(font, x, pLabel->GetYPos() + (pLabel->GetTall() - vgui2::surface()->GetFontTall(font)) / 2, color, buf); + + return textWide; +} + } +/** + * Section header of the custom scoreboard. Columns added with HEADER_IMAGE are drawn by cells: + * texts from the server keep their '&', which a label takes for a hotkey mark, and team cells + * are followed by their badges (docs/scoreboard-protocol.md, 6.7). + */ +class CScorePanel::CSectionHeader : public vgui2::SectionedListPanelHeader +{ +public: + DECLARE_CLASS_SIMPLE(CSectionHeader, vgui2::SectionedListPanelHeader); + + CSectionHeader(vgui2::SectionedListPanel *parent, int sectionID, const ScoreCellStyle &style) + : BaseClass(parent, "", sectionID) + , m_Style(style) + { + } + + //! Creates the cell of a column that was added to the section with HEADER_IMAGE + CScoreCellImage *AddCell(int column) + { + if (column >= (int)m_Cells.size()) + m_Cells.resize(column + 1); + + m_Cells[column] = std::make_unique(m_Style); + return m_Cells[column].get(); + } + + //! Returns the cell of a column or nullptr for a text column + CScoreCellImage *GetCell(int column) + { + return column < (int)m_Cells.size() ? m_Cells[column].get() : nullptr; + } + + virtual void PerformLayout() override + { + int count = std::min((int)m_Cells.size(), m_pListPanel->GetColumnCountBySection(m_iSectionID)); + + for (int i = 0; i < count; i++) + { + if (m_Cells[i]) + m_Cells[i]->SetSize(m_pListPanel->GetColumnWidthBySection(m_iSectionID, i) - COLUMN_DATA_GAP, GetTall()); + } + + BaseClass::PerformLayout(); + + // When the base rebuilds its images, it leaves HEADER_IMAGE columns empty + bool bAdded = false; + + for (int i = 0; i < count; i++) + { + if (m_Cells[i] && GetImageAtIndex(i) != m_Cells[i].get()) + { + SetImageAtIndex(i, m_Cells[i].get(), 0); + bAdded = true; + } + } + + // Texts of other columns may run over empty columns, not over cells + if (bAdded) + BaseClass::PerformLayout(); + } + + virtual void Paint() override + { + m_Style.hFont = GetFont(); + + for (const std::unique_ptr &pCell : m_Cells) + { + if (pCell) + pCell->SetColor(GetFgColor()); + } + + BaseClass::Paint(); + } + +private: + ScoreCellStyle m_Style; //!< Style of the cells, with the font of the header + std::vector> m_Cells; //!< Cells by column, nullptr for a text column +}; + CScorePanel::CScorePanel() : BaseClass(nullptr, VIEWPORT_PANEL_SCORE) { @@ -181,6 +282,16 @@ void CScorePanel::UpdateServerName() wchar_t wbuf[MAX_SERVERNAME_LENGTH]; g_pVGuiLocalize->ConvertANSIToUnicode(g_pViewport->GetServerName(), wbuf, sizeof(wbuf)); m_pServerNameLabel->SetText(wbuf); + + // The title of the custom scoreboard replaces the server name. Paint draws it, so its '&' isn't a hotkey mark. + CScoreboardData &data = CScoreboardData::Get(); + CScoreboardData::LocalizeString(m_bCustom ? data.GetTitle() : "", m_wszTitle, sizeof(m_wszTitle)); + CScoreboardData::LocalizeString(m_bCustom ? data.GetTag() : "", m_wszTag, sizeof(m_wszTag)); + + if (m_bCustom && data.GetTitle()[0]) + m_pServerNameLabel->SetText(L""); + + LayoutBanner(); } void CScorePanel::EnableMousePointer(bool bEnable) @@ -238,16 +349,34 @@ void CScorePanel::ApplySchemeSettings(vgui2::IScheme *pScheme) void CScorePanel::OnThink() { + CScoreboardData &data = CScoreboardData::Get(); + + // Sections and columns can't be changed in place, so the schema or the order of teams rebuilds them. + // The order is checked every frame: team frags come from ScoreInfo and TeamScore, which don't change the store. + if (data.IsActive() != m_bCustom || (m_bCustom && data.GetSchemaSerial() != m_iSchemaSerial)) + FullUpdate(); + else if (m_bCustom && (m_bSectionsDirty || !AreTeamsSorted())) + RefreshItems(); + else if (m_bCustom && data.GetSerial() != m_iStoreSerial) + UpdateAllClients(); + + m_iStoreSerial = data.GetSerial(); + if (m_iKillerIndex != 0 && m_PlayerData[m_iKillerIndex].nItemID != -1) { // Update bg color UpdateClientInfo(m_iKillerIndex); } - if (m_flLastUpdateTime + UPDATE_PERIOD <= gEngfuncs.GetAbsoluteTime()) + float flUpdatePeriod = m_bCustom && data.HasRunningClock() ? CLOCK_UPDATE_PERIOD : UPDATE_PERIOD; + + if (m_flLastUpdateTime + flUpdatePeriod <= gEngfuncs.GetAbsoluteTime()) { UpdateAllClients(); } + + // Banner rows are templates evaluated every frame, like HUD elements + UpdateBanner(); } void CScorePanel::OnCommand(const char *command) @@ -286,6 +415,52 @@ void CScorePanel::OnCommand(const char *command) } } +void CScorePanel::PaintBackground() +{ + BaseClass::PaintBackground(); + + bool bTop = m_BannerTop.wszText[0] != L'\0'; + bool bBottom = m_BannerBottom.wszText[0] != L'\0'; + + if (bTop || bBottom) + { + // Banner: a box around the drawn rows with an accent at the left edge + vgui2::Label *pFirst = bTop ? m_pServerNameLabel : m_pMapNameLabel; + vgui2::Label *pLast = bBottom ? m_pMapNameLabel : m_pServerNameLabel; + int x0 = m_iBannerX - m_iBannerAccentWide - m_iBannerPadding; + int y0 = pFirst->GetYPos() - m_iBannerPadding; + int x1 = m_iBannerX + m_iBannerWide + m_iBannerPadding; + int y1 = pLast->GetYPos() + pLast->GetTall() + m_iBannerPadding; + + vgui2::surface()->DrawSetColor(m_BannerBgColor); + vgui2::surface()->DrawFilledRect(x0, y0, x1, y1); + vgui2::surface()->DrawSetColor(m_BannerAccentColor); + vgui2::surface()->DrawFilledRect(x0, y0, x0 + m_iBannerAccentWide, y1); + } +} + +void CScorePanel::Paint() +{ + BaseClass::Paint(); + + // Texts from the server are drawn here and not by labels, which take '&' for a hotkey mark + if (m_pServerNameLabel->IsVisible() && (m_wszTitle[0] || m_wszTag[0])) + { + int x, y, wide, tall, textWide, textTall; + m_pServerNameLabel->GetBounds(x, y, wide, tall); + m_pServerNameLabel->GetContentSize(textWide, textTall); + + if (m_wszTitle[0]) + textWide = PaintHeaderText(m_pServerNameLabel, x, wide, m_pServerNameLabel->GetFgColor(), m_wszTitle); + + if (m_wszTag[0]) + DrawScoreBadge(m_CellStyle, x + std::min(textWide, wide) + m_CellStyle.iSpacing, y + tall / 2, m_wszTag); + } + + PaintHeaderText(m_pServerNameLabel, m_iBannerX, m_iBannerWide, m_BannerTop.color, m_BannerTop.wszText); + PaintHeaderText(m_pMapNameLabel, m_iBannerX, m_iBannerWide, m_BannerBottom.color, m_BannerBottom.wszText); +} + const char *CScorePanel::GetName() { return VIEWPORT_PANEL_SCORE; @@ -348,8 +523,14 @@ void CScorePanel::OnItemContextMenu(int itemID) void CScorePanel::FullUpdate() { + CScoreboardData &data = CScoreboardData::Get(); + m_bCustom = data.IsActive(); + m_iStoreSerial = data.GetSerial(); + m_iSchemaSerial = data.GetSchemaSerial(); + UpdateServerName(); UpdateMapName(); + UpdateBanner(); RefreshItems(); } @@ -367,9 +548,12 @@ void CScorePanel::RefreshItems() std::fill(m_TeamData.begin(), m_TeamData.end(), TeamData()); std::fill(m_PlayerData.begin(), m_PlayerData.end(), PlayerData()); std::fill(m_IsTeamSectionCreated.begin(), m_IsTeamSectionCreated.end(), false); + std::fill(m_SectionHeaders.begin(), m_SectionHeaders.end(), nullptr); + m_bSectionsDirty = false; m_pPlayerList->RemoveAll(); m_pPlayerList->RemoveAllSections(); + BuildCustomColumns(); RestoreSize(); // Assign player teams, calculate team scores @@ -415,6 +599,10 @@ void CScorePanel::RefreshItems() // Sort teams based on the score std::sort(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + iTeamCount, [&](int ilhs, int irhs) { + // The store has the full order: sort keys, then the standard order, then the number + if (m_bCustom) + return CScoreboardData::Get().CompareTeams(ilhs, irhs) < 0; + const TeamData &lhs = m_TeamData[ilhs]; const TeamData &rhs = m_TeamData[irhs]; @@ -433,6 +621,7 @@ void CScorePanel::RefreshItems() // Compare idx if everything is equal return ilhs > irhs; }); + m_iSortedTeamCount = iTeamCount; // Create header before any other sections CreateSection(HEADER_SECTION_ID); @@ -465,7 +654,13 @@ void CScorePanel::CreateSection(int nTeamID) char buf[128]; TeamData &td = m_TeamData[nTeamID]; - m_pPlayerList->AddSection(nTeamID, "", StaticPlayerSortFuncByFrags); + m_SectionHeaders[nTeamID] = m_bCustom ? new CSectionHeader(m_pPlayerList, nTeamID, m_CellStyle) : nullptr; + + if (m_bCustom) + m_pPlayerList->AddSection(nTeamID, m_SectionHeaders[nTeamID], StaticPlayerSortFuncCustom); + else + m_pPlayerList->AddSection(nTeamID, "", StaticPlayerSortFuncByFrags); + m_pPlayerList->SetSectionFgColor(nTeamID, g_pViewport->GetTeamColor(nTeamID)); if (nTeamID == HEADER_SECTION_ID) @@ -474,6 +669,29 @@ void CScorePanel::CreateSection(int nTeamID) m_pPlayerList->SetSectionDividerColor(nTeamID, Color(0, 0, 0, 0)); } + if (m_bCustom) + { + // Cells draw the column titles, team cells and places. Team sections get their texts from UpdateScoresAndCounts. + bool bTitles = nTeamID == HEADER_SECTION_ID; + + for (int i = 0; i < (int)m_CustomColumns.size(); i++) + { + const CustomColumn &col = m_CustomColumns[i]; + bool bCell = bTitles ? col.type != ColumnType::Avatar : (col.type == ColumnType::Rank || col.type == ColumnType::Custom); + int flags = bCell ? col.iFlags | vgui2::SectionedListPanel::HEADER_IMAGE : col.iFlags; + m_pPlayerList->AddColumnToSection(nTeamID, col.szName, L"", flags, col.iWidth); + + if (!bCell) + continue; + + CScoreCellImage *pCell = m_SectionHeaders[nTeamID]->AddCell(i); + pCell->SetAlign(col.iAlign); + pCell->SetText(bTitles ? col.wszTitle : L""); + } + + return; + } + // Avatar m_pPlayerList->AddColumnToSection(nTeamID, "avatar", "", vgui2::SectionedListPanel::COLUMN_IMAGE | vgui2::SectionedListPanel::COLUMN_CENTER, @@ -583,6 +801,9 @@ void CScorePanel::UpdateClientInfo(int client) pd.nTeamID = pi->GetTeamNumber(); } + if (m_bCustom && !m_IsTeamSectionCreated[pd.nTeamID]) + m_bSectionsDirty = true; + // Create section for player's team if need to CreateSection(pd.nTeamID); @@ -638,6 +859,9 @@ void CScorePanel::UpdateClientInfo(int client) { playerKv->SetInt("ping", pi->GetPing()); } + + if (m_bCustom) + UpdateCustomCells(pi, playerKv); } if (pd.nItemID == -1) @@ -768,6 +992,9 @@ void CScorePanel::UpdateScoresAndCounts() snprintf(buf, sizeof(buf), "%d", td.iDeaths); g_pVGuiLocalize->ConvertANSIToUnicode(buf, wbuf, sizeof(wbuf)); m_pPlayerList->ModifyColumn(nTeamID, "deaths", wbuf); + + if (m_bCustom) + UpdateCustomTeamHeader(nTeamID); }; // Update team score and player count @@ -1068,15 +1295,17 @@ int CScorePanel::GetLineSpacingForHeight(int h) int CScorePanel::GetLineSpacingForNormal() { if (hud_scoreboard_spacing_normal.GetInt() > 0) - return hud_scoreboard_spacing_normal.GetInt(); + return hud_scoreboard_spacing_normal.GetInt() + m_iLineSpacingExtra; + if (m_iLineSpacingExtra > 0) + return m_iDefaultLineSpacing + m_iLineSpacingExtra; return 0; } int CScorePanel::GetLineSpacingForCompact() { if (hud_scoreboard_spacing_compact.GetInt() > 0) - return hud_scoreboard_spacing_compact.GetInt(); - return GetLineSpacingForHeight(ScreenHeight); + return hud_scoreboard_spacing_compact.GetInt() + m_iLineSpacingExtra; + return GetLineSpacingForHeight(ScreenHeight) + m_iLineSpacingExtra; } void CScorePanel::RestoreSize() @@ -1148,6 +1377,10 @@ void CScorePanel::Resize() GetPos(x, y); y = (ScreenHeight - height) / 2; SetPos(x, y); + + // A new size lays out the children from the layout file, which moves the banner. + // The player count text also changes before every resize. + LayoutBanner(); } bool CScorePanel::StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, int itemID1, int itemID2) @@ -1175,3 +1408,364 @@ bool CScorePanel::StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, i // the same, so compare itemID's (as a sentinel value to get deterministic sorts) return itemID1 < itemID2; } + +bool CScorePanel::AreTeamsSorted() +{ + return std::is_sorted(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + m_iSortedTeamCount, [](int ilhs, int irhs) { + return CScoreboardData::Get().CompareTeams(ilhs, irhs) < 0; + }); +} + +void CScorePanel::BuildCustomColumns() +{ + m_CustomColumns.clear(); + m_iLineSpacingExtra = 0; + + if (!m_bCustom) + return; + + CScoreboardData &data = CScoreboardData::Get(); + + m_CellStyle.hFont = m_CellFont; + m_CellStyle.hBadgeFont = m_BadgeFont; + m_CellStyle.filledColor = m_CellFilledColor; + m_CellStyle.emptyColor = m_CellEmptyColor; + m_CellStyle.currentColor = m_CellCurrentColor; + m_CellStyle.lastColor = m_CellLastColor; + m_CellStyle.badgeBgColor = m_BadgeBgColor; + m_CellStyle.badgeFgColor = m_BadgeFgColor; + m_CellStyle.iconColor = m_CellIconColor; + m_CellStyle.iDotSize = m_iCellDotSize; + m_CellStyle.iDotGap = m_iCellDotGap; + m_CellStyle.iStripTall = m_iCellStripTall; + m_CellStyle.iStripGap = m_iCellStripGap; + m_CellStyle.iSpacing = m_iCellSpacing; + m_CellStyle.iMargin = m_iCellMargin; + + // Standard columns indexed by ColumnType, their names are the keys of Builtin columns + struct StdColumn + { + const char *pszName; + const char *pszTitle; + int iWidth; + int iFlags; + bool bVisible; + }; + + constexpr int bright = vgui2::SectionedListPanel::COLUMN_BRIGHT; + const StdColumn stdColumns[] = { + { "rank", "#", m_iColumnWidthRank, bright, true }, + { "avatar", "", m_iColumnWidthAvatar, vgui2::SectionedListPanel::COLUMN_IMAGE | vgui2::SectionedListPanel::COLUMN_CENTER, true }, + { "name", "#PlayerName", 0, bright | (gHUD.GetColorCodeAction() == ColorCodeAction::Handle ? vgui2::SectionedListPanel::COLUMN_COLORED : 0), true }, + { "steamid", "#BHL_Scores_ColSteamID", m_iColumnWidthSteamID, bright, hud_scoreboard_showsteamid.GetBool() && !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideSteamID) }, + { "eff", "#BHL_Scores_ColEff", m_iColumnWidthEff, bright, hud_scoreboard_showeff.GetBool() && !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideEff) }, + { "frags", "#PlayerScore", m_iColumnWidthFrags, bright, !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideFrags) }, + { "deaths", "#PlayerDeath", m_iColumnWidthDeaths, bright, !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideDeaths) }, + { "ping", hud_scoreboard_showloss.GetBool() ? "#BHL_Scores_ColPingLoss" : "#BHL_Scores_ColPing", m_iColumnWidthPing, bright, true }, + }; + static_assert(ARRAYSIZE(stdColumns) == static_cast(ColumnType::Custom), "every standard column needs an entry"); + + auto fnGetBuiltinType = [&](const char *key) { + for (ColumnType type : { ColumnType::Rank, ColumnType::SteamID, ColumnType::Eff, ColumnType::Frags, ColumnType::Deaths, ColumnType::Ping }) + { + if (!Q_strcmp(key, stdColumns[(int)type].pszName)) + return type; + } + + return ColumnType::Custom; + }; + + // Custom columns are drawn by CScoreCellImage + auto fnAddColumn = [&](ColumnType type, int nColumnID, const char *title, int width, int align) { + CustomColumn col; + col.type = type; + col.nColumnID = nColumnID; + col.iAlign = align; + col.iWidth = width; + col.iFlags = type == ColumnType::Custom ? vgui2::SectionedListPanel::COLUMN_IMAGE : stdColumns[(int)type].iFlags; + col.iFlags |= align == 1 ? vgui2::SectionedListPanel::COLUMN_CENTER : (align == 2 ? vgui2::SectionedListPanel::COLUMN_RIGHT : 0); + + if (type == ColumnType::Custom) + snprintf(col.szName, sizeof(col.szName), "c%d_%s", nColumnID, data.GetColumn(nColumnID).szKey); + else + Q_strncpy(col.szName, stdColumns[(int)type].pszName, sizeof(col.szName)); + + CScoreboardData::LocalizeString(title, col.wszTitle, sizeof(col.wszTitle)); + m_CustomColumns.push_back(col); + }; + + // pColumn: the Builtin column that moves the standard one + auto fnAddStdColumn = [&](ColumnType type, const CScoreboardData::Column *pColumn) { + const StdColumn &info = stdColumns[(int)type]; + + if (info.bVisible) + fnAddColumn(type, -1, pColumn && pColumn->szTitle[0] ? pColumn->szTitle : info.pszTitle, info.iWidth, pColumn ? pColumn->GetAlign() : 0); + }; + + // Standard columns moved by Builtin columns + std::array builtins = {}; + + for (int i = 0; i < bhl::sb::MAX_COLUMNS; i++) + { + const CScoreboardData::Column &col = data.GetColumn(i); + + if (col.bValid && !col.IsHidden() && col.IsBuiltin()) + { + ColumnType type = fnGetBuiltinType(col.szKey); + + if (type != ColumnType::Custom && !builtins[(int)type]) + builtins[(int)type] = &col; + } + } + + if (builtins[(int)ColumnType::Rank]) + fnAddStdColumn(ColumnType::Rank, builtins[(int)ColumnType::Rank]); + + for (ColumnType type : { ColumnType::Avatar, ColumnType::Name, ColumnType::SteamID, ColumnType::Eff, ColumnType::Frags, ColumnType::Deaths }) + { + if (!builtins[(int)type]) + fnAddStdColumn(type, nullptr); + } + + for (int i = 0; i < bhl::sb::MAX_COLUMNS; i++) + { + const CScoreboardData::Column &col = data.GetColumn(i); + + // Badge columns take no width: they are drawn in the cells of their host + if (!col.bValid || col.IsHidden() || col.IsBadge()) + continue; + + if (col.IsBuiltin()) + { + ColumnType type = fnGetBuiltinType(col.szKey); + + if (type != ColumnType::Custom && type != ColumnType::Rank && builtins[(int)type] == &col) + fnAddStdColumn(type, &col); + + continue; + } + + int width = col.iWidth ? col.iWidth : bhl::sb::GetDefaultWidth(col.display); + + fnAddColumn(ColumnType::Custom, i, col.szTitle, vgui2::scheme()->GetProportionalScaledValue(width), col.GetAlign()); + } + + if (!builtins[(int)ColumnType::Ping]) + fnAddStdColumn(ColumnType::Ping, nullptr); + + // Name takes the free width and shrinks to its minimum, then columns are dropped from the end + int reservedWide = LIST_ROW_PADDING + m_pPlayerList->GetScrollBar()->GetWide(); + int otherWide = 0; + + for (const CustomColumn &col : m_CustomColumns) + otherWide += col.iWidth; + + int freeWide = m_pPlayerList->GetWide() - reservedWide; + + // On narrow screens Name gives up to a fifth of its minimum before a column is dropped + int nameMin = std::max(std::min(freeWide - otherWide, m_iColumnWidthNameMin), m_iColumnWidthNameMin * 4 / 5); + + while (otherWide + nameMin > freeWide && m_CustomColumns.back().type != ColumnType::Name) + { + otherWide -= m_CustomColumns.back().iWidth; + m_CustomColumns.pop_back(); + } + + for (CustomColumn &col : m_CustomColumns) + { + if (col.type == ColumnType::Name) + col.iWidth = std::max(freeWide - otherWide, nameMin); + else if (col.type == ColumnType::Custom && data.GetColumn(col.nColumnID).display == bhl::sb::E_Display::Steps) + m_iLineSpacingExtra = m_iCellStripTall + m_iCellStripGap; + } + + m_pPlayerList->SetLineSpacingOverride(0); + m_iDefaultLineSpacing = m_pPlayerList->GetLineSpacing(); +} + +void CScorePanel::UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv) +{ + CScoreboardData &data = CScoreboardData::Get(); + int client = pi->GetIndex(); + int lineSpacing = m_pPlayerList->GetLineSpacing(); + bool bTeamMode = data.IsTeamMode(); + Color color = gHUD.GetClientColor(client, NoTeamColor::White); + int badgeIDs[bhl::sb::MAX_COLUMNS]; + + for (const CustomColumn &col : m_CustomColumns) + { + if (col.type == ColumnType::Rank) + { + // In team mode the place is shown in team headers + int place = bTeamMode ? 0 : data.GetPlayerPlace(client); + + if (place > 0) + kv->SetInt(col.szName, place); + + continue; + } + + if (col.type != ColumnType::Custom) + continue; + + // Image columns read the index of the image from the row, cells are created on first use + int index = CELL_IMAGE_BASE + col.nColumnID * MAX_PLAYERS + client - 1; + + if (!m_pImageList->IsValidIndex(index) || !m_pImageList->GetImage(index)) + m_pImageList->SetImageAtIndex(index, new CScoreCellImage(m_CellStyle)); + + CScoreCellImage *pCell = static_cast(m_pImageList->GetImage(index)); + pCell->SetSize(col.iWidth - COLUMN_DATA_GAP, lineSpacing); + pCell->SetAlign(col.iAlign); + pCell->SetColor(color); + pCell->SetValue(data.GetColumn(col.nColumnID), data.GetPlayerValue(client, col.nColumnID)); + + int badgeCount = data.GetBadgeColumns(col.nColumnID, badgeIDs, ARRAYSIZE(badgeIDs)); + + for (int i = 0; i < badgeCount; i++) + pCell->AddBadge(data.GetPlayerValue(client, badgeIDs[i])); + + kv->SetInt(col.szName, index); + } +} + +void CScorePanel::UpdateCustomTeamHeader(int nTeamID) +{ + CSectionHeader *pHeader = m_SectionHeaders[nTeamID]; + + if (!pHeader) + return; + + CScoreboardData &data = CScoreboardData::Get(); + int badgeIDs[bhl::sb::MAX_COLUMNS]; + wchar_t wbuf[128]; + + // TEAM_SPECTATOR has no values and no place in the store, so its cells stay empty + for (int i = 0; i < (int)m_CustomColumns.size(); i++) + { + const CustomColumn &col = m_CustomColumns[i]; + CScoreCellImage *pCell = pHeader->GetCell(i); + + if (!pCell) + continue; + + wbuf[0] = L'\0'; + + if (col.type == ColumnType::Rank) + { + int place = data.IsTeamMode() ? data.GetTeamPlace(nTeamID) : 0; + + if (place > 0) + V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%d", place); + } + else + { + const CScoreboardData::Value &value = data.GetTeamValue(nTeamID, col.nColumnID); + + // Like dots in rows, a short progress has no counter. A progress with max 0 is its cur. + bool bDots = data.GetColumn(col.nColumnID).display == bhl::sb::E_Display::Meter + && value.type == bhl::sb::E_ValueType::Progress && value.iMax > 0 && value.iMax <= bhl::sb::MAX_DOTS; + + if (!bDots) + value.ToString(wbuf, sizeof(wbuf)); + } + + pCell->SetText(wbuf); + + int badgeCount = data.GetBadgeColumns(col.nColumnID, badgeIDs, ARRAYSIZE(badgeIDs)); + + for (int j = 0; j < badgeCount; j++) + pCell->AddBadge(data.GetTeamValue(nTeamID, badgeIDs[j])); + } +} + +void CScorePanel::UpdateBanner() +{ + bool bTopChanged = UpdateBannerRow(m_BannerTop, bhl::sb::E_Place::BannerTop, m_BannerAccentColor); + bool bBottomChanged = UpdateBannerRow(m_BannerBottom, bhl::sb::E_Place::BannerBottom, m_pMapNameLabel->GetFgColor()); + + if (bTopChanged || bBottomChanged) + LayoutBanner(); +} + +bool CScorePanel::UpdateBannerRow(BannerRow &row, bhl::sb::E_Place place, Color schemeColor) +{ + CScoreboardData &data = CScoreboardData::Get(); + wchar_t text[bhl::sb::TEMPLATE_BUF_LEN] = L""; + int id = m_bCustom ? data.GetBannerRow(place, text, sizeof(text)) : -1; + + if (id != -1) + { + const CScoreboardData::Element &element = data.GetElement(id); + + if (element.HasFlag(bhl::sb::E_ElementFlags::HudColor)) + row.color = Color(schemeColor.r(), schemeColor.g(), schemeColor.b(), schemeColor.a() * element.a / 255); + else + row.color = Color(element.r, element.g, element.b, element.a); + } + + if (!wcscmp(text, row.wszText)) + return false; + + V_wcsncpy(row.wszText, text, sizeof(row.wszText)); + return true; +} + +void CScorePanel::LayoutBanner() +{ + bool bTop = m_BannerTop.wszText[0] != L'\0'; + bool bBottom = m_BannerBottom.wszText[0] != L'\0'; + + // The server name is narrowed only while a row stands on its line + if (!bTop && m_iServerNameWide != -1) + { + m_pServerNameLabel->SetWide(m_iServerNameWide); + m_iServerNameWide = -1; + } + + if (!bTop && !bBottom) + return; + + // Rows end left of the player count, on the lines of the server and the map name, in the fonts of their labels + int nameX = m_pServerNameLabel->GetXPos(); + int mapTextWide, countTextWide, tall; + m_pMapNameLabel->GetContentSize(mapTextWide, tall); + m_pPlayerCountLabel->GetContentSize(countTextWide, tall); + int topWide = bTop ? GetCellTextWide(m_pServerNameLabel->GetFont(), m_BannerTop.wszText) : 0; + int bottomWide = bBottom ? GetCellTextWide(m_pMapNameLabel->GetFont(), m_BannerBottom.wszText) : 0; + + if (bTop && m_iServerNameWide == -1) + m_iServerNameWide = m_pServerNameLabel->GetWide(); + + int tagWide = m_wszTag[0] ? GetScoreBadgeWide(m_CellStyle, m_wszTag) + m_CellStyle.iSpacing : 0; + int boxLeft = m_iBannerAccentWide + m_iBannerPadding + m_CellStyle.iSpacing; + int bannerRight = m_pPlayerCountLabel->GetXPos() + m_pPlayerCountLabel->GetWide() - countTextWide - m_CellStyle.iSpacing - m_iBannerPadding; + + // Long rows are cut, so the map name and a third of the server name stay visible + int bannerMinX = 0; + + if (bTop) + bannerMinX = nameX + tagWide + (bannerRight - nameX) / 3; + + if (bBottom) + bannerMinX = std::max(bannerMinX, m_pMapNameLabel->GetXPos() + mapTextWide); + + bannerMinX += boxLeft; + + m_iBannerWide = std::min(std::max(topWide, bottomWide), std::max(bannerRight - bannerMinX, 0)); + m_iBannerX = bannerRight - m_iBannerWide; + + // The server name and its tag end before the banner + if (bTop) + m_pServerNameLabel->SetWide(std::clamp(m_iBannerX - boxLeft - tagWide - nameX, 0, m_iServerNameWide)); +} + +bool CScorePanel::StaticPlayerSortFuncCustom(vgui2::SectionedListPanel *list, int itemID1, int itemID2) +{ + KeyValues *it1 = list->GetItemData(itemID1); + KeyValues *it2 = list->GetItemData(itemID2); + Assert(it1 && it2); + + // The store has the full order: sort keys, then the standard order, then the index + return CScoreboardData::Get().ComparePlayers(it1->GetInt("client"), it2->GetInt("client")) < 0; +} diff --git a/src/game/client/vgui/score_panel.h b/src/game/client/vgui/score_panel.h index 17e57e5a..55e0f740 100644 --- a/src/game/client/vgui/score_panel.h +++ b/src/game/client/vgui/score_panel.h @@ -3,12 +3,14 @@ #include #include +#include #include #include #include #include #include "IViewportPanel.h" #include "viewport_panel_names.h" +#include "vgui/score_panel_cells.h" namespace vgui2 { @@ -52,6 +54,8 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel virtual void ApplySchemeSettings(vgui2::IScheme *pScheme) override; virtual void OnThink() override; virtual void OnCommand(const char *command) override; + virtual void PaintBackground() override; + virtual void Paint() override; // IViewportPanel overrides virtual const char *GetName() override; @@ -70,6 +74,18 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel static constexpr float HIGHLIGHT_KILLER_TIME = 10.f; static constexpr float UPDATE_PERIOD = 0.5f; + //! Update period while the store has a running Clock, so its seconds change on time + static constexpr float CLOCK_UPDATE_PERIOD = 0.1f; + + //! First index of custom cell images in m_pImageList (avatars use 1..MAX_PLAYERS) + static constexpr int CELL_IMAGE_BASE = MAX_PLAYERS + 1; + + //! Width of a row is the width of the list minus this padding (SectionedListPanel::LayoutPanels) + static constexpr int LIST_ROW_PADDING = 10; + + //! Gap at the right of a cell (COLUMN_DATA_GAP of SectionedListPanel) + static constexpr int COLUMN_DATA_GAP = 2; + enum class MenuAction { Mute, @@ -88,6 +104,8 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel Compact = 2, }; + class CSectionHeader; + struct TeamData { int iFrags = 0; @@ -102,6 +120,37 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel int nTeamID = 0; }; + enum class ColumnType + { + Rank, + Avatar, + Name, + SteamID, + Eff, + Frags, + Deaths, + Ping, + Custom, + }; + + struct CustomColumn + { + ColumnType type = ColumnType::Custom; + int nColumnID = -1; //!< Column id in the store for ColumnType::Custom + int iAlign = 0; //!< 0 left, 1 center, 2 right + int iFlags = 0; //!< SectionedListPanel column flags + int iWidth = 0; + char szName[32] = {}; //!< Column name, also the key in row data + wchar_t wszTitle[64] = {}; + }; + + //! Row of the banner in the header (docs/scoreboard-protocol.md, 6.8) + struct BannerRow + { + wchar_t wszText[bhl::sb::TEMPLATE_BUF_LEN] = {}; //!< Evaluated text, "" when the row is not drawn + Color color; + }; + struct MenuData { // Menu items @@ -138,6 +187,24 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel char m_szSpectatorTag[32] = "(spectator)"; + // Custom scoreboard (docs/scoreboard-protocol.md) + BannerRow m_BannerTop; //!< On the line of the server name + BannerRow m_BannerBottom; //!< On the line of the map name + int m_iBannerX = 0, m_iBannerWide = 0; //!< Shared by both rows, set by LayoutBanner + std::vector m_CustomColumns; + std::array m_SectionHeaders = {}; //!< Headers of the sections by team + ScoreCellStyle m_CellStyle; + wchar_t m_wszTitle[bhl::sb::MAX_TITLE_LEN + 1] = {}; //!< Drawn in place of the server name + wchar_t m_wszTag[32] = {}; + bool m_bCustom = false; + bool m_bSectionsDirty = false; //!< A section was created outside of RefreshItems + int m_iStoreSerial = -1; + int m_iSchemaSerial = -1; + int m_iSortedTeamCount = 0; + int m_iDefaultLineSpacing = 0; + int m_iLineSpacingExtra = 0; //!< Added to the line spacing while a Steps column is visible + int m_iServerNameWide = -1; //!< Width of the server name label before the banner cut it + // Column widths CPanelAnimationVarAliasType(int, m_iColumnWidthAvatar, "column_avatar", "26", "proportional_int"); CPanelAnimationVarAliasType(int, m_iColumnWidthName, "column_name", "170", "proportional_int"); @@ -152,6 +219,31 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel CPanelAnimationVarAliasType(int, m_iVerticalMargin, "vertical_margin", "30", "proportional_int"); CPanelAnimationVarAliasType(int, m_iBottomPadding, "bottom_padding", "4", "proportional_int"); + // Custom scoreboard + CPanelAnimationVarAliasType(int, m_iColumnWidthRank, "column_rank", "24", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iColumnWidthNameMin, "column_name_min", "100", "proportional_int"); + CPanelAnimationVar(vgui2::HFont, m_CellFont, "cell_font", "Default"); + CPanelAnimationVar(vgui2::HFont, m_BadgeFont, "badge_font", "DefaultVerySmall"); + CPanelAnimationVar(Color, m_CellFilledColor, "cell_filled_color", "255 160 0 255"); + CPanelAnimationVar(Color, m_CellEmptyColor, "cell_empty_color", "84 56 16 255"); + CPanelAnimationVar(Color, m_CellCurrentColor, "cell_current_color", "255 255 255 255"); + CPanelAnimationVar(Color, m_CellLastColor, "cell_last_color", "255 64 32 255"); + CPanelAnimationVar(Color, m_CellIconColor, "cell_icon_color", "255 160 0 255"); + CPanelAnimationVar(Color, m_BadgeBgColor, "badge_bgcolor", "255 160 0 255"); + CPanelAnimationVar(Color, m_BadgeFgColor, "badge_fgcolor", "0 0 0 255"); + CPanelAnimationVarAliasType(int, m_iCellDotSize, "cell_dot_size", "6", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellDotGap, "cell_dot_gap", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellStripTall, "cell_strip_tall", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellStripGap, "cell_strip_gap", "1", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellSpacing, "cell_spacing", "3", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellMargin, "cell_margin", "6", "proportional_int"); + + // Banner in the header, its rows are elements placed BannerTop and BannerBottom + CPanelAnimationVar(Color, m_BannerBgColor, "banner_bgcolor", "255 64 32 48"); + CPanelAnimationVar(Color, m_BannerAccentColor, "banner_accent_color", "255 160 0 255"); + CPanelAnimationVarAliasType(int, m_iBannerPadding, "banner_padding", "1", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iBannerAccentWide, "banner_accent_wide", "2", "proportional_int"); + /** * Updates all labels, recreates all sections, recalculates all data. * Called when panel becomes visible. @@ -269,6 +361,30 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel * Sorts rows in DESC order by frags. */ static bool StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, int itemID1, int itemID2); + + //! Returns true if the team sections of the custom scoreboard are still in the order of the store + bool AreTeamsSorted(); + + void BuildCustomColumns(); + + void UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv); + + void UpdateCustomTeamHeader(int nTeamID); + + //! Evaluates the banner rows. Lays the banner out again if a text changed. + void UpdateBanner(); + + /** + * Evaluates one banner row and sets its color. + * @param schemeColor Color of the row for an element with HudColor + * @return true if its text changed + */ + bool UpdateBannerRow(BannerRow &row, bhl::sb::E_Place place, Color schemeColor); + + //! Places the banner in the header left of the player count and narrows the server name + void LayoutBanner(); + + static bool StaticPlayerSortFuncCustom(vgui2::SectionedListPanel *list, int itemID1, int itemID2); }; #endif \ No newline at end of file diff --git a/src/game/client/vgui/score_panel_cells.cpp b/src/game/client/vgui/score_panel_cells.cpp new file mode 100644 index 00000000..8007b80d --- /dev/null +++ b/src/game/client/vgui/score_panel_cells.cpp @@ -0,0 +1,713 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hud.h" +#include "cl_util.h" +#include "hud_renderer.h" +#include "vgui/score_panel_cells.h" + +namespace +{ + +constexpr wchar_t ELLIPSIS = 0x2026; + +constexpr int SPRITE_IDENT = ('P' << 24) | ('S' << 16) | ('D' << 8) | 'I'; +constexpr int SPRITE_VERSION = 2; +constexpr int SPRITE_INDEXALPHA = 2; +constexpr int SPRITE_ALPHATEST = 3; +constexpr int SPRITE_MAX_SIZE = 1024; + +//! Without blending, darker texels of an additive sprite would draw as a dark fringe +constexpr int SPRITE_ALPHA_TEST_MIN = 48; + +//! Sprite textures of the software renderer, one per drawn size; VGUI2 can't delete textures, so they are reused +constexpr int MAX_SPRITE_TEXTURES = 64; + +constexpr int TEXTURE_NOT_CREATED = -2; +constexpr int TEXTURE_FAILED = -1; + +struct SpriteTexture +{ + int id = TEXTURE_NOT_CREATED; + unsigned lastUse = 0; +}; + +//! Sprite textures by sprite index, wide and tall +std::map, SpriteTexture> s_SpriteTextures; +unsigned s_iSpriteTextureUse = 0; + +int GetBadgePadding(const ScoreCellStyle &style) +{ + return vgui2::surface()->GetFontTall(style.hBadgeFont) / 3; +} + +//! Reads the colors of rectangle rc of the first frame of a sprite file, 3 bytes per texel +bool LoadSpriteRGB(const char *path, const wrect_t &rc, std::vector &rgb, int &wide, int &tall) +{ + int length = 0; + unsigned char *file = gEngfuncs.COM_LoadFile(path, 5, &length); + + if (!file) + return false; + + int pos = 0; + auto fnRead = [&](void *dest, int size) { + if (size < 0 || pos + size > length) + return false; + + memcpy(dest, file + pos, size); + pos += size; + return true; + }; + + // dsprite_t: ident, version, type, texFormat, boundingradius, width, height, numframes, beamlength, synctype + int header[10]; + short paletteSize = 0; + unsigned char palette[256][3]; + int frameType = 0; + int frame[4]; // origin x, origin y, width, height + + bool bValid = fnRead(header, sizeof(header)) && header[0] == SPRITE_IDENT && header[1] == SPRITE_VERSION && header[7] > 0 + && fnRead(&paletteSize, sizeof(paletteSize)) && paletteSize > 0 && paletteSize <= 256 + && fnRead(palette, paletteSize * 3) && fnRead(&frameType, sizeof(frameType)) && frameType == 0 + && fnRead(frame, sizeof(frame)) && frame[2] > 0 && frame[3] > 0 && frame[2] <= SPRITE_MAX_SIZE && frame[3] <= SPRITE_MAX_SIZE + && pos + frame[2] * frame[3] <= length; + + if (bValid) + { + int texFormat = header[3]; + int x0 = std::clamp(rc.left, 0, frame[2]); + int x1 = std::clamp(rc.right, x0, frame[2]); + int y0 = std::clamp(rc.top, 0, frame[3]); + int y1 = std::clamp(rc.bottom, y0, frame[3]); + const unsigned char *pixels = file + pos; + wide = x1 - x0; + tall = y1 - y0; + rgb.assign(wide * tall * 3, 0); + + for (int y = 0; y < tall; y++) + { + for (int x = 0; x < wide; x++) + { + int index = pixels[(y0 + y) * frame[2] + x0 + x]; + unsigned char *out = &rgb[(y * wide + x) * 3]; + + for (int i = 0; i < 3; i++) + { + if (texFormat == SPRITE_INDEXALPHA) + out[i] = paletteSize == 256 ? palette[255][i] * index / 255 : 0; + else if (texFormat == SPRITE_ALPHATEST && index == 255) + out[i] = 0; + else + out[i] = index < paletteSize ? palette[index][i] : 0; + } + } + } + + bValid = wide > 0 && tall > 0; + } + + gEngfuncs.COM_FreeFile(file); + return bValid; +} + +//! Sprite files have indexes -2, -3, ...: gHUD.GetSprite and gHUD.GetSpriteRect take them as no sprite +constexpr int FILE_SPRITE_FIRST = -2; + +//! The engine has 256 HUD sprite slots and stops with an error when they run out +constexpr int MAX_FILE_SPRITES = 32; + +struct FileSprite +{ + char szPath[bhl::sb::MAX_TEXT_LEN + 1] = {}; + HSPRITE hSprite = 0; + wrect_t rc = {}; + bool bTried = false; //!< Loaded or failed since the last reset +}; + +//! Sprite files by index, kept for the whole game so an index always means the same path +FileSprite s_FileSprites[MAX_FILE_SPRITES]; +int s_iFileSpriteCount = 0; + +FileSprite *GetFileSprite(int sprite) +{ + int i = FILE_SPRITE_FIRST - sprite; + return i >= 0 && i < s_iFileSpriteCount ? &s_FileSprites[i] : nullptr; +} + +HSPRITE GetSpriteHandle(int sprite) +{ + if (sprite >= 0) + return gHUD.GetSprite(sprite); + + FileSprite *pFile = GetFileSprite(sprite); + return pFile ? pFile->hSprite : 0; +} + +struct ScaleTap +{ + int index; + float weight; +}; + +/** + * Returns the source texels of destination pixel i when srcSize texels are scaled to dstSize pixels: + * the two nearest ones with linear weights when the image grows, the covered ones when it shrinks. + */ +std::vector GetScaleTaps(int i, int srcSize, int dstSize) +{ + std::vector taps; + float scale = (float)srcSize / dstSize; + + if (scale <= 1.0f) + { + float center = (i + 0.5f) * scale - 0.5f; + int i0 = (int)floorf(center); + float frac = center - i0; + taps.push_back({ std::clamp(i0, 0, srcSize - 1), 1.0f - frac }); + taps.push_back({ std::clamp(i0 + 1, 0, srcSize - 1), frac }); + } + else + { + int i0 = (int)(i * scale); + int i1 = std::clamp((int)((i + 1) * scale), i0 + 1, srcSize); + + for (int j = i0; j < i1; j++) + taps.push_back({ j, 1.0f / (i1 - i0) }); + } + + return taps; +} + +/** + * Scales the sprite colors to the drawn size, so the software renderer doesn't scale them into blocks. + * Pixels bright enough are opaque, the rest transparent: the texture is drawn without blending. + */ +void ScaleSpriteToRGBA(const std::vector &rgb, int srcWide, int srcTall, int wide, int tall, std::vector &rgba) +{ + std::vector> tapsX(wide); + std::vector> tapsY(tall); + + for (int x = 0; x < wide; x++) + tapsX[x] = GetScaleTaps(x, srcWide, wide); + + for (int y = 0; y < tall; y++) + tapsY[y] = GetScaleTaps(y, srcTall, tall); + + rgba.assign(wide * tall * 4, 0); + + for (int y = 0; y < tall; y++) + { + for (int x = 0; x < wide; x++) + { + float color[3] = {}; + + for (const ScaleTap &ty : tapsY[y]) + { + for (const ScaleTap &tx : tapsX[x]) + { + const unsigned char *texel = &rgb[(ty.index * srcWide + tx.index) * 3]; + + for (int i = 0; i < 3; i++) + color[i] += texel[i] * tx.weight * ty.weight; + } + } + + unsigned char *out = &rgba[(y * wide + x) * 4]; + + if (std::max({ color[0], color[1], color[2] }) < SPRITE_ALPHA_TEST_MIN) + continue; + + for (int i = 0; i < 3; i++) + out[i] = static_cast(std::clamp(color[i] + 0.5f, 0.0f, 255.0f)); + + out[3] = 255; + } + } +} + +int GetSpriteTexture(int sprite, int wide, int tall) +{ + SpriteTexture &texture = s_SpriteTextures[{ sprite, wide, tall }]; + texture.lastUse = ++s_iSpriteTextureUse; + + if (texture.id != TEXTURE_NOT_CREATED) + return texture.id; + + texture.id = TEXTURE_FAILED; + + const model_t *model = gEngfuncs.GetSpritePointer(GetSpriteHandle(sprite)); + std::vector rgb; + std::vector rgba; + int srcWide = 0; + int srcTall = 0; + + if (!model || !LoadSpriteRGB(model->name, GetScoreSpriteRect(sprite), rgb, srcWide, srcTall)) + return TEXTURE_FAILED; + + ScaleSpriteToRGBA(rgb, srcWide, srcTall, wide, tall, rgba); + + // Over the limit the texture of the least recently drawn size is reused + int id = TEXTURE_FAILED; + + if (s_SpriteTextures.size() > MAX_SPRITE_TEXTURES) + { + // Created textures come first, by their last use + auto oldest = std::min_element(s_SpriteTextures.begin(), s_SpriteTextures.end(), [](const auto &a, const auto &b) { + return a.second.id >= 0 && (b.second.id < 0 || a.second.lastUse < b.second.lastUse); + }); + + if (oldest->second.id >= 0) + { + id = oldest->second.id; + s_SpriteTextures.erase(oldest); + } + } + + bool bReused = id != TEXTURE_FAILED; + + if (!bReused) + id = vgui2::surface()->CreateNewTextureID(true); + + vgui2::surface()->DrawSetTextureRGBA(id, rgba.data(), wide, tall, false, bReused); + texture.id = id; + return id; +} + +} + +void CScoreCellImage::Clear() +{ + m_Kind = Kind::Text; + m_bMarkLast = false; + m_iSprite = -1; + m_iCur = 0; + m_iMax = 0; + m_wszText[0] = L'\0'; + m_wszBadges[0] = L'\0'; + m_iBadgesLen = 0; + m_iBadgeCount = 0; +} + +void CScoreCellImage::SetValue(const CScoreboardData::Column &column, const CScoreboardData::Value &value) +{ + Clear(); + m_bMarkLast = column.IsMarkLast(); + value.ToString(m_wszText, sizeof(m_wszText)); + + bhl::sb::E_Display display = column.display; + + if (value.type == bhl::sb::E_ValueType::Progress && value.iMax > 0 + && (display == bhl::sb::E_Display::Meter || display == bhl::sb::E_Display::Steps)) + { + m_Kind = display == bhl::sb::E_Display::Meter ? Kind::Meter : Kind::Steps; + m_iCur = value.iValue; + m_iMax = value.iMax; + return; + } + + if (value.type == bhl::sb::E_ValueType::Icon && display == bhl::sb::E_Display::Icon && value.szSprite[0]) + m_iSprite = GetScoreSpriteIndex(value.szSprite); +} + +void CScoreCellImage::SetText(const wchar_t *text) +{ + Clear(); + V_wcsncpy(m_wszText, text, sizeof(m_wszText)); +} + +void CScoreCellImage::AddBadge(const CScoreboardData::Value &value) +{ + wchar_t text[BADGES_LEN]; + value.ToString(text, sizeof(text)); + int len = static_cast(wcslen(text)); + + if (len == 0 || m_iBadgesLen + len + 1 > BADGES_LEN) + return; + + memcpy(m_wszBadges + m_iBadgesLen, text, (len + 1) * sizeof(wchar_t)); + m_iBadgesLen += len + 1; + m_iBadgeCount++; +} + +void CScoreCellImage::Paint() +{ + if (m_Kind == Kind::Meter) + PaintMeter(); + else if (m_Kind == Kind::Steps) + PaintSteps(); + else + PaintText(); +} + +int CScoreCellImage::GetAreaWide() const +{ + return std::max(m_iWide - m_Style.iMargin, 0); +} + +int CScoreCellImage::GetAlignOffset(int contentWide, int areaWide) +{ + int freeWide = std::max(areaWide - contentWide, 0); + return m_iAlign == 1 ? freeWide / 2 : (m_iAlign == 2 ? freeWide : 0); +} + +int CScoreCellImage::GetBadgesWide(int maxWide, int &count) +{ + const wchar_t *badge = m_wszBadges; + int wide = 0; + count = 0; + + for (int i = 0; i < m_iBadgeCount; i++) + { + int badgeWide = m_Style.iSpacing + GetScoreBadgeWide(m_Style, badge); + + if (wide + badgeWide > maxWide) + break; + + wide += badgeWide; + count++; + badge += wcslen(badge) + 1; + } + + return wide; +} + +void CScoreCellImage::PaintBadges(int x, int yCenter, int count) +{ + const wchar_t *badge = m_wszBadges; + + for (int i = 0; i < count; i++) + { + x += m_Style.iSpacing; + DrawScoreBadge(m_Style, x, yCenter, badge); + x += GetScoreBadgeWide(m_Style, badge); + badge += wcslen(badge) + 1; + } +} + +void CScoreCellImage::PaintText() +{ + vgui2::HFont font = m_Style.hFont; + int spacing = m_Style.iSpacing; + int yCenter = m_iY + m_iTall / 2; + int areaWide = GetAreaWide(); + + // Sprite scaled to the row height with its aspect ratio kept + const wrect_t &rc = GetScoreSpriteRect(m_iSprite); + int iconWide = 0; + int iconTall = 0; + + if (rc.GetWidth() > 0 && rc.GetHeight() > 0) + { + iconTall = std::max(m_iTall - 2 * spacing, 1); + iconWide = rc.GetWidth() * iconTall / rc.GetHeight(); + + if (iconWide > areaWide) + { + iconWide = areaWide; + iconTall = rc.GetHeight() * iconWide / rc.GetWidth(); + } + } + + // Badges come first: the text is cut to the rest + int iconSpace = iconWide > 0 ? iconWide + spacing : 0; + int badgeCount = 0; + int badgesWide = GetBadgesWide(areaWide - iconSpace, badgeCount); + + wchar_t text[ARRAYSIZE(m_wszText)]; + V_wcsncpy(text, m_wszText, sizeof(text)); + int textWide = FitCellText(font, text, std::max(areaWide - iconSpace - badgesWide, 0)); + + int x = m_iX + GetAlignOffset(iconSpace + textWide + badgesWide, areaWide); + + if (iconWide > 0 && iconTall > 0) + { + DrawScoreSprite(m_iSprite, x, yCenter - iconTall / 2, iconWide, iconTall, m_Style.iconColor); + x += iconSpace; + } + + // The text stands where a label puts it, so it lines up with text columns + if (text[0]) + DrawCellText(font, x, m_iY + (m_iTall - vgui2::surface()->GetFontTall(font)) / 2, m_Color, text); + + PaintBadges(x + textWide, yCenter, badgeCount); +} + +void CScoreCellImage::PaintMeter() +{ + vgui2::HFont font = m_Style.hFont; + int maxDots = bhl::sb::MAX_DOTS; + bool bBar = m_iMax > maxDots; + int badgeCount = 0; + int cellWide = GetAreaWide(); + int badgesWide = GetBadgesWide(cellWide, badgeCount); + int areaWide = cellWide - badgesWide; + + // Only the bar has a counter: dots are easy to count + int counterSpace = bBar ? m_Style.iSpacing + GetCellTextWide(font, m_wszText) : 0; + + int gap = m_Style.iDotGap; + int dot = (areaWide - counterSpace - (maxDots - 1) * gap) / maxDots; + dot = std::min(std::min(dot, m_Style.iDotSize), m_iTall); + + // The bar has the length of a full row of dots + int barWide = dot > 0 ? maxDots * dot + (maxDots - 1) * gap : 0; + int contentWide = bBar ? barWide + counterSpace : std::max(m_iMax * (dot + gap) - gap, 0); + int x = m_iX + GetAlignOffset(contentWide + badgesWide, cellWide); + int y = m_iY + (m_iTall - dot) / 2; + int cur = std::clamp(m_iCur, 0, m_iMax); + + if (dot > 0 && !bBar) + { + for (int i = 0; i < m_iMax; i++) + { + int dotX = x + i * (dot + gap); + DrawRoundedBox(dotX, y, dotX + dot, y + dot, dot / 2, i < cur ? m_Style.filledColor : m_Style.emptyColor); + } + } + else if (dot > 0) + { + DrawRoundedBox(x, y, x + barWide, y + dot, dot / 2, m_Style.emptyColor); + + if (cur > 0) + DrawRoundedBox(x, y, x + std::max(barWide * cur / m_iMax, dot), y + dot, dot / 2, m_Style.filledColor); + } + + if (bBar) + DrawCellText(font, x + barWide + m_Style.iSpacing, m_iY + (m_iTall - vgui2::surface()->GetFontTall(font)) / 2, m_Color, m_wszText); + + PaintBadges(x + contentWide, m_iY + m_iTall / 2, badgeCount); +} + +void CScoreCellImage::PaintSteps() +{ + vgui2::HFont font = m_Style.hFont; + + // The strip takes the width that the badges leave + int badgeCount = 0; + int cellWide = GetAreaWide(); + int badgesWide = GetBadgesWide(cellWide, badgeCount); + int stripWide = cellWide - badgesWide; + + int textTall = vgui2::surface()->GetFontTall(font); + int stripTall = m_Style.iStripTall; + int y = m_iY + (m_iTall - (textTall + m_Style.iStripGap + stripTall)) / 2; + DrawCellText(font, m_iX + GetAlignOffset(GetCellTextWide(font, m_wszText), stripWide), y, m_Color, m_wszText); + PaintBadges(m_iX + stripWide, m_iY + m_iTall / 2, badgeCount); + + int stripY = y + textTall + m_Style.iStripGap; + + if (m_iMax * 2 > stripWide) + { + // Too many steps for separate segments + int fillWide = stripWide * std::clamp(m_iCur, 0, m_iMax) / m_iMax; + vgui2::surface()->DrawSetColor(m_Style.filledColor); + vgui2::surface()->DrawFilledRect(m_iX, stripY, m_iX + fillWide, stripY + stripTall); + vgui2::surface()->DrawSetColor(m_Style.emptyColor); + vgui2::surface()->DrawFilledRect(m_iX + fillWide, stripY, m_iX + stripWide, stripY + stripTall); + return; + } + + int gap = m_iMax * 3 <= stripWide ? 1 : 0; + + for (int i = 0; i < m_iMax; i++) + { + int x0 = m_iX + i * (stripWide + gap) / m_iMax; + int x1 = m_iX + (i + 1) * (stripWide + gap) / m_iMax - gap; + Color color; + + if (i == m_iCur - 1) + color = m_Style.currentColor; + else if (i < m_iCur - 1) + color = m_Style.filledColor; + else if (m_bMarkLast && i == m_iMax - 1) + color = m_Style.lastColor; + else + color = m_Style.emptyColor; + + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x0, stripY, x1, stripY + stripTall); + } +} + +void DrawRoundedBox(int x0, int y0, int x1, int y1, int radius, Color color, int clipX1) +{ + radius = std::min(radius, std::min(x1 - x0, y1 - y0) / 2); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x0, y0 + radius, std::min(x1, clipX1), y1 - radius); + + for (int i = 0; i < radius; i++) + { + float dy = radius - i - 0.5f; + int inset = (int)(radius - sqrtf(radius * radius - dy * dy) + 0.5f); + int right = std::min(x1 - inset, clipX1); + + if (x0 + inset >= right) + continue; + + vgui2::surface()->DrawFilledRect(x0 + inset, y0 + i, right, y0 + i + 1); + vgui2::surface()->DrawFilledRect(x0 + inset, y1 - i - 1, right, y1 - i); + } +} + +void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text) +{ + int padding = GetBadgePadding(style); + int tall = vgui2::surface()->GetFontTall(style.hBadgeFont); + int y = yCenter - tall / 2; + + DrawRoundedBox(x, y, x + GetScoreBadgeWide(style, text), y + tall, padding, style.badgeBgColor); + DrawCellText(style.hBadgeFont, x + padding, y, style.badgeFgColor, text); +} + +int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text) +{ + return GetCellTextWide(style.hBadgeFont, text) + 2 * GetBadgePadding(style); +} + +void DrawScoreSprite(int sprite, int x, int y, int wide, int tall, Color color) +{ + HSPRITE hSprite = GetSpriteHandle(sprite); + + if (hSprite <= 0 || wide <= 0 || tall <= 0 || wide > SPRITE_MAX_SIZE || tall > SPRITE_MAX_SIZE) + return; + + // Neither way blends with the alpha of the color, a dimmer color stands in for translucency + int r = color.r() * color.a() / 255; + int g = color.g() * color.a() / 255; + int b = color.b() * color.a() / 255; + + if (CHudRenderer::Get().IsAvailable()) + { + // VGUI2 buffers text and draws it with the texture bound at the flush, which would be the sprite after TriangleAPI + vgui2::surface()->DrawFlushText(); + + // TriangleAPI sets its own blending, while VGUI2 turns blending off once a panel has drawn text + CHudRenderer::SpriteSet(hSprite, r, g, b); + CHudRenderer::SpriteDrawAdditiveScaled(0, x, y, wide, tall, &GetScoreSpriteRect(sprite)); + return; + } + + int texture = GetSpriteTexture(sprite, wide, tall); + + if (texture == TEXTURE_FAILED) + return; + + vgui2::surface()->DrawSetTexture(texture); + vgui2::surface()->DrawSetColor(Color(r, g, b, 255)); + vgui2::surface()->DrawTexturedRect(x, y, x + wide, y + tall); +} + +void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text) +{ + vgui2::surface()->DrawSetTextFont(font); + vgui2::surface()->DrawSetTextColor(color); + vgui2::surface()->DrawSetTextPos(x, y); + vgui2::surface()->DrawPrintText(text, wcslen(text)); +} + +int GetCellTextWide(vgui2::HFont font, const wchar_t *text) +{ + int wide = 0; + + for (; *text; text++) + wide += vgui2::surface()->GetCharacterWidth(font, *text); + + return wide; +} + +int FitCellText(vgui2::HFont font, wchar_t *text, int maxWide) +{ + int wide = GetCellTextWide(font, text); + + if (wide <= maxWide) + return wide; + + int ellipsisWide = vgui2::surface()->GetCharacterWidth(font, ELLIPSIS); + + if (ellipsisWide > maxWide) + { + text[0] = L'\0'; + return 0; + } + + int len = 0; + wide = 0; + + for (; text[len]; len++) + { + int charWide = vgui2::surface()->GetCharacterWidth(font, text[len]); + + if (wide + charWide + ellipsisWide > maxWide) + break; + + wide += charWide; + } + + text[len] = ELLIPSIS; + text[len + 1] = L'\0'; + return wide + ellipsisWide; +} + +int GetScoreSpriteIndex(const char *name) +{ + if (!bhl::sb::IsSpriteFilePath(name)) + return gHUD.GetSpriteIndex(name); + + int i = 0; + + while (i < s_iFileSpriteCount && Q_stricmp(s_FileSprites[i].szPath, name)) + i++; + + if (i == s_iFileSpriteCount) + { + if (i == MAX_FILE_SPRITES) + return -1; + + V_strcpy_safe(s_FileSprites[i].szPath, name); + s_iFileSpriteCount++; + } + + FileSprite &file = s_FileSprites[i]; + std::vector rgb; + int wide = 0; + int tall = 0; + + // The engine stops with an error on a missing file when developer is above 1, and on a broken one always: + // the file is read and checked first + if (!file.bTried && LoadSpriteRGB(file.szPath, wrect_t { 0, SPRITE_MAX_SIZE, 0, SPRITE_MAX_SIZE }, rgb, wide, tall)) + { + file.hSprite = gEngfuncs.pfnSPR_Load(file.szPath); + file.rc = wrect_t { 0, wide, 0, tall }; + } + + file.bTried = true; + return file.hSprite > 0 ? FILE_SPRITE_FIRST - i : -1; +} + +const wrect_t &GetScoreSpriteRect(int sprite) +{ + static const wrect_t empty = {}; + + if (sprite >= 0) + return gHUD.GetSpriteRect(sprite); + + FileSprite *pFile = GetFileSprite(sprite); + return pFile && pFile->hSprite > 0 ? pFile->rc : empty; +} + +void ResetScoreSpriteFiles() +{ + for (int i = 0; i < s_iFileSpriteCount; i++) + { + s_FileSprites[i].hSprite = 0; + s_FileSprites[i].bTried = false; + } +} diff --git a/src/game/client/vgui/score_panel_cells.h b/src/game/client/vgui/score_panel_cells.h new file mode 100644 index 00000000..68c344e3 --- /dev/null +++ b/src/game/client/vgui/score_panel_cells.h @@ -0,0 +1,163 @@ +#ifndef VGUI_SCORE_PANEL_CELLS_H +#define VGUI_SCORE_PANEL_CELLS_H +#include +#include +#include +#include +#include "scoreboard_data.h" + +/** + * Fonts, colors and sizes of custom scoreboard cells, which keep a reference to it: + * CScorePanel owns the style of the rows, each CSectionHeader a copy with its font. + * Fills are drawn opaque: after text the engine may draw translucent fills without blending. + */ +struct ScoreCellStyle +{ + vgui2::HFont hFont = vgui2::INVALID_FONT; + vgui2::HFont hBadgeFont = vgui2::INVALID_FONT; + Color filledColor; //!< Filled dots and bar, passed steps + Color emptyColor; //!< Empty dots and bar, next steps + Color currentColor; //!< Current step + Color lastColor; //!< Last step + Color badgeBgColor; + Color badgeFgColor; + Color iconColor; //!< Tint of sprite icons + int iDotSize = 0; //!< Maximum diameter of a dot + int iDotGap = 0; + int iStripTall = 0; //!< Height of the steps strip + int iStripGap = 0; //!< Distance between the steps text and the strip + int iSpacing = 0; //!< Distance between icon, text, badge and counter + int iMargin = 0; //!< Free width at the right of a cell, so its content doesn't touch the next column +}; + +/** + * Image of a custom scoreboard cell: text, icon, meter or steps, followed by badges. + * Draws within the bounds set by the row or the section header. An empty cell draws only its badges. + * Texts are drawn as they are: a VGUI2 text image would take '&' for a hotkey mark. + */ +class CScoreCellImage : public vgui2::IImage +{ +public: + CScoreCellImage(const ScoreCellStyle &style) + : m_Style(style) + { + } + + //! Sets a value of the store drawn as the column shows it (docs/scoreboard-protocol.md, 6.6). Clears the badges. + void SetValue(const CScoreboardData::Column &column, const CScoreboardData::Value &value); + + //! Sets a text, drawn like a Text cell. Clears the badges. + void SetText(const wchar_t *text); + + /** + * Adds the text of a value as a badge after the content (6.7). Badges are drawn in the order they were added, + * as many as fit into the cell. A value with an empty text adds nothing. + */ + void AddBadge(const CScoreboardData::Value &value); + + //! @param align 0 left, 1 center, 2 right + void SetAlign(int align) { m_iAlign = align; } + + // IImage overrides + virtual void Paint() override; + + virtual void SetPos(int x, int y) override + { + m_iX = x; + m_iY = y; + } + + virtual void GetContentSize(int &wide, int &tall) override + { + wide = m_iWide; + tall = m_iTall; + } + + virtual void GetSize(int &wide, int &tall) override { GetContentSize(wide, tall); } + + virtual void SetSize(int wide, int tall) override + { + m_iWide = wide; + m_iTall = tall; + } + + virtual void SetColor(Color col) override { m_Color = col; } + +private: + enum class Kind + { + Text, + Meter, + Steps, + }; + + //! Room for the badge texts of one cell, each with its NUL + static constexpr int BADGES_LEN = 128; + + const ScoreCellStyle &m_Style; + Kind m_Kind = Kind::Text; + bool m_bMarkLast = false; + int m_iAlign = 0; + int m_iX = 0, m_iY = 0; + int m_iWide = 0, m_iTall = 0; + int m_iSprite = -1; + int m_iCur = 0, m_iMax = 0; + Color m_Color = Color(255, 255, 255, 255); + wchar_t m_wszText[128] = {}; //!< Text of the value, also the counter of Meter and Steps + wchar_t m_wszBadges[BADGES_LEN] = {}; //!< Badge texts one after another + int m_iBadgesLen = 0; //!< Used part of m_wszBadges + int m_iBadgeCount = 0; + + void Clear(); + int GetAreaWide() const; + int GetAlignOffset(int contentWide, int areaWide); + + /** + * Returns the width of the first badges that fit into maxWide, each with the spacing before it. + * @param count Receives the number of these badges + */ + int GetBadgesWide(int maxWide, int &count); + + //! Draws the first count badges after x + void PaintBadges(int x, int yCenter, int count); + + void PaintText(); + void PaintMeter(); + void PaintSteps(); +}; + +/** + * Draws a box with round corners line by line, so it doesn't depend on alpha blending. + * @param clipX1 Only the part left of it is drawn + */ +void DrawRoundedBox(int x0, int y0, int x1, int y1, int radius, Color color, int clipX1 = INT_MAX); + +//! Draws a badge vertically centered on yCenter +void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text); + +int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text); + +//! Draws a sprite from GetScoreSpriteIndex stretched to wide x tall and tinted with color, additively like the HUD (6.6) +void DrawScoreSprite(int sprite, int x, int y, int wide, int tall, Color color); + +/** + * Sprite of an Icon value for DrawScoreSprite: a name from hud.txt, or the path "sprites/.spr" of a sprite file + * the server precaches (4.3). A file is loaded on first use and drawn whole. -1 if the client doesn't have the sprite. + */ +int GetScoreSpriteIndex(const char *name); + +//! Rectangle of a sprite from GetScoreSpriteIndex, empty for -1 or a file that isn't loaded +const wrect_t &GetScoreSpriteRect(int sprite); + +//! Forgets the handles of sprite files: the engine reloads its sprite list on a new map +void ResetScoreSpriteFiles(); + +void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text); + +//! Returns the width of a text drawn by DrawCellText +int GetCellTextWide(vgui2::HFont font, const wchar_t *text); + +//! Cuts a text with an ellipsis to fit into maxWide. Returns the width of the result. +int FitCellText(vgui2::HFont font, wchar_t *text, int maxWide); + +#endif diff --git a/src/game/server/CBugfixedServer.cpp b/src/game/server/CBugfixedServer.cpp index e2f25171..367253bb 100644 --- a/src/game/server/CBugfixedServer.cpp +++ b/src/game/server/CBugfixedServer.cpp @@ -21,6 +21,28 @@ CBugfixedServer *serverapi() return &g_staticserver; } +CON_COMMAND(bhl_caps, "Prints capabilities of connected clients") +{ + serverapi()->PrintClientCaps(); +} + +//! Parses "_bhl": 1 to 8 hex digits without a sign, spaces or prefix, anything else is 0. Unknown bits are dropped. +static bhl::E_ClientCaps ParseClientCaps(const char *value) +{ + size_t len = strlen(value); + + if (len > 8 || strspn(value, "0123456789abcdefABCDEF") != len) + return bhl::E_ClientCaps::None; + + return (bhl::E_ClientCaps)(strtoul(value, nullptr, 16) & (unsigned long)bhl::E_ClientCaps::All); +} + +static bool IsProxy(edict_t *pEntity) +{ + const char *authId = GETPLAYERAUTHID(pEntity); + return (pEntity->v.flags & FL_PROXY) || (authId && !strcmp(authId, "HLTV")); +} + //---------------------------------------------------------------------------------------------------- // CBugfixedServer //---------------------------------------------------------------------------------------------------- @@ -41,6 +63,16 @@ void CBugfixedServer::ClientConnect(edict_t *pEntity) ResetPlayerData(idx); const char *authId = GETPLAYERAUTHID(pEntity); + m_pClientInfo[idx].isConnected = true; + m_pClientInfo[idx].isBot = (pEntity->v.flags & FL_FAKECLIENT) || (authId && !strcmp(authId, "BOT")); + m_pClientInfo[idx].isProxy = IsProxy(pEntity); + + // The engine's ClientUserInfoChanged ran before ClientConnect, ResetPlayerData dropped its caps + ClientUserInfoChanged(pEntity, g_engfuncs.pfnGetInfoKeyBuffer(pEntity)); + + if ((m_pClientInfo[idx].isBot || m_pClientInfo[idx].isProxy) && m_pClientInfo[idx].capsSource == CAPS_SOURCE_UNKNOWN) + m_pClientInfo[idx].capsSource = CAPS_SOURCE_NONE; + // Bots can't receive network messages if (pEntity->v.flags & FL_FAKECLIENT) { @@ -78,6 +110,22 @@ void CBugfixedServer::PlayerPostThink(edict_t *pEntity) CheckClientSteamID(pEntity); m_pClientInfo[idx].nextAuthCheck = gpGlobals->time + 0.1; } + + if (m_pClientInfo[idx].isCapsQueryDeferred && gpGlobals->time >= m_pClientInfo[idx].nextCapsQuery) + { + QueryClientCaps(pEntity); + m_pClientInfo[idx].nextCapsQuery = gpGlobals->time + 0.1; + } + + // A changed client setting reaches the server only with a new answer + if (m_pClientInfo[idx].capsSource == CAPS_SOURCE_QUERY + && m_pClientInfo[idx].isReady + && m_Scoreboard.IsActive() + && gpGlobals->time >= m_pClientInfo[idx].nextCapsRequery) + { + m_pClientInfo[idx].nextCapsRequery = gpGlobals->time + CAPS_REQUERY_INTERVAL; + g_engfuncs.pfnQueryClientCvarValue2(pEntity, bhl::sb::CAPS_KEY, REQUESTID_CAPS); + } } void CBugfixedServer::CvarValueCallback(const edict_t *pEnt, int requestID, const char *cvarName, const char *value) @@ -106,6 +154,13 @@ void CBugfixedServer::CvarValueCallback(const edict_t *pEnt, int requestID, cons int iValue = atoi(value); m_pClientInfo[idx].isColorEnabled = (iValue == 1); } + else if (requestID == REQUESTID_CAPS && !strcmp(cvarName, bhl::sb::CAPS_KEY)) + { + // Other plugins get their answers here too, hence the name check. + // Userinfo wins over a late answer. + if (m_pClientInfo[idx].isCapsQueried && m_pClientInfo[idx].capsSource != CAPS_SOURCE_USERINFO) + SetClientCaps(idx, ParseClientCaps(value), CAPS_SOURCE_QUERY); + } } bool CBugfixedServer::IsClientSupportsReceived(int index) @@ -113,9 +168,102 @@ bool CBugfixedServer::IsClientSupportsReceived(int index) return m_pClientInfo[index].isSupportsReceived; } +void CBugfixedServer::ClientUserInfoChanged(edict_t *pEntity, char *infobuffer) +{ + int idx = ENTINDEX(pEntity); + if (idx < 1 || idx > gpGlobals->maxClients) + return; + + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + const char *value = g_engfuncs.pfnInfoKeyValue(infobuffer, bhl::sb::CAPS_KEY); + + if (value[0]) + { + SetClientCaps(idx, ParseClientCaps(value), CAPS_SOURCE_USERINFO); + } + else if (clientInfo.capsSource == CAPS_SOURCE_USERINFO) + { + clientInfo.capsSource = CAPS_SOURCE_UNKNOWN; + clientInfo.isCapsQueried = false; + + if (clientInfo.isReady) + QueryClientCaps(pEntity); + } +} + +void CBugfixedServer::ClientDisconnect(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + if (idx < 1 || idx > gpGlobals->maxClients) + return; + + ResetPlayerData(idx); +} + +void CBugfixedServer::InitHUD(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + + clientInfo.isReady = true; + clientInfo.isProxy = clientInfo.isProxy || IsProxy(pEntity); + + // Also without caps and when inactive: caps that arrive later and an extension + // turned on later must still wait for the InitHUD burst + m_Scoreboard.StartFullSync(idx, true); + + QueryClientCaps(pEntity); +} + +void CBugfixedServer::StartFrame() +{ + // The engine calls ClientDisconnect only for spawned clients. A client dropped while it loads + // the map or downloads resources is seen only by its edict having no userid any more. + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (m_pClientInfo[i].isConnected && GETPLAYERUSERID(INDEXENT(i)) == -1) + ResetPlayerData(i); + } + + m_Scoreboard.StartFrame(); +} + +void CBugfixedServer::ServerDeactivate() +{ + // Clients that stay connect again on the new map. A slot dropped before spawning on this map + // gets an edict again there, so StartFrame could no longer see that it is empty. + for (bhl_client_info_t &clientInfo : m_pClientInfo) + clientInfo.isConnected = clientInfo.isReady = false; + + m_Scoreboard.ClearAll(); +} + +void CBugfixedServer::QueryUnknownClientCaps() +{ + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (m_pClientInfo[i].isReady) + QueryClientCaps(INDEXENT(i)); + } +} + +void CBugfixedServer::PrintClientCaps() +{ + static const char *sourceNames[] = { "unknown", "userinfo", "query", "none" }; + + g_engfuncs.pfnServerPrint(UTIL_VarArgs("%4s %-32s %8s %s\n", "slot", "name", "caps", "source")); + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (m_pClientInfo[i].isConnected) + g_engfuncs.pfnServerPrint(UTIL_VarArgs("%4d %-32s %8x %s\n", i, STRING(INDEXENT(i)->v.netname), (unsigned int)GetClientCaps(i), sourceNames[m_pClientInfo[i].capsSource])); + } +} + void CBugfixedServer::ResetPlayerData(int idx) { m_pClientInfo[idx] = bhl_client_info_t(); + m_Scoreboard.ClearPlayer(idx); } void CBugfixedServer::CheckClientSteamID(edict_t *pEntity) @@ -187,6 +335,50 @@ void CBugfixedServer::OnClientSupportsReceived(edict_t *pEntity) m_pClientInfo[ENTINDEX(pEntity)].isSupportsReceived = true; } +void CBugfixedServer::QueryClientCaps(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + + clientInfo.isCapsQueryDeferred = false; + + if (clientInfo.capsSource != CAPS_SOURCE_UNKNOWN || clientInfo.isCapsQueried) + return; + + if (!m_Scoreboard.IsActive() && !sv_bhl_query_vars.GetBool()) + return; + + const char *authId = GETPLAYERAUTHID(pEntity); + + // Bots and HLTV don't answer, p47 clients don't support QueryClientCvarValue2 + if (clientInfo.isBot || clientInfo.isProxy || (authId && (!strcmp(authId, "STEAM_ID_LAN") || !strncmp(authId, "VALVE_", 6)))) + { + SetClientCaps(idx, bhl::E_ClientCaps::None, CAPS_SOURCE_NONE); + } + else if (authId && strcmp(authId, "STEAM_ID_PENDING") != 0) + { + clientInfo.isCapsQueried = true; + clientInfo.nextCapsRequery = gpGlobals->time + CAPS_REQUERY_INTERVAL; + g_engfuncs.pfnQueryClientCvarValue2(pEntity, bhl::sb::CAPS_KEY, REQUESTID_CAPS); + } + else + { + clientInfo.isCapsQueryDeferred = true; + } +} + +void CBugfixedServer::SetClientCaps(int idx, bhl::E_ClientCaps caps, E_CapsSource source) +{ + bool hadScoreboard = IsScoreboardClient(idx); + + m_pClientInfo[idx].caps = caps; + m_pClientInfo[idx].capsSource = source; + + // A client that lost the cap is skipped by the scoreboard without a Reset + if (!hadScoreboard && IsScoreboardClient(idx)) + m_Scoreboard.StartFullSync(idx, false); +} + //---------------------------------------------------------------------------------------------------- // IBugfixedServer methods //---------------------------------------------------------------------------------------------------- @@ -351,3 +543,25 @@ void CBugfixedServer::SetPlayerScore(int idx, int frags, int deaths) pPlayer->m_iDeaths = deaths; pPlayer->SendScoreInfo(); } + +bhl::E_ClientCaps CBugfixedServer::GetClientCaps(int idx) +{ + if (idx < 1 || idx > gpGlobals->maxClients) + { + UTIL_LogPrintf("CBugfixedServer::GetClientCaps(): invalid player id (%d)\n", idx); + return bhl::E_ClientCaps::None; + } + + const bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + + // HudV1 alone would make a plugin drop its HUD texts for a client that gets no data + if (!clientInfo.isConnected || clientInfo.isBot || clientInfo.isProxy || !IsEnumFlagSet(clientInfo.caps, bhl::E_ClientCaps::ScoreboardV1)) + return bhl::E_ClientCaps::None; + + return clientInfo.caps; +} + +bhl::IScoreboardExt *CBugfixedServer::GetScoreboard() +{ + return &m_Scoreboard; +} diff --git a/src/game/server/CBugfixedServer.h b/src/game/server/CBugfixedServer.h index 6ba5ae04..88c09fd0 100644 --- a/src/game/server/CBugfixedServer.h +++ b/src/game/server/CBugfixedServer.h @@ -5,6 +5,7 @@ #include #include "eiface.h" #include "progdefs.h" +#include "CScoreboardExt.h" #ifndef BUGFIXEDAPI_REQUEST_BASE #define BUGFIXEDAPI_REQUEST_BASE 1 @@ -23,8 +24,25 @@ class CBugfixedServer : public bhl::IBugfixedServer void PlayerPostThink(edict_t *pEntity); void CvarValueCallback(const edict_t *pEnt, int requestID, const char *cvarName, const char *value); bool IsClientSupportsReceived(int index); + void ClientUserInfoChanged(edict_t *pEntity, char *infobuffer); + void ClientDisconnect(edict_t *pEntity); + void InitHUD(edict_t *pEntity); + void StartFrame(); + void ServerDeactivate(); + + bool IsClientConnected(int idx) { return m_pClientInfo[idx].isConnected; } + + //! Whether the client gets "BhlScore": passed InitHUD, has ScoreboardV1, not a bot or HLTV + bool IsScoreboardClient(int idx) { return m_pClientInfo[idx].isReady && IsEnumFlagSet(GetClientCaps(idx), bhl::E_ClientCaps::ScoreboardV1); } + + //! Queries "_bhl" from clients that passed InitHUD and haven't reported it + void QueryUnknownClientCaps(); + + void PrintClientCaps(); private: + static constexpr float CAPS_REQUERY_INTERVAL = 10.0f; //!< Seconds between "_bhl" queries of a client that answers them + enum E_RequestType { REQUEST_VERSION = 0, @@ -37,9 +55,18 @@ class CBugfixedServer : public bhl::IBugfixedServer REQUESTID_VERSION = 0, REQUESTID_SUPPORTS, REQUESTID_COLOR, + REQUESTID_CAPS, REQUESTID_END }; + enum E_CapsSource + { + CAPS_SOURCE_UNKNOWN = 0, + CAPS_SOURCE_USERINFO, + CAPS_SOURCE_QUERY, + CAPS_SOURCE_NONE + }; + struct bhl_client_info_t { CGameVersion version; @@ -49,17 +76,31 @@ class CBugfixedServer : public bhl::IBugfixedServer bool isAuthed = false; //!< Whether the player has received a SteamID float nextAuthCheck = 0; //!< Next time to check for SteamID bool isSupportsReceived = false; + + bool isConnected = false; + bool isReady = false; //!< InitHUD was sent + bool isBot = false; //!< Cached on connect because Spawn clears FL_FAKECLIENT + bool isProxy = false; //!< HLTV + bhl::E_ClientCaps caps = bhl::E_ClientCaps::None; //!< Known bits of "_bhl", GetClientCaps normalizes them + E_CapsSource capsSource = CAPS_SOURCE_UNKNOWN; + bool isCapsQueried = false; + bool isCapsQueryDeferred = false; //!< Waits for a SteamID + float nextCapsQuery = 0; //!< Next try of a deferred query + float nextCapsRequery = 0; //!< Next query while the source is CAPS_SOURCE_QUERY }; bhl_client_info_t m_pClientInfo[MAX_PLAYERS + 1]; CGameVersion m_ServerVersion; bhl::E_MotdType m_nMotdType = bhl::E_MotdType::All; + CScoreboardExt m_Scoreboard; void ResetPlayerData(int idx); void CheckClientSteamID(edict_t *pEntity); void QueryClientCvars(edict_t *pEntity); void QueryUnsupportedClientCvars(edict_t *pEntity); void OnClientSupportsReceived(edict_t *pEntity); + void QueryClientCaps(edict_t *pEntity); + void SetClientCaps(int idx, bhl::E_ClientCaps caps, E_CapsSource source); public: //---------------------------------------------------------------------------------------------------- @@ -77,6 +118,8 @@ class CBugfixedServer : public bhl::IBugfixedServer virtual void ShowMotdFromString(bhl::E_MotdType type, int idx, const char *str); virtual void ShowMotdFromFile(bhl::E_MotdType type, int idx, const char *file); virtual void SetPlayerScore(int idx, int frags, int deaths); + virtual bhl::E_ClientCaps GetClientCaps(int idx); + virtual bhl::IScoreboardExt *GetScoreboard(); }; CBugfixedServer *serverapi(); diff --git a/src/game/server/CMakeLists.txt b/src/game/server/CMakeLists.txt index abc27166..b85269f5 100644 --- a/src/game/server/CMakeLists.txt +++ b/src/game/server/CMakeLists.txt @@ -40,6 +40,8 @@ set( SOURCE_FILES controller.cpp crossbow.cpp crowbar.cpp + CScoreboardExt.cpp + CScoreboardExt.h decals.h defaultai.cpp defaultai.h diff --git a/src/game/server/CScoreboardExt.cpp b/src/game/server/CScoreboardExt.cpp new file mode 100644 index 00000000..641d0104 --- /dev/null +++ b/src/game/server/CScoreboardExt.cpp @@ -0,0 +1,1429 @@ +#include +#include +#include "extdll.h" +#include "util.h" +#include "cbase.h" +#include "gamerules.h" +#include "CBugfixedServer.h" +#include "CScoreboardExt.h" + +extern int gmsgBhlScore; + +//! Copies a string and truncates it on a UTF-8 character boundary +template +static void CopyString(char (&dst)[N], const char *src) +{ + if (!src) + src = ""; + + int len = (int)strlen(src); + + if (len >= (int)N) + { + len = (int)N - 1; + + while (len > 0 && ((unsigned char)src[len] & 0xC0) == 0x80) + len--; + } + + memcpy(dst, src, len); + dst[len] = '\0'; +} + +//! Index of the item with the key among the first count, -1 if none; "" matches nothing +template +static int FindKey(const T *items, int count, const char *key) +{ + if (!key || !key[0]) + return -1; + + for (int i = 0; i < count; i++) + { + if (!strcmp(items[i].key, key)) + return i; + } + + return -1; +} + +//! Returns a mask of the lowest count bits; count may be the width of T +template +static T GetLowBits(int count) +{ + return count >= (int)(sizeof(T) * 8) ? ~T(0) : (T(1) << count) - 1; +} + +static int ClampByte(int value) +{ + return std::clamp(value, 0, 255); +} + +static int ClampWord(int value) +{ + return std::clamp(value, 0, 65535); +} + +//---------------------------------------------------------------------------------------------------- +// CScoreboardExt +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::ClearAll() +{ + ClearState(); + m_iTeamCount = 0; + std::fill(std::begin(m_Clients), std::end(m_Clients), client_state_t()); + std::fill(std::begin(m_Pacing), std::end(m_Pacing), pacing_t()); +} + +void CScoreboardExt::ClearPlayer(int idx) +{ + bool hasCells = GetFilledCells(idx) != 0; + std::fill(std::begin(m_Cells[idx]), std::end(m_Cells[idx]), value_t()); + + for (client_state_t &state : m_Clients) + { + if (hasCells || state.cellsDirty[idx]) + state.targetsCleared.set(idx); + + state.cellsDirty[idx] = 0; + } + + // Overrides of the slot only change what this client gets, and its sync state starts anew + m_PlayerHud[idx] = player_hud_t(); + m_Clients[idx] = client_state_t(); + m_Pacing[idx] = pacing_t(); + m_Events[idx].clear(); +} + +void CScoreboardExt::StartFullSync(int idx, bool delay) +{ + client_state_t &state = m_Clients[idx]; + + if (delay) + m_Pacing[idx].nextSendTime = gpGlobals->time + FULL_SYNC_DELAY; + + state = client_state_t(); + state.isResetPending = true; + + if (!m_bActive) + return; + + state.isConfigPending = m_bHasConfig; + state.columnsPending = GetLowBits(m_iColumnCount); + + for (int i = 0; i < m_iListCount; i++) + { + if (m_Lists[i].count == 0) + continue; + + state.listsResized |= 1u << i; + + for (int j = 0; j < m_Lists[i].count; j++) + { + if (m_Lists[i].items[j].type != bhl::sb::E_ValueType::None) + state.listItemsDirty[i] |= 1ULL << j; + } + } + + for (int target = 0; target < MAX_TARGETS; target++) + state.cellsDirty[target] = GetFilledCells(target); + + // Free ids and empty variants send nothing + state.elementsPending = ~0u; + memset(state.templatesPending, 0xFF, sizeof(state.templatesPending)); +} + +void CScoreboardExt::StartFrame() +{ + if (!gmsgBhlScore) + return; + + for (int i = 0; i < m_iTeamCount; i++) + { + int index = g_pGameRules ? g_pGameRules->GetTeamIndex(m_szTeamNames[i]) : -1; + m_TeamNumbers[i] = index >= 0 && index < MAX_TEAMS ? index + 1 : 0; + } + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + pacing_t &pacing = m_Pacing[i]; + + if (!serverapi()->IsScoreboardClient(i) || gpGlobals->time < pacing.nextSendTime) + continue; + + // A budget per period, not per frame: the rate must not grow with the server fps + if (gpGlobals->time >= pacing.periodEnd) + { + pacing.periodEnd = gpGlobals->time + BUDGET_PERIOD; + pacing.bytesLeft = BUDGET; + } + + m_iBytesLeft = pacing.bytesLeft; + + if (!SendToClient(i)) + pacing.nextSendTime = pacing.periodEnd; + + pacing.bytesLeft = m_iBytesLeft; + } +} + +//---------------------------------------------------------------------------------------------------- +// IScoreboardExt methods +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::Reset() +{ + ClearState(); + + for (int i = 1; i <= gpGlobals->maxClients; i++) + StartFullSync(i, false); +} + +void CScoreboardExt::SetConfig(unsigned int hideFlags, const char *title, const char *tag) +{ + char newTitle[sizeof(m_szTitle)]; + char newTag[sizeof(m_szTag)]; + + hideFlags &= (unsigned int)bhl::sb::E_ConfigFlags::All; + CopyString(newTitle, title); + CopyString(newTag, tag); + + if (m_bHasConfig && hideFlags == m_iHideFlags && !strcmp(newTitle, m_szTitle) && !strcmp(newTag, m_szTag)) + return; + + Activate(); + + m_bHasConfig = true; + m_iHideFlags = hideFlags; + CopyString(m_szTitle, newTitle); + CopyString(m_szTag, newTag); + + for (client_state_t &state : m_Clients) + state.isConfigPending = true; +} + +bool CScoreboardExt::AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags) +{ + if (!bhl::sb::IsValidKey(key) || display < (int)bhl::sb::E_Display::Text || display > (int)bhl::sb::E_Display::Steps) + return false; + + column_t column; + CopyString(column.key, key); + CopyString(column.title, title); + column.display = display; + column.flags = flags & (unsigned int)bhl::sb::E_ColumnFlags::All; + column.width = ClampByte(width); + column.sort = ClampByte(sort); + return SetColumn(column); +} + +int CScoreboardExt::GetTeamTarget(const char *teamName) +{ + if (!teamName || !teamName[0]) + return -1; + + char name[MAX_TEAM_NAME]; + CopyString(name, teamName); + + for (int i = 0; i < m_iTeamCount; i++) + { + if (!_stricmp(m_szTeamNames[i], name)) + return TEAM_TARGET_BASE + i; + } + + if (m_iTeamCount == MAX_TEAMS) + return -1; + + CopyString(m_szTeamNames[m_iTeamCount], name); + return TEAM_TARGET_BASE + m_iTeamCount++; +} + +void CScoreboardExt::SetInt(int target, const char *key, int value) +{ + SetCell(target, key, { bhl::sb::E_ValueType::Int, value }); +} + +void CScoreboardExt::SetText(int target, const char *key, const char *text) +{ + SetCell(target, key, MakeValue(bhl::sb::E_ValueType::Text, "", text)); +} + +void CScoreboardExt::SetIcon(int target, const char *key, const char *sprite, const char *text) +{ + SetCell(target, key, MakeValue(bhl::sb::E_ValueType::Icon, sprite, text)); +} + +void CScoreboardExt::SetProgress(int target, const char *key, int cur, int max) +{ + SetCell(target, key, { bhl::sb::E_ValueType::Progress, ClampWord(cur), ClampWord(max) }); +} + +void CScoreboardExt::Clear(int target, const char *key) +{ + for (int column = 0; column < m_iColumnCount; column++) + { + if (!key || !key[0] || !strcmp(m_Columns[column].key, key)) + SetCell(target, m_Columns[column].key, value_t()); + } +} + +bool CScoreboardExt::ListResize(const char *key, int count) +{ + if (!bhl::sb::IsValidKey(key)) + return false; + + int id = FindList(key); + + if (id == -1) + { + if (m_iListCount == bhl::sb::MAX_LISTS) + return false; + + id = m_iListCount++; + CopyString(m_Lists[id].key, key); + } + + list_t &list = m_Lists[id]; + count = std::clamp(count, 0, bhl::sb::MAX_LIST_ITEMS); + + if (list.count == count) + return true; + + for (int i = count; i < list.count; i++) + list.items[i] = value_t(); + + uint64_t itemsMask = GetLowBits(count); + + // The client still has old values there if it missed the smaller total, so grown items are sent even if empty + uint64_t grownItems = count > list.count ? itemsMask & ~GetLowBits(list.count) : 0; + + list.count = count; + + for (client_state_t &state : m_Clients) + { + state.listsResized |= 1u << id; + state.listItemsDirty[id] = (state.listItemsDirty[id] & itemsMask) | grownItems; + } + + return true; +} + +void CScoreboardExt::ListSetInt(const char *key, int index, int value) +{ + SetListItem(key, index, { bhl::sb::E_ValueType::Int, value }); +} + +void CScoreboardExt::ListSetText(const char *key, int index, const char *text) +{ + SetListItem(key, index, MakeValue(bhl::sb::E_ValueType::Text, "", text)); +} + +void CScoreboardExt::ListSetIcon(const char *key, int index, const char *sprite, const char *text) +{ + SetListItem(key, index, MakeValue(bhl::sb::E_ValueType::Icon, sprite, text)); +} + +void CScoreboardExt::SetClock(int target, const char *key, int ms, unsigned int flags) +{ + flags &= (unsigned int)bhl::sb::E_ClockFlags::All; + + // A running clock runs from this call, so a call with the same values restarts it + SetCell(target, key, { bhl::sb::E_ValueType::Clock, ms, 0, flags, (flags & (unsigned int)bhl::sb::E_ClockFlags::Run) ? gpGlobals->time : 0.0f }); +} + +bool CScoreboardExt::AddBadge(const char *key, const char *host) +{ + if (!bhl::sb::IsValidKey(key) || !bhl::sb::IsValidKey(host)) + return false; + + column_t column; + CopyString(column.key, key); + CopyString(column.host, host); + column.display = (int)bhl::sb::E_Display::Badge; + return SetColumn(column); +} + +bool CScoreboardExt::HudAdd(const char *key, int kind, float x, float y, int font, int align, unsigned int flags) +{ + if (!bhl::sb::IsValidKey(key) || !bhl::sb::IsKnownKind(kind)) + return false; + + int id = FindElement(key); + bool isNew = id == -1; + + if (isNew) + { + id = FindFreeElementId(); + + if (id == -1) + return false; + } + + Activate(); + + element_t &element = m_Elements[id]; + element_def_t def = element.def; + + if (!isNew && def.kind != kind) + { + DropTexts(id); + def.select[0] = '\0'; + def.value[0] = '\0'; + def.list[0] = '\0'; + def.paramsSet = 0; + def.slotsSet = 0; + } + + def.kind = kind; + def.flags = flags & (unsigned int)bhl::sb::E_ElementFlags::All & ~(unsigned int)bhl::sb::E_ElementFlags::HudColor; + def.x = bhl::sb::PositionToWire(x); + def.y = bhl::sb::PositionToWire(y); + def.font = font >= 0 && font < bhl::sb::FONT_COUNT ? font : (int)bhl::sb::E_Font::Text; + def.align = align & bhl::sb::ALIGN_MASK; + + if (isNew) + { + CopyString(element.key, key); + m_iVisible |= 1u << id; + MarkChildren(key); + } + + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudSetPlace(const char *key, int place, const char *parent, int gap) +{ + int id = FindElement(key); + + if (id == -1 || place < (int)bhl::sb::E_Place::Screen || place > (int)bhl::sb::E_Place::ParentRight || (parent && parent[0] && !bhl::sb::IsValidKey(parent))) + return false; + + element_def_t def = m_Elements[id].def; + def.place = place; + CopyString(def.parent, bhl::sb::IsParentPlace((bhl::sb::E_Place)place) ? parent : ""); + def.gap = ClampByte(gap); + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudSetColor(const char *key, int r, int g, int b, int a) +{ + int id = FindElement(key); + + if (id == -1) + return false; + + element_def_t def = m_Elements[id].def; + def.isHudColor = r < 0; + def.color[0] = def.isHudColor ? 0 : ClampByte(r); + def.color[1] = def.isHudColor ? 0 : ClampByte(g); + def.color[2] = def.isHudColor ? 0 : ClampByte(b); + def.color[3] = ClampByte(a); + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudBind(const char *key, const char *value, const char *list, const char *select) +{ + int id = FindElement(key); + + if (id == -1 + || (value && value[0] && !bhl::sb::IsValidRef(value)) + || (list && list[0] && !bhl::sb::IsValidKey(list)) + || (select && select[0] && !bhl::sb::IsValidRef(select))) + return false; + + element_def_t def = m_Elements[id].def; + CopyString(def.value, value); + CopyString(def.list, list); + CopyString(def.select, select); + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudSetParam(const char *key, int param, int value) +{ + int id = FindElement(key); + + if (id == -1) + return false; + + element_def_t def = m_Elements[id].def; + const bhl::sb::ParamInfo *info = bhl::sb::FindParamInfo((bhl::sb::E_ElementKind)def.kind, param); + + if (!info) + return false; + + def.paramsSet |= 1ULL << param; + def.params[param] = std::clamp(value, info->iMin, info->iMax); + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudSetText(int player, const char *key, int variant, const char *text) +{ + int id = FindElement(key); + + if (!text) + text = ""; + + if (id == -1 || variant < 0 || variant >= bhl::sb::MAX_VARIANTS || !IsValidHudPlayer(player) || strlen(text) > bhl::sb::MAX_TEMPLATE_LEN) + return false; + + element_t &element = m_Elements[id]; + uint8_t bit = 1 << variant; + + if (player == 0) + { + // The default wins over every player's own text, even when it doesn't change (5.4) + for (int i = 1; i <= MAX_PLAYERS; i++) + { + if (GetText(i, id, variant) != text) + m_Clients[i].templatesPending[id] |= bit; + + m_PlayerHud[i].texts[id][variant].reset(); + } + + element.texts[variant] = text; + return true; + } + + std::optional &own = m_PlayerHud[player].texts[id][variant]; + + if (GetText(player, id, variant) != text) + m_Clients[player].templatesPending[id] |= bit; + + if (element.texts[variant] == text) + own.reset(); + else + own = text; + + return true; +} + +bool CScoreboardExt::HudShow(int player, const char *key, bool show) +{ + int id = FindElement(key); + + if (id == -1 || !IsValidHudPlayer(player)) + return false; + + unsigned int bit = 1u << id; + + if (player == 0) + { + m_iVisible = show ? m_iVisible | bit : m_iVisible & ~bit; + + for (player_hud_t &hud : m_PlayerHud) + hud.visibleToggled &= ~bit; + + return true; + } + + if (show == ((m_iVisible & bit) != 0)) + m_PlayerHud[player].visibleToggled &= ~bit; + else + m_PlayerHud[player].visibleToggled |= bit; + + return true; +} + +void CScoreboardExt::HudRemove(const char *key) +{ + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + if (m_Elements[id].key[0] && (!key || !key[0] || !strcmp(m_Elements[id].key, key))) + RemoveElement(id); + } +} + +void CScoreboardExt::HudHideStd(unsigned int parts, bool hide) +{ + parts &= (unsigned int)bhl::sb::E_HudStd::All; + + unsigned int hidden = hide ? m_iHiddenStd | parts : m_iHiddenStd & ~parts; + + if (hidden == m_iHiddenStd) + return; + + Activate(); + m_iHiddenStd = hidden; +} + +bool CScoreboardExt::HudSetSlotColor(const char *key, int slot, int r, int g, int b, int a) +{ + int id = FindElement(key); + + if (id == -1 || slot < 0 || slot >= bhl::sb::MAX_COLOR_SLOTS) + return false; + + element_def_t def = m_Elements[id].def; + + if (r < 0) + { + def.slotsSet &= ~(1u << slot); + } + else + { + def.slotsSet |= 1u << slot; + def.slotColors[slot][0] = ClampByte(r); + def.slotColors[slot][1] = ClampByte(g); + def.slotColors[slot][2] = ClampByte(b); + def.slotColors[slot][3] = ClampByte(a); + } + + return SetElementDef(id, def); +} + +bool CScoreboardExt::HudEvent(int player, const char *key, int variant, int lifeMs, const int *args, int argCount, const char *iconSprite, const char *iconText) +{ + int id = FindElement(key); + + if (id == -1 || m_Elements[id].def.kind != (int)bhl::sb::E_ElementKind::Feed || variant < 0 || variant >= bhl::sb::MAX_VARIANTS + || argCount < 0 || argCount > bhl::sb::MAX_EVENT_INTS || (argCount > 0 && !args) || !IsValidHudPlayer(player)) + return false; + + event_t event; + CopyString(event.key, key); + event.variant = variant; + event.lifeMs = ClampWord(lifeMs); + event.time = gpGlobals->time; + + for (int i = 0; i < argCount; i++) + event.args[i] = { bhl::sb::E_ValueType::Int, args[i] }; + + event.argCount = argCount; + + if ((iconSprite && iconSprite[0]) || (iconText && iconText[0])) + event.args[event.argCount++] = MakeValue(bhl::sb::E_ValueType::Icon, iconSprite, iconText); + + if (GetEventSize(event) > bhl::sb::MAX_MSG_SIZE) + return false; + + // Events are not state: clients that are not ready now never get this one + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if ((player != 0 && player != i) || !serverapi()->IsScoreboardClient(i) || !IsEnumFlagSet(serverapi()->GetClientCaps(i), bhl::E_ClientCaps::HudV1)) + continue; + + if ((int)m_Events[i].size() == MAX_QUEUED_EVENTS) + m_Events[i].pop_front(); + + m_Events[i].push_back(event); + } + + return true; +} + +//---------------------------------------------------------------------------------------------------- +// State +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::ClearState() +{ + m_bActive = false; + m_bHasConfig = false; + m_iColumnCount = 0; + std::fill(std::begin(m_Lists), std::end(m_Lists), list_t()); + m_iListCount = 0; + + for (auto &cells : m_Cells) + std::fill(std::begin(cells), std::end(cells), value_t()); + + std::fill(std::begin(m_Elements), std::end(m_Elements), element_t()); + m_iVisible = 0; + m_iHiddenStd = 0; + std::fill(std::begin(m_PlayerHud), std::end(m_PlayerHud), player_hud_t()); + + for (std::deque &queue : m_Events) + queue.clear(); +} + +void CScoreboardExt::Activate() +{ + if (m_bActive) + return; + + m_bActive = true; + + // Drops what was marked while inactive; clients still in the wait after InitHUD keep it + for (int i = 1; i <= gpGlobals->maxClients; i++) + StartFullSync(i, false); + + serverapi()->QueryUnknownClientCaps(); +} + +bool CScoreboardExt::IsValidHudPlayer(int player) +{ + return player == 0 || (player >= 1 && player <= gpGlobals->maxClients && serverapi()->IsClientConnected(player)); +} + +int CScoreboardExt::FindColumn(const char *key) +{ + return FindKey(m_Columns, m_iColumnCount, key); +} + +int CScoreboardExt::FindList(const char *key) +{ + return FindKey(m_Lists, m_iListCount, key); +} + +int CScoreboardExt::FindElement(const char *key) +{ + return FindKey(m_Elements, bhl::sb::MAX_ELEMENTS, key); +} + +int CScoreboardExt::FindFreeElementId() +{ + // A new element under an id the client still has something of (the old element, its visibility bit, + // a child placed at it) would show that old state until everything of the new one arrives. When every + // free id is held, the lowest is reused: SendElements still drops the old templates with a removal. + unsigned int held = 0; + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (!serverapi()->IsScoreboardClient(i)) + continue; + + const client_state_t &state = m_Clients[i]; + held |= state.elementsSent | state.sentVisible; + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + if ((state.elementsSent & (1u << id)) && state.sentParents[id] != bhl::sb::NO_ID) + held |= 1u << state.sentParents[id]; + } + } + + int fallback = -1; + + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + if (m_Elements[id].key[0]) + continue; + + if (!(held & (1u << id))) + return id; + + if (fallback == -1) + fallback = id; + } + + return fallback; +} + +bool CScoreboardExt::SetColumn(const column_t &definition) +{ + int id = FindColumn(definition.key); + bool isNew = id == -1; + + if (isNew) + { + if (m_iColumnCount == bhl::sb::MAX_COLUMNS) + return false; + + id = m_iColumnCount++; + } + else if (IsEqual(m_Columns[id], definition)) + { + return true; + } + + m_Columns[id] = definition; + + if (definition.display == (int)bhl::sb::E_Display::Builtin) + { + for (int target = 0; target < MAX_TARGETS; target++) + StoreCell(target, id, value_t()); + } + + // Badges that follow a new key were sent without their host + unsigned int columns = 1u << id; + + if (isNew) + { + for (int i = 0; i < m_iColumnCount; i++) + { + if (!strcmp(m_Columns[i].host, definition.key)) + columns |= 1u << i; + } + } + + for (client_state_t &state : m_Clients) + state.columnsPending |= columns; + + return true; +} + +void CScoreboardExt::SetCell(int target, const char *key, const value_t &value) +{ + int column = FindColumn(key); + + if (column == -1 || m_Columns[column].display == (int)bhl::sb::E_Display::Builtin) + return; + + if (target >= TEAM_TARGET_BASE && target < TEAM_TARGET_BASE + m_iTeamCount) + StoreCell(FIRST_TEAM + target - TEAM_TARGET_BASE, column, value); + else if (target == bhl::sb::TARGET_GLOBAL || (target >= 1 && target <= gpGlobals->maxClients && serverapi()->IsClientConnected(target))) + StoreCell(target, column, value); +} + +void CScoreboardExt::StoreCell(int target, int column, const value_t &value) +{ + value_t &cell = m_Cells[target][column]; + + if (IsEqual(cell, value)) + return; + + cell = value; + + for (client_state_t &state : m_Clients) + state.cellsDirty[target] |= 1u << column; +} + +void CScoreboardExt::SetListItem(const char *key, int index, const value_t &value) +{ + int id = FindList(key); + + if (id == -1 || index < 0 || index >= m_Lists[id].count) + return; + + value_t &item = m_Lists[id].items[index]; + + if (IsEqual(item, value)) + return; + + item = value; + + for (client_state_t &state : m_Clients) + state.listItemsDirty[id] |= 1ULL << index; +} + +unsigned int CScoreboardExt::GetFilledCells(int target) +{ + unsigned int cells = 0; + + for (int column = 0; column < m_iColumnCount; column++) + { + if (m_Cells[target][column].type != bhl::sb::E_ValueType::None) + cells |= 1u << column; + } + + return cells; +} + +bool CScoreboardExt::SetElementDef(int id, const element_def_t &def) +{ + if (GetElementSize(def) > bhl::sb::MAX_MSG_SIZE) + return false; + + if (IsEqual(m_Elements[id].def, def)) + return true; + + m_Elements[id].def = def; + MarkElement(id); + return true; +} + +void CScoreboardExt::RemoveElement(int id) +{ + unsigned int bit = 1u << id; + + MarkChildren(m_Elements[id].key); + DropTexts(id); + m_Elements[id] = element_t(); + m_iVisible &= ~bit; + + for (player_hud_t &hud : m_PlayerHud) + hud.visibleToggled &= ~bit; + + MarkElement(id); +} + +void CScoreboardExt::DropTexts(int id) +{ + for (std::string &text : m_Elements[id].texts) + text.clear(); + + for (player_hud_t &hud : m_PlayerHud) + { + for (std::optional &text : hud.texts[id]) + text.reset(); + } + + // A new definition keeps the client's templates: they are dropped by a removal sent before it + for (client_state_t &state : m_Clients) + state.textsDropped |= 1u << id; +} + +const std::string &CScoreboardExt::GetText(int player, int id, int variant) +{ + const std::optional &own = m_PlayerHud[player].texts[id][variant]; + return own ? *own : m_Elements[id].texts[variant]; +} + +void CScoreboardExt::MarkElement(int id) +{ + for (client_state_t &state : m_Clients) + state.elementsPending |= 1u << id; +} + +void CScoreboardExt::MarkChildren(const char *parent) +{ + for (int i = 0; i < bhl::sb::MAX_ELEMENTS; i++) + { + if (m_Elements[i].key[0] && !strcmp(m_Elements[i].def.parent, parent)) + MarkElement(i); + } +} + +//---------------------------------------------------------------------------------------------------- +// Sending +//---------------------------------------------------------------------------------------------------- +bool CScoreboardExt::SendToClient(int idx) +{ + client_state_t &state = m_Clients[idx]; + edict_t *pEdict = INDEXENT(idx); + + if (state.isResetPending) + { + if (!BeginMessage(pEdict, 1, bhl::sb::E_Op::Reset)) + return false; + + MESSAGE_END(); + state.isResetPending = false; + } + + if (!m_bActive) + return true; + + // Without mp_teamlist team indexes change when teams appear and disappear + for (int i = 0; i < m_iTeamCount; i++) + { + if (state.teamNumbers[i] == m_TeamNumbers[i]) + continue; + + if (state.teamNumbers[i] != 0) + state.targetsCleared.set(bhl::sb::TARGET_TEAM_BASE + state.teamNumbers[i]); + + state.teamNumbers[i] = m_TeamNumbers[i]; + state.cellsDirty[FIRST_TEAM + i] = GetFilledCells(FIRST_TEAM + i); + } + + // Elements before their templates, templates before HudState shows them, events last + return SendHeader(pEdict, state) + && SendLists(pEdict, state) + && SendValues(pEdict, state) + && SendElements(pEdict, state) + && SendTemplates(pEdict, idx, state) + && SendHudState(pEdict, idx, state) + && SendEvents(pEdict, idx, state); +} + +bool CScoreboardExt::BeginMessage(edict_t *pEdict, int size, bhl::sb::E_Op op) +{ + if (size > m_iBytesLeft) + return false; + + m_iBytesLeft -= size; + MESSAGE_BEGIN(MSG_ONE, gmsgBhlScore, NULL, pEdict); + WRITE_BYTE((int)op); + return true; +} + +bool CScoreboardExt::SendHeader(edict_t *pEdict, client_state_t &state) +{ + if (state.isConfigPending && m_bHasConfig) + { + int size = 3 + (int)strlen(m_szTitle) + 1 + (int)strlen(m_szTag) + 1; + + if (!BeginMessage(pEdict, size, bhl::sb::E_Op::Config)) + return false; + + WRITE_SHORT(m_iHideFlags); + WRITE_STRING(m_szTitle); + WRITE_STRING(m_szTag); + MESSAGE_END(); + } + + state.isConfigPending = false; + + for (int i = 0; i < m_iColumnCount; i++) + { + if (!(state.columnsPending & (1u << i))) + continue; + + const column_t &column = m_Columns[i]; + int size = 7 + (int)strlen(column.key) + 1 + (int)strlen(column.title) + 1 + 1; + int host = column.display == (int)bhl::sb::E_Display::Badge ? FindColumn(column.host) : -1; + + if (!BeginMessage(pEdict, size, bhl::sb::E_Op::Column)) + return false; + + // AddBadge leaves flags, width and sort of a Badge at 0 + WRITE_BYTE(i); + WRITE_BYTE(column.display); + WRITE_SHORT(column.flags); + WRITE_BYTE(column.width); + WRITE_BYTE(column.sort); + WRITE_STRING(column.key); + WRITE_STRING(column.title); + WRITE_BYTE(host == -1 ? bhl::sb::NO_ID : host); + MESSAGE_END(); + state.columnsPending &= ~(1u << i); + } + + return true; +} + +bool CScoreboardExt::SendLists(edict_t *pEdict, client_state_t &state) +{ + for (int id = 0; id < m_iListCount; id++) + { + const list_t &list = m_Lists[id]; + uint64_t &dirty = state.listItemsDirty[id]; + unsigned int resized = 1u << id; + int headerSize = 4 + (int)strlen(list.key) + 1; + + while (dirty || (state.listsResized & resized)) + { + int start = 0; + int end = 0; + int size = headerSize; + + if (dirty) + { + while (!(dirty & (1ULL << start))) + start++; + + // Up to the last dirty item: clean items between dirty ones are sent again to keep the run contiguous + end = start; + + while ((dirty & ~GetLowBits(end)) && size + GetValueSize(list.items[end]) <= bhl::sb::MAX_MSG_SIZE) + size += GetValueSize(list.items[end++]); + } + + if (!BeginMessage(pEdict, size, bhl::sb::E_Op::List)) + return false; + + WRITE_BYTE(id); + WRITE_BYTE(list.count); + WRITE_BYTE(start); + WRITE_STRING(list.key); + + for (int i = start; i < end; i++) + { + WriteValue(list.items[i]); + dirty &= ~(1ULL << i); + } + + MESSAGE_END(); + state.listsResized &= ~resized; + } + } + + return true; +} + +bool CScoreboardExt::SendValues(edict_t *pEdict, client_state_t &state) +{ + // Clears go first: a team number may already be reused by another team + for (int wire = 0; wire < (int)state.targetsCleared.size(); wire++) + { + if (!state.targetsCleared[wire]) + continue; + + if (!BeginMessage(pEdict, 5, bhl::sb::E_Op::Values)) + return false; + + WRITE_BYTE(wire); + WRITE_BYTE(bhl::sb::ALL_COLUMNS); + WriteValue(value_t()); + MESSAGE_END(); + state.targetsCleared.reset(wire); + } + + for (int target = 0; target < MAX_TARGETS; target++) + { + unsigned int &dirty = state.cellsDirty[target]; + int wire = target; + + if (target >= FIRST_TEAM) + { + int number = state.teamNumbers[target - FIRST_TEAM]; + + // Its cells are marked again when the team gets a number + if (number == 0) + continue; + + wire = bhl::sb::TARGET_TEAM_BASE + number; + } + + // One target per message with the cells that fit; the first one always does + while (dirty) + { + unsigned int cells = 0; + int size = 2; + + for (int column = 0; column < bhl::sb::MAX_COLUMNS; column++) + { + if (!(dirty & (1u << column))) + continue; + + int cellSize = 1 + GetValueSize(m_Cells[target][column]); + + if (size + cellSize > bhl::sb::MAX_MSG_SIZE) + break; + + cells |= 1u << column; + size += cellSize; + } + + if (!BeginMessage(pEdict, size, bhl::sb::E_Op::Values)) + return false; + + WRITE_BYTE(wire); + + for (int column = 0; column < bhl::sb::MAX_COLUMNS; column++) + { + if (cells & (1u << column)) + { + WRITE_BYTE(column); + WriteValue(m_Cells[target][column]); + } + } + + MESSAGE_END(); + dirty &= ~cells; + } + } + + return true; +} + +bool CScoreboardExt::SendElements(edict_t *pEdict, client_state_t &state) +{ + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + unsigned int bit = 1u << id; + + if (!(state.elementsPending & bit)) + continue; + + if (m_Elements[id].key[0]) + { + // Both or neither (a removal is 3 bytes): a split would leave the new element with the old templates + if ((state.textsDropped & bit) && (state.elementsSent & bit)) + { + if (3 + GetElementSize(m_Elements[id].def) > m_iBytesLeft || !SendElementRemoval(pEdict, id)) + return false; + + state.templatesSent[id] = 0; + } + + if (!SendElement(pEdict, state, id)) + return false; + + state.elementsSent |= bit; + } + else if (state.elementsSent & bit) + { + if (!SendElementRemoval(pEdict, id)) + return false; + + state.elementsSent &= ~bit; + state.templatesSent[id] = 0; + } + + state.textsDropped &= ~bit; + state.elementsPending &= ~bit; + } + + return true; +} + +int CScoreboardExt::GetElementSize(const element_def_t &def) +{ + // 18 bytes from the opcode to font: an Element that ends before font is ignored + return 18 + (int)strlen(def.select) + 1 + (int)strlen(def.value) + 1 + (int)strlen(def.list) + 1 + + 1 + 3 * (int)std::bitset(def.paramsSet).count() + + 1 + 5 * (int)std::bitset(def.slotsSet).count(); +} + +bool CScoreboardExt::SendElement(edict_t *pEdict, client_state_t &state, int id) +{ + const element_def_t &def = m_Elements[id].def; + int parent = FindElement(def.parent); + + if (!BeginMessage(pEdict, GetElementSize(def), bhl::sb::E_Op::Element)) + return false; + + state.sentParents[id] = parent == -1 ? bhl::sb::NO_ID : parent; + + WRITE_BYTE(id); + WRITE_BYTE(def.kind); + WRITE_SHORT(def.isHudColor ? def.flags | (unsigned int)bhl::sb::E_ElementFlags::HudColor : def.flags); + WRITE_SHORT(def.x); + WRITE_SHORT(def.y); + WRITE_BYTE(def.align); + WRITE_BYTE(def.place); + WRITE_BYTE(state.sentParents[id]); + WRITE_BYTE(def.gap); + + for (int component : def.color) + WRITE_BYTE(component); + + WRITE_BYTE(def.font); + WRITE_STRING(def.select); + WRITE_STRING(def.value); + WRITE_STRING(def.list); + WRITE_BYTE((int)std::bitset(def.paramsSet).count()); + + for (int i = 0; i <= bhl::sb::MAX_PARAM_ID; i++) + { + if (!(def.paramsSet & (1ULL << i))) + continue; + + WRITE_BYTE(i); + WRITE_SHORT(def.params[i]); + } + + WRITE_BYTE((int)std::bitset(def.slotsSet).count()); + + for (int i = 0; i < bhl::sb::MAX_COLOR_SLOTS; i++) + { + if (!(def.slotsSet & (1u << i))) + continue; + + WRITE_BYTE(i); + + for (int component : def.slotColors[i]) + WRITE_BYTE(component); + } + + MESSAGE_END(); + return true; +} + +bool CScoreboardExt::SendElementRemoval(edict_t *pEdict, int id) +{ + if (!BeginMessage(pEdict, 3, bhl::sb::E_Op::Element)) + return false; + + WRITE_BYTE(id); + WRITE_BYTE((int)bhl::sb::E_ElementKind::None); + MESSAGE_END(); + return true; +} + +bool CScoreboardExt::SendTemplates(edict_t *pEdict, int idx, client_state_t &state) +{ + for (int id = 0; id < bhl::sb::MAX_ELEMENTS; id++) + { + for (int variant = 0; variant < bhl::sb::MAX_VARIANTS; variant++) + { + uint8_t bit = 1 << variant; + + if (!(state.templatesPending[id] & bit)) + continue; + + const std::string &text = GetText(idx, id, variant); + + // "" removes the variant, so it only goes to a client that has one + if (!text.empty() || (state.templatesSent[id] & bit)) + { + if (!BeginMessage(pEdict, 3 + (int)text.size() + 1, bhl::sb::E_Op::Template)) + return false; + + WRITE_BYTE(id); + WRITE_BYTE(variant); + WRITE_STRING(text.c_str()); + MESSAGE_END(); + + if (text.empty()) + state.templatesSent[id] &= ~bit; + else + state.templatesSent[id] |= bit; + } + + state.templatesPending[id] &= ~bit; + } + } + + return true; +} + +bool CScoreboardExt::SendHudState(edict_t *pEdict, int idx, client_state_t &state) +{ + unsigned int visible = m_iVisible ^ m_PlayerHud[idx].visibleToggled; + + if (visible == state.sentVisible && m_iHiddenStd == state.sentHidden) + return true; + + if (!BeginMessage(pEdict, 7, bhl::sb::E_Op::HudState)) + return false; + + WRITE_LONG((int)visible); + WRITE_SHORT(m_iHiddenStd); + MESSAGE_END(); + state.sentVisible = visible; + state.sentHidden = m_iHiddenStd; + return true; +} + +bool CScoreboardExt::SendEvents(edict_t *pEdict, int idx, client_state_t &state) +{ + std::deque &queue = m_Events[idx]; + + while (!queue.empty()) + { + const event_t &event = queue.front(); + int id = FindElement(event.key); + constexpr int param = (int)bhl::sb::E_Param::LifeMs; + bool isParamSet = id != -1 && (m_Elements[id].def.paramsSet & (1ULL << param)); + int life = event.lifeMs ? event.lifeMs : (isParamSet ? m_Elements[id].def.params[param] : bhl::sb::FindParamInfo(bhl::sb::E_ElementKind::Feed, param)->iDefault); + + // Dropped unsent once its line would be gone + if (gpGlobals->time <= event.time + life * 0.001f) + { + // Waits for the element, keeping the order + if (id == -1 || m_Elements[id].def.kind != (int)bhl::sb::E_ElementKind::Feed || !(state.elementsSent & (1u << id))) + return true; + + if (!BeginMessage(pEdict, GetEventSize(event), bhl::sb::E_Op::Event)) + return false; + + WRITE_BYTE(id); + WRITE_BYTE(event.variant); + WRITE_SHORT(event.lifeMs); + WRITE_BYTE(event.argCount); + + for (int i = 0; i < event.argCount; i++) + WriteValue(event.args[i]); + + MESSAGE_END(); + } + + queue.pop_front(); + } + + return true; +} + +CScoreboardExt::value_t CScoreboardExt::MakeValue(bhl::sb::E_ValueType type, const char *sprite, const char *text) +{ + value_t value; + value.type = type; + CopyString(value.sprite, sprite); + CopyString(value.text, text); + return value; +} + +bool CScoreboardExt::IsEqual(const value_t &a, const value_t &b) +{ + return a.type == b.type && a.value == b.value && a.max == b.max && a.flags == b.flags && a.time == b.time && !strcmp(a.text, b.text) && !strcmp(a.sprite, b.sprite); +} + +bool CScoreboardExt::IsEqual(const column_t &a, const column_t &b) +{ + return !strcmp(a.key, b.key) && !strcmp(a.title, b.title) && a.display == b.display && a.flags == b.flags + && a.width == b.width && a.sort == b.sort && !strcmp(a.host, b.host); +} + +bool CScoreboardExt::IsEqual(const element_def_t &a, const element_def_t &b) +{ + // Unset params and slot colors are compared too: def is always a copy of the stored one + return a.kind == b.kind && a.flags == b.flags && a.x == b.x && a.y == b.y && a.align == b.align + && a.place == b.place && !strcmp(a.parent, b.parent) && a.gap == b.gap && a.isHudColor == b.isHudColor + && a.font == b.font && !strcmp(a.select, b.select) && !strcmp(a.value, b.value) && !strcmp(a.list, b.list) + && a.paramsSet == b.paramsSet && a.slotsSet == b.slotsSet && !memcmp(a.color, b.color, sizeof(a.color)) + && !memcmp(a.params, b.params, sizeof(a.params)) && !memcmp(a.slotColors, b.slotColors, sizeof(a.slotColors)); +} + +int CScoreboardExt::GetEventSize(const event_t &event) +{ + int size = 6; // Opcode, id, variant, life and count + + for (int i = 0; i < event.argCount; i++) + size += GetValueSize(event.args[i]); + + return size; +} + +int CScoreboardExt::GetValueSize(const value_t &value) +{ + int len = 0; + + switch (value.type) + { + case bhl::sb::E_ValueType::Int: + if (value.value >= -128 && value.value <= 127) + len = 1; + else if (value.value >= -32768 && value.value <= 32767) + len = 2; + else + len = 4; + break; + case bhl::sb::E_ValueType::Text: + len = (int)strlen(value.text) + 1; + break; + case bhl::sb::E_ValueType::Icon: + len = (int)strlen(value.sprite) + 1 + (int)strlen(value.text) + 1; + break; + case bhl::sb::E_ValueType::Progress: + len = value.value >= 0 && value.value <= 255 && value.max >= 0 && value.max <= 255 ? 2 : 4; + break; + case bhl::sb::E_ValueType::Clock: + len = bhl::sb::CLOCK_VALUE_LEN; + break; + } + + return 2 + len; +} + +void CScoreboardExt::WriteValue(const value_t &value) +{ + int len = GetValueSize(value) - 2; + + WRITE_BYTE((int)value.type); + WRITE_BYTE(len); + + switch (value.type) + { + case bhl::sb::E_ValueType::Int: + if (len == 1) + WRITE_CHAR(value.value); + else if (len == 2) + WRITE_SHORT(value.value); + else + WRITE_LONG(value.value); + break; + case bhl::sb::E_ValueType::Text: + WRITE_STRING(value.text); + break; + case bhl::sb::E_ValueType::Icon: + WRITE_STRING(value.sprite); + WRITE_STRING(value.text); + break; + case bhl::sb::E_ValueType::Progress: + if (len == 2) + { + WRITE_BYTE(value.value); + WRITE_BYTE(value.max); + } + else + { + WRITE_SHORT(value.value); + WRITE_SHORT(value.max); + } + break; + case bhl::sb::E_ValueType::Clock: + { + // The client runs a clock from its arrival, so a running one goes with the time it has run since it was set + int64_t ms = value.value; + + if (value.flags & (unsigned int)bhl::sb::E_ClockFlags::Run) + { + int64_t elapsed = (int64_t)(std::max(gpGlobals->time - value.time, 0.0f) * 1000.0 + 0.5); + ms = (value.flags & (unsigned int)bhl::sb::E_ClockFlags::Down) ? std::max(ms - elapsed, 0) : std::min(ms + elapsed, INT_MAX); + } + + WRITE_LONG((int)ms); + WRITE_BYTE(value.flags); + break; + } + } +} diff --git a/src/game/server/CScoreboardExt.h b/src/game/server/CScoreboardExt.h new file mode 100644 index 00000000..b15ef4eb --- /dev/null +++ b/src/game/server/CScoreboardExt.h @@ -0,0 +1,256 @@ +#ifndef CSCOREBOARDEXT_H +#define CSCOREBOARDEXT_H + +#include +#include +#include +#include +#include +#include +#include +#include "eiface.h" +#include "cdll_dll.h" + +/** + * Implementation of IScoreboardExt: keeps the scoreboard and HUD state and sends every client + * its own view of it in "BhlScore" messages. + * @see docs/scoreboard-protocol.md + */ +class CScoreboardExt : public bhl::IScoreboardExt +{ +public: + //! Whether a Config, an element or a hidden standard HUD part was set since the last reset (5.1) + bool IsActive() { return m_bActive; } + + //! Clears everything without sending anything. Called on map change. + void ClearAll(); + + //! Clears cells, per-player texts and visibility, and the sync state of a player slot. Called when the slot is taken or freed. + void ClearPlayer(int idx); + + /** + * Schedules Reset for the client, and everything else if the extension is active. + * @param delay Send nothing for FULL_SYNC_DELAY (InitHUD has just sent a lot); otherwise a running wait is kept + */ + void StartFullSync(int idx, bool delay); + + //! Sends pending data to the clients + void StartFrame(); + + //---------------------------------------------------------------------------------------------------- + // IScoreboardExt methods + //---------------------------------------------------------------------------------------------------- + virtual void Reset(); + virtual void SetConfig(unsigned int hideFlags, const char *title, const char *tag); + virtual bool AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags); + virtual int GetTeamTarget(const char *teamName); + virtual void SetInt(int target, const char *key, int value); + virtual void SetText(int target, const char *key, const char *text); + virtual void SetIcon(int target, const char *key, const char *sprite, const char *text); + virtual void SetProgress(int target, const char *key, int cur, int max); + virtual void Clear(int target, const char *key); + virtual bool ListResize(const char *key, int count); + virtual void ListSetInt(const char *key, int index, int value); + virtual void ListSetText(const char *key, int index, const char *text); + virtual void ListSetIcon(const char *key, int index, const char *sprite, const char *text); + virtual void SetClock(int target, const char *key, int ms, unsigned int flags); + virtual bool AddBadge(const char *key, const char *host); + virtual bool HudAdd(const char *key, int kind, float x, float y, int font, int align, unsigned int flags); + virtual bool HudSetPlace(const char *key, int place, const char *parent, int gap); + virtual bool HudSetColor(const char *key, int r, int g, int b, int a); + virtual bool HudBind(const char *key, const char *value, const char *list, const char *select); + virtual bool HudSetParam(const char *key, int param, int value); + virtual bool HudSetText(int player, const char *key, int variant, const char *text); + virtual bool HudShow(int player, const char *key, bool show); + virtual void HudRemove(const char *key); + virtual void HudHideStd(unsigned int parts, bool hide); + virtual bool HudSetSlotColor(const char *key, int slot, int r, int g, int b, int a); + virtual bool HudEvent(int player, const char *key, int variant, int lifeMs, const int *args, int argCount, const char *iconSprite, const char *iconText); + +private: + static constexpr int TEAM_TARGET_BASE = 0x100; //!< GetTeamTarget returns this plus the team slot + static constexpr int FIRST_TEAM = MAX_PLAYERS + 1; //!< Index of the first team in m_Cells + static constexpr int MAX_TARGETS = FIRST_TEAM + MAX_TEAMS; + static constexpr int BUDGET = 512; //!< Bytes per client per BUDGET_PERIOD + static constexpr float BUDGET_PERIOD = 0.1f; //!< Seconds; about 5 KB/s per client, which the reliable channel drains + static constexpr float FULL_SYNC_DELAY = 0.5f; //!< Seconds after InitHUD before the full sync starts + static constexpr int MAX_QUEUED_EVENTS = 8; //!< Events per client; the oldest is dropped + + struct value_t + { + bhl::sb::E_ValueType type = bhl::sb::E_ValueType::None; + int value = 0; //!< Int value, Progress cur or Clock ms + int max = 0; //!< Progress max + unsigned int flags = 0; //!< Clock flags + float time = 0; //!< Server time when a running Clock was set + char text[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Text value or Icon text + char sprite[bhl::sb::MAX_TEXT_LEN + 1] = {}; + }; + + struct column_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; + char title[bhl::sb::MAX_COLUMN_TITLE_LEN + 1] = {}; + int display = 0; + unsigned int flags = 0; + int width = 0; + int sort = 0; + char host[bhl::sb::MAX_KEY_LEN + 1] = {}; //!< Badge: key of the column it follows, resolved when sent + }; + + struct list_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; + int count = 0; + value_t items[bhl::sb::MAX_LIST_ITEMS]; + }; + + //! Fields of the Element message, with the parent kept as a key + struct element_def_t + { + int kind = (int)bhl::sb::E_ElementKind::None; + unsigned int flags = 0; //!< E_ElementFlags without HudColor + int x = 0; //!< Wire position + int y = 0; + int align = 0; + int place = (int)bhl::sb::E_Place::Screen; + char parent[bhl::sb::MAX_KEY_LEN + 1] = {}; //!< Only set for the parent places + int gap = 0; + bool isHudColor = true; + int color[4] = { 0, 0, 0, 255 }; //!< r, g, b, a; rgb is 0 with isHudColor + int font = (int)bhl::sb::E_Font::Text; + char select[bhl::sb::MAX_REF_LEN + 1] = {}; + char value[bhl::sb::MAX_REF_LEN + 1] = {}; + char list[bhl::sb::MAX_KEY_LEN + 1] = {}; + uint64_t paramsSet = 0; //!< Bit per param id: set by HudSetParam, sent + int params[bhl::sb::MAX_PARAM_ID + 1] = {}; + unsigned int slotsSet = 0; //!< Bit per color slot: set by HudSetSlotColor, sent + int slotColors[bhl::sb::MAX_COLOR_SLOTS][4] = {}; + }; + + struct element_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; //!< Empty if the id is free + element_def_t def; + std::string texts[bhl::sb::MAX_VARIANTS]; //!< Default templates, "" if the variant has none + }; + + //! Per-player texts and visibility (5.4). Kept apart from client_state_t, which a full sync resets. + struct player_hud_t + { + unsigned int visibleToggled = 0; //!< Bit per element id: the player sees the opposite of the default + std::optional texts[bhl::sb::MAX_ELEMENTS][bhl::sb::MAX_VARIANTS]; //!< The player's own texts + }; + + //! Kept apart from client_state_t, so that a full sync doesn't refill the budget + struct pacing_t + { + float nextSendTime = 0; //!< Nothing is sent to the client before this time + float periodEnd = 0; //!< End of the budget period + int bytesLeft = 0; //!< Budget left in the period + }; + + //! Kept apart from client_state_t: a full sync neither clears nor replays events + struct event_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; //!< Element, looked up when sent + int variant = 0; + int lifeMs = 0; + float time = 0; //!< When HudEvent was called + int argCount = 0; + value_t args[bhl::sb::MAX_EVENT_ARGS]; + }; + + struct client_state_t + { + bool isResetPending = false; + bool isConfigPending = false; + unsigned int columnsPending = 0; //!< Bit per column id + unsigned int listsResized = 0; //!< Bit per list id + uint64_t listItemsDirty[bhl::sb::MAX_LISTS] = {}; + unsigned int cellsDirty[MAX_TARGETS] = {}; //!< Bit per column id + std::bitset targetsCleared; //!< Bit per wire target: all its cells must be cleared + int teamNumbers[MAX_TEAMS] = {}; //!< Team number the cells of a team slot were sent with, 0 if none + unsigned int elementsPending = 0; //!< Bit per element id: definition, or removal if the id is free + unsigned int elementsSent = 0; //!< Bit per element id the client has + unsigned int textsDropped = 0; //!< Bit per element id: texts dropped, a client that has the element gets a removal before the definition + uint8_t sentParents[bhl::sb::MAX_ELEMENTS] = {}; //!< Parent id the client got with the element, for ids in elementsSent + uint8_t templatesPending[bhl::sb::MAX_ELEMENTS] = {}; //!< Bit per variant + uint8_t templatesSent[bhl::sb::MAX_ELEMENTS] = {}; //!< Bit per variant the client has a text for + unsigned int sentVisible = 0; //!< HudState the client has + unsigned int sentHidden = 0; + }; + + bool m_bActive = false; + bool m_bHasConfig = false; + unsigned int m_iHideFlags = 0; + char m_szTitle[bhl::sb::MAX_TITLE_LEN + 1] = {}; + char m_szTag[bhl::sb::MAX_TAG_LEN + 1] = {}; + + column_t m_Columns[bhl::sb::MAX_COLUMNS]; + int m_iColumnCount = 0; + list_t m_Lists[bhl::sb::MAX_LISTS]; + int m_iListCount = 0; + char m_szTeamNames[MAX_TEAMS][MAX_TEAM_NAME] = {}; + int m_iTeamCount = 0; + int m_TeamNumbers[MAX_TEAMS] = {}; //!< Team numbers of the team slots in the current frame + value_t m_Cells[MAX_TARGETS][bhl::sb::MAX_COLUMNS]; + + element_t m_Elements[bhl::sb::MAX_ELEMENTS]; + unsigned int m_iVisible = 0; //!< Bit per existing element id: default visibility + unsigned int m_iHiddenStd = 0; //!< E_HudStd + player_hud_t m_PlayerHud[MAX_PLAYERS + 1]; + + client_state_t m_Clients[MAX_PLAYERS + 1]; + pacing_t m_Pacing[MAX_PLAYERS + 1]; + std::deque m_Events[MAX_PLAYERS + 1]; + + int m_iBytesLeft = 0; + + //! Clears the state of every plugin and turns the extension off; team targets stay valid + void ClearState(); + void Activate(); + bool IsValidHudPlayer(int player); + int FindColumn(const char *key); + int FindList(const char *key); + int FindElement(const char *key); + int FindFreeElementId(); + bool SetColumn(const column_t &definition); + void SetCell(int target, const char *key, const value_t &value); + void StoreCell(int target, int column, const value_t &value); + void SetListItem(const char *key, int index, const value_t &value); + unsigned int GetFilledCells(int target); + + //! Returns false and changes nothing if the Element message would be larger than MAX_MSG_SIZE + bool SetElementDef(int id, const element_def_t &def); + void RemoveElement(int id); + void DropTexts(int id); + const std::string &GetText(int player, int id, int variant); + + void MarkElement(int id); + void MarkChildren(const char *parent); + + //! Returns false if the budget ran out before everything was sent + bool SendToClient(int idx); + bool BeginMessage(edict_t *pEdict, int size, bhl::sb::E_Op op); + bool SendHeader(edict_t *pEdict, client_state_t &state); + bool SendLists(edict_t *pEdict, client_state_t &state); + bool SendValues(edict_t *pEdict, client_state_t &state); + bool SendElements(edict_t *pEdict, client_state_t &state); + static int GetElementSize(const element_def_t &def); + bool SendElement(edict_t *pEdict, client_state_t &state, int id); + bool SendElementRemoval(edict_t *pEdict, int id); + bool SendTemplates(edict_t *pEdict, int idx, client_state_t &state); + bool SendHudState(edict_t *pEdict, int idx, client_state_t &state); + bool SendEvents(edict_t *pEdict, int idx, client_state_t &state); + + static value_t MakeValue(bhl::sb::E_ValueType type, const char *sprite, const char *text); + static bool IsEqual(const value_t &a, const value_t &b); + static bool IsEqual(const column_t &a, const column_t &b); + static bool IsEqual(const element_def_t &a, const element_def_t &b); + static int GetEventSize(const event_t &event); + static int GetValueSize(const value_t &value); + static void WriteValue(const value_t &value); +}; + +#endif diff --git a/src/game/server/client.cpp b/src/game/server/client.cpp index 68471370..7a12e308 100644 --- a/src/game/server/client.cpp +++ b/src/game/server/client.cpp @@ -100,6 +100,8 @@ GLOBALS ASSUMED SET: g_fGameOver */ void ClientDisconnect(edict_t *pEntity) { + serverapi()->ClientDisconnect(pEntity); + if (g_fGameOver) return; @@ -674,6 +676,8 @@ it gets sent into the rest of the engine. */ void ClientUserInfoChanged(edict_t *pEntity, char *infobuffer) { + serverapi()->ClientUserInfoChanged(pEntity, infobuffer); + // Is the client spawned yet? if (!pEntity->pvPrivateData) return; @@ -749,6 +753,7 @@ void ServerDeactivate(void) // Peform any shutdown operations here... // + serverapi()->ServerDeactivate(); } void ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) @@ -841,6 +846,8 @@ void StartFrame(void) if (g_pGameRules) g_pGameRules->Think(); + serverapi()->StartFrame(); + if (g_fGameOver) return; diff --git a/src/game/server/multiplay_gamerules.cpp b/src/game/server/multiplay_gamerules.cpp index 4a34a9ab..90cc8456 100644 --- a/src/game/server/multiplay_gamerules.cpp +++ b/src/game/server/multiplay_gamerules.cpp @@ -469,6 +469,8 @@ void CHalfLifeMultiplay ::InitHUD(CBasePlayer *pl) if (!sv_bhl_defer_motd.GetBool() || serverapi()->IsClientSupportsReceived(pl->entindex())) SendDefaultMOTDToClient(pl->edict()); + serverapi()->InitHUD(pl->edict()); + // loop through all active players and send their score and team info to the new client for (int i = 1; i <= gpGlobals->maxClients; i++) { diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 58c9fb46..a2208cae 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -35,6 +35,7 @@ #include "gamerules.h" #include "game.h" #include "hltv.h" +#include // #define DUCKFIX @@ -216,6 +217,7 @@ int gmsgViewMode = 0; int gmsgVGUIMenu = 0; int gmsgStatusIcon = 0; int gmsgFog = 0; +int gmsgBhlScore = 0; const char *const gCustomMessages[] = { "IconInfo", @@ -287,6 +289,7 @@ void LinkUserMessages(void) } gmsgFog = REG_USER_MSG("Fog", 7); + gmsgBhlScore = REG_USER_MSG(bhl::sb::MSG_NAME, -1); } LINK_ENTITY_TO_CLASS(player, CBasePlayer); @@ -5023,7 +5026,7 @@ Vector CBasePlayer ::AutoaimDeflection(Vector &vecSrc, float flDist, float flDel edict_t *bestent; TraceResult tr; - if (g_psv_aim->value == 0 && (!g_psv_allow_autoaim || g_psv_allow_autoaim->value != 0)) + if (g_psv_aim->value == 0 || (g_psv_allow_autoaim && g_psv_allow_autoaim->value == 0)) { m_fOnTarget = FALSE; return g_vecZero; diff --git a/src/game/shared/CMakeLists.txt b/src/game/shared/CMakeLists.txt index a5843ff4..f1d816a8 100644 --- a/src/game/shared/CMakeLists.txt +++ b/src/game/shared/CMakeLists.txt @@ -7,7 +7,9 @@ add_sources( enum_utils.h IBugfixedServer.h IGameVersion.h + IScoreboardExt.h mathlib.cpp + ScoreboardProtocol.h voice_common.h ) diff --git a/src/game/shared/ClientSupportsFlags.h b/src/game/shared/ClientSupportsFlags.h index 45b933f8..1e263a4d 100644 --- a/src/game/shared/ClientSupportsFlags.h +++ b/src/game/shared/ClientSupportsFlags.h @@ -12,5 +12,14 @@ enum class E_ClientSupports : unsigned int HtmlMotd = (1 << 1) }; +//! Features the client reports in the "_bhl" userinfo key (docs/scoreboard-protocol.md, 3.1) +enum class E_ClientCaps : unsigned int +{ + None = 0, + ScoreboardV1 = (1 << 0), //!< Receives "BhlScore" protocol version 1 + HudV1 = (1 << 1), //!< Draws HUD elements; only set together with ScoreboardV1 + All = ScoreboardV1 | HudV1 //!< Every bit this build knows, the default value of "_bhl" +}; + } #endif diff --git a/src/game/shared/IBugfixedServer.h b/src/game/shared/IBugfixedServer.h index 0099366b..e82987b4 100644 --- a/src/game/shared/IBugfixedServer.h +++ b/src/game/shared/IBugfixedServer.h @@ -2,11 +2,12 @@ #define IBUGFIXEDAPI_H #include #include +#include #include #define IBUGFIXEDSERVER_NAME "IBugfixedServer" #define IBUGFIXEDSERVER_MAJOR 1 -#define IBUGFIXEDSERVER_MINOR 0 +#define IBUGFIXEDSERVER_MINOR 4 class CGameRules; class IGameVersion; @@ -146,6 +147,24 @@ class IBugfixedServer : public IBaseInterface * @param deaths Number of deaths */ virtual void SetPlayerScore(int idx, int frags, int deaths) = 0; + + /** + * Returns the client's "_bhl" caps, normalized (docs/scoreboard-protocol.md, 3.1): known bits only, HudV1 only + * with ScoreboardV1, None for bots, HLTV proxies, empty slots and clients that don't report anything. + * + * Added in version v1.3 + * + * @param idx Client index [1; (maxplayers)] + */ + virtual bhl::E_ClientCaps GetClientCaps(int idx) = 0; + + /** + * Returns the scoreboard and HUD extension. Never null. Draft builds reported v1.2 with an incompatible + * IScoreboardExt, so callers must not use it below v1.3; HudSetSlotColor and HudEvent need v1.4. + * + * Added in version v1.3 + */ + virtual bhl::IScoreboardExt *GetScoreboard() = 0; }; } #endif diff --git a/src/game/shared/IScoreboardExt.h b/src/game/shared/IScoreboardExt.h new file mode 100644 index 00000000..48ebb9b9 --- /dev/null +++ b/src/game/shared/IScoreboardExt.h @@ -0,0 +1,129 @@ +#ifndef ISCOREBOARDEXT_H +#define ISCOREBOARDEXT_H + +namespace bhl +{ + +/** + * Server-side scoreboard and HUD extension. The methods back the bhl_sb_* and bhl_hud_* natives; + * bugfixedapi.inc and docs/scoreboard-protocol.md (5, 8, 9) describe their behaviour. + * + * Columns, lists and elements are addressed by keys of 1-15 characters of [a-z0-9_]. + * Wire ids are assigned by the server and never reach plugins. + * All plugins share one state, so plugins prefix their keys. + * + * Targets of cells: + * 0 - the whole game; + * 1 .. maxClients - a player; values for players that are not connected are ignored; + * a value of GetTeamTarget - a team. + * Any other target is ignored. + * + * Players of per-player texts and visibility: 0 is the default for everybody and drops the per-player values + * of that variant or bit, 1 .. maxClients is that player only (5.4). + * + * A null string is treated as "". Strings are truncated to the limits of bhl::sb (ScoreboardProtocol.h) + * on a UTF-8 character boundary, except templates, which are refused when too long. + * Unknown bits of flags and parts are dropped. A setter that writes the value already stored marks nothing. + * + * New methods must be added to the end. + */ +class IScoreboardExt +{ +public: + //! Removes everything of every plugin, sends Reset to every ready client and turns the extension off + virtual void Reset() = 0; + + //! Turns the custom scoreboard and the extension on. hideFlags: bhl::sb::E_ConfigFlags + virtual void SetConfig(unsigned int hideFlags, const char *title, const char *tag) = 0; + + /** + * Adds a column or replaces the definition of the column with the same key; its cells are kept. + * display: bhl::sb::E_Display except Badge; width is clamped to 0-255; sort: 0 or a priority starting at 1, + * plus bhl::sb::SORT_ASC; flags: bhl::sb::E_ColumnFlags. + * @return false if the key is invalid, display is Badge or unknown, or all 32 columns are used + */ + virtual bool AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags) = 0; + + //! Returns an opaque target of a team that stays valid until the map changes, or -1 + virtual int GetTeamTarget(const char *teamName) = 0; + + virtual void SetInt(int target, const char *key, int value) = 0; + virtual void SetText(int target, const char *key, const char *text) = 0; + virtual void SetIcon(int target, const char *key, const char *sprite, const char *text) = 0; + + //! cur and max are clamped to 0-65535 + virtual void SetProgress(int target, const char *key, int cur, int max) = 0; + + //! Clears a cell, or every cell of the target if key is "" + virtual void Clear(int target, const char *key) = 0; + + /** + * count is clamped to 0-64; 0 removes the list on the clients. + * @return false if the key is invalid or all 8 lists are used + */ + virtual bool ListResize(const char *key, int count) = 0; + + //! Items out of range and unknown lists are ignored + virtual void ListSetInt(const char *key, int index, int value) = 0; + virtual void ListSetText(const char *key, int index, const char *text) = 0; + virtual void ListSetIcon(const char *key, int index, const char *sprite, const char *text) = 0; + + //! Sets a Clock cell (4.3). flags: bhl::sb::E_ClockFlags. A running clock runs from the call, so a call with the same values restarts it (5.2). + virtual void SetClock(int target, const char *key, int ms, unsigned int flags) = 0; + + /** + * host may name a column that is added later. + * @return false if key or host is invalid, or all 32 columns are used + */ + virtual bool AddBadge(const char *key, const char *host) = 0; + + /** + * Turns the extension on. Bit 0 of flags is ignored: the color mode comes from HudSetColor. + * kind: bhl::sb::E_ElementKind except None; font: bhl::sb::E_Font, unknown fonts are Text; + * align: anchors (4.3), bits above 3 are dropped; flags: bhl::sb::E_ElementFlags. + */ + virtual bool HudAdd(const char *key, int kind, float x, float y, int font, int align, unsigned int flags) = 0; + + //! place: bhl::sb::E_Place; parent may name an element that is added later; gap is clamped to 0-255 + virtual bool HudSetPlace(const char *key, int place, const char *parent, int gap) = 0; + + //! r < 0: follow hud_color; g and b are ignored. Components are clamped to 0-255. + virtual bool HudSetColor(const char *key, int r, int g, int b, int a) = 0; + + /** + * A value ref "@value" is accepted; it names the element's own value, so clients treat it as missing. + * false, and nothing changes, if the Element message would be larger than bhl::sb::MAX_MSG_SIZE. + */ + virtual bool HudBind(const char *key, const char *value, const char *list, const char *select) = 0; + + //! param: bhl::sb::E_Param of the element's kind or of every kind; false as HudBind + virtual bool HudSetParam(const char *key, int param, int value) = 0; + + virtual bool HudSetText(int player, const char *key, int variant, const char *text) = 0; + virtual bool HudShow(int player, const char *key, bool show) = 0; + + //! Unknown keys are ignored, "" removes every element + virtual void HudRemove(const char *key) = 0; + + //! Sets or clears only the given parts (bhl::sb::E_HudStd), for everybody. Hiding a part turns the extension on. + virtual void HudHideStd(unsigned int parts, bool hide) = 0; + + /** + * slot: 0-7, bhl::sb::SLOT_WARN or bhl::sb::SLOT_ACCENT; r < 0 clears the slot. Components are clamped + * to 0-255. false as HudBind. + * Added in version v1.4 + */ + virtual bool HudSetSlotColor(const char *key, int slot, int r, int g, int b, int a) = 0; + + /** + * Sends a line to a Feed element. Events are not state (5.5, 5.6): only clients that get the scoreboard and have + * HudV1 now get them. lifeMs is clamped to 0-65535, 0 for the life_ms param of the element. args: argCount Int + * values, 0 to bhl::sb::MAX_EVENT_INTS; an Icon value follows if iconSprite or iconText is not empty. + * Added in version v1.4 + */ + virtual bool HudEvent(int player, const char *key, int variant, int lifeMs, const int *args, int argCount, const char *iconSprite, const char *iconText) = 0; +}; + +} + +#endif diff --git a/src/game/shared/ScoreboardProtocol.h b/src/game/shared/ScoreboardProtocol.h new file mode 100644 index 00000000..4baf62ee --- /dev/null +++ b/src/game/shared/ScoreboardProtocol.h @@ -0,0 +1,482 @@ +#ifndef SCOREBOARDPROTOCOL_H +#define SCOREBOARDPROTOCOL_H +#include +#include +#include +#include + +/** + * Constants of the "BhlScore" user message, shared by the server and the client. + * See docs/scoreboard-protocol.md for the format. Section numbers below refer to it. + */ +namespace bhl::sb +{ + +constexpr const char *MSG_NAME = "BhlScore"; +constexpr const char *CAPS_KEY = "_bhl"; + +//---------------------------------------------------------------------------------------------------- +// Limits (4.7). String limits are in bytes, without the terminating NUL. +//---------------------------------------------------------------------------------------------------- +constexpr int MAX_MSG_SIZE = 192; +constexpr int MAX_COLUMNS = 32; +constexpr int MAX_LISTS = 8; +constexpr int MAX_LIST_ITEMS = 64; +constexpr int MAX_ELEMENTS = 32; +constexpr int MAX_VARIANTS = 8; +constexpr int MAX_DOTS = 10; //!< A scoreboard Meter with max above this is a bar +constexpr int MAX_EVENT_ARGS = 5; //!< Args of one Event: 4 numbers and an icon from the natives +constexpr int MAX_EVENT_INTS = 4; //!< Number args of bhl_hud_event + +constexpr int MAX_KEY_LEN = 15; //!< Column, list and element keys +constexpr int MAX_COLUMN_TITLE_LEN = 31; +constexpr int MAX_TITLE_LEN = 63; +constexpr int MAX_TAG_LEN = 15; +constexpr int MAX_TEXT_LEN = 31; //!< Text value, Icon sprite and Icon text +constexpr int MAX_REF_LEN = 31; //!< Element select and value +constexpr int MAX_TEMPLATE_LEN = 188; +constexpr int MAX_BUILTIN_NAME_LEN = 14; //!< Name of a built-in value after '@' +constexpr int MAX_PLACEHOLDERS = 16; //!< Placeholders in one template +constexpr int MAX_CUT = 255; //!< Largest cut format of a placeholder +constexpr int MAX_EVAL_LEN = 255; //!< Evaluated text, in UTF-16 units + +//! Id that means "every column of the target" (Values, only with E_ValueType::None) +constexpr int ALL_COLUMNS = 0xFF; + +//! Column host and element parent when there is none +constexpr int NO_ID = 0xFF; + +constexpr int SORT_ASC = 0x80; +constexpr int SORT_PRIORITY_MASK = 0x7F; + +//---------------------------------------------------------------------------------------------------- +// Targets of Values (4.3) +//---------------------------------------------------------------------------------------------------- +constexpr int TARGET_GLOBAL = 0x00; +constexpr int TARGET_PLAYER_FIRST = 0x01; +constexpr int TARGET_PLAYER_LAST = 0x40; +constexpr int TARGET_TEAM_BASE = 0x80; //!< Team number N is TARGET_TEAM_BASE + N +constexpr int TARGET_TEAM_FIRST = 0x81; +constexpr int TARGET_TEAM_LAST = 0xC0; + +//---------------------------------------------------------------------------------------------------- +// Element positions (4.3, 8.4) +//---------------------------------------------------------------------------------------------------- +constexpr int POS_SCALE = 8192; //!< x and y are in 1/8192 of the screen size +constexpr int POS_CENTER = -8192; //!< x or y exactly at the center + +/** + * Converts a set_hudmessage coordinate to the wire value: + * (int)floor(f * 8192 + 0.5), clamped to -32768..32767. 0.025 gives 205, -1.0 gives POS_CENTER. + */ +inline int PositionToWire(float f) +{ + if (std::isnan(f)) + return 0; + + return static_cast(std::clamp(std::floor(static_cast(f) * POS_SCALE + 0.5), -32768.0, 32767.0)); +} + +//---------------------------------------------------------------------------------------------------- +// Opcodes (4.3) +//---------------------------------------------------------------------------------------------------- +enum class E_Op : unsigned int +{ + Reset = 0, + Config = 1, + Column = 2, + Values = 3, + List = 4, + Element = 5, + Template = 6, + HudState = 7, + Event = 8, //!< A line of a Feed element; not state, never replayed +}; + +//---------------------------------------------------------------------------------------------------- +// Values (4.3) +//---------------------------------------------------------------------------------------------------- +enum class E_ValueType : unsigned int +{ + None = 0, + Int = 1, + Text = 2, + Icon = 3, + Progress = 4, + Clock = 5, +}; + +constexpr int CLOCK_VALUE_LEN = 5; //!< long ms, byte flags + +//! Flags byte of a Clock value +enum class E_ClockFlags : unsigned int +{ + None = 0, + Run = (1 << 0), + Down = (1 << 1), //!< Counts down to 0 and stops there + All = Run | Down, +}; + +//---------------------------------------------------------------------------------------------------- +// Config (4.3) +//---------------------------------------------------------------------------------------------------- +enum class E_ConfigFlags : unsigned int +{ + None = 0, + HideFrags = (1 << 0), + HideDeaths = (1 << 1), + HideEff = (1 << 2), + HideSteamID = (1 << 3), + All = HideFrags | HideDeaths | HideEff | HideSteamID, +}; + +//---------------------------------------------------------------------------------------------------- +// Columns (4.3) +//---------------------------------------------------------------------------------------------------- +enum class E_Display : unsigned int +{ + Text = 0, + Icon = 1, + Meter = 2, + Builtin = 3, + Steps = 4, + Badge = 5, //!< Drawn after the cells of the host column, takes no width +}; + +enum class E_ColumnFlags : unsigned int +{ + None = 0, + Hidden = (1 << 0), + AlignCenter = (1 << 1), + AlignRight = (2 << 1), + AlignMask = (3 << 1), //!< 3 is treated as left + Primary = (1 << 3), + MarkLast = (1 << 4), //!< Steps: the last step has its own color + All = Hidden | AlignMask | Primary | MarkLast, +}; + +//! Default widths of custom columns with width 0, proportional units +constexpr int DEFAULT_WIDTH_TEXT = 60; +constexpr int DEFAULT_WIDTH_ICON = 100; +constexpr int DEFAULT_WIDTH_METER = 90; +constexpr int DEFAULT_WIDTH_STEPS = 60; + +//! Width of a column whose width is 0 +inline int GetDefaultWidth(E_Display display) +{ + return display == E_Display::Icon ? DEFAULT_WIDTH_ICON : display == E_Display::Meter ? DEFAULT_WIDTH_METER : display == E_Display::Steps ? DEFAULT_WIDTH_STEPS : DEFAULT_WIDTH_TEXT; +} + +//---------------------------------------------------------------------------------------------------- +// HUD elements (4.3, 8) +//---------------------------------------------------------------------------------------------------- +enum class E_ElementKind : unsigned int +{ + None = 0, //!< Removes the element. Unknown kinds remove it too. + Text = 1, + Meter = 2, + Strip = 3, + Icon = 4, + Board = 5, //!< Rows of the scoreboard order or of a list + Feed = 6, //!< Lines of Event messages + Box = 7, //!< Backdrop of the group of its parent +}; + +inline bool IsKnownKind(int kind) +{ + return kind >= static_cast(E_ElementKind::Text) && kind <= static_cast(E_ElementKind::Box); +} + +//! Color slots of an element: variants 0-7, then these (4.3, 8.5) +constexpr int SLOT_WARN = 8; //!< Color while warn_at holds +constexpr int SLOT_ACCENT = 9; //!< Accent bar of a Box +constexpr int MAX_COLOR_SLOTS = 10; + +//! Warn color when the element has none in SLOT_WARN +inline constexpr unsigned char DEFAULT_WARN_COLOR[4] = { 255, 64, 32, 255 }; + +enum class E_ElementFlags : unsigned int +{ + None = 0, + HudColor = (1 << 0), //!< rgb follows hud_color, only alpha of the message is used + Subject = (1 << 1), //!< Hidden when there is no subject + NoScoreboard = (1 << 2), //!< Hidden while the scoreboard is open + Leader = (1 << 3), //!< The subject is the first row of the scoreboard order + All = HudColor | Subject | NoScoreboard | Leader, +}; + +//! What the position of an element is relative to. Unknown values are Screen. +enum class E_Place : unsigned int +{ + Screen = 0, + Parent = 1, + NumbersRow = 2, + BannerTop = 3, + BannerBottom = 4, + ParentLeft = 5, + ParentRight = 6, +}; + +inline bool IsParentPlace(E_Place place) +{ + return place == E_Place::Parent || place == E_Place::ParentLeft || place == E_Place::ParentRight; +} + +inline bool IsBannerPlace(E_Place place) +{ + return place == E_Place::BannerTop || place == E_Place::BannerBottom; +} + +//! Anchors in the align byte: bits 0-1 horizontal, bits 2-3 vertical +constexpr int ANCHOR_AUTO = 0; +constexpr int ANCHOR_START = 1; //!< Left or top edge +constexpr int ANCHOR_CENTER = 2; +constexpr int ANCHOR_END = 3; //!< Right or bottom edge + +constexpr int ALIGN_MASK = 0x0F; + +//! Font of an element (8.5). Unknown ids are Text. +enum class E_Font : unsigned int +{ + Text = 0, + Large = 1, + Small = 2, + Huge = 3, +}; + +constexpr int FONT_COUNT = 4; + +//! Names of the fonts in ClientSchemeBase.res, indexed by E_Font +inline constexpr const char *FONT_NAMES[FONT_COUNT] = { "HudServerText", "HudServerLarge", "HudServerSmall", "HudServerHuge" }; + +//! Kind params of elements (8.7-8.9) +enum class E_Param : unsigned int +{ + // Meter + Dots = 1, + DotSize = 2, + DotGap = 3, + BarWide = 4, + Counter = 5, + CounterGap = 6, + AlphaEmpty = 7, + + // Strip + CellWide = 10, + CellMinWide = 11, + CellTall = 12, + CellGap = 13, + IconPadding = 14, + MaxWide = 15, + AlphaPassed = 16, + AlphaCurrent = 17, + AlphaFuture = 18, + AlphaIconFuture = 19, + Frame = 20, + + // Icon + IconTall = 30, + IconGap = 31, + + // Every kind (8.13). Ids from 32 on are sent after all older ids. + FlashMs = 32, + FadeMs = 33, + HoldMs = 34, + WarnAt = 35, + WarnPulseMs = 36, + + // Meter + Form = 40, + + // Strip + Track = 41, + + // Board + Rows = 44, + BoardMode = 45, + RowGap = 46, + ColumnGap = 47, + FillAlpha = 48, + HighlightAlpha = 49, + + // Feed + Lines = 52, + LifeMs = 53, + LineFadeMs = 54, + Queue = 55, + LineGap = 56, + + // Box + AccentWide = 60, + Radius = 61, +}; + +constexpr int MAX_PARAM_ID = 63; //!< Param ids fit a 64-bit mask + +//! Meter forms (param form) +enum class E_MeterForm : unsigned int +{ + Line = 0, //!< Dots or a bar + Ring = 1, //!< Dots on a circle +}; + +//! Rows of a Board (param board_mode) +enum class E_BoardMode : unsigned int +{ + Top = 0, //!< The first rows + TopAndOwn = 1, //!< The first rows and the own or highlighted row under them + Window = 2, //!< Rows around the own or highlighted row +}; + +struct ParamInfo +{ + E_Param id; + E_ElementKind kind; //!< Params of other kinds are ignored; None means every kind + const char *pszName; //!< Name in the spec and in HudServerPanel of HudLayoutBase.res + int iMin; + int iMax; + int iDefault; +}; + +/** + * Ranges and defaults of the params. Values are clamped to the range on both sides. + * cell_min_wide is limited to 1-255 here; the layout also keeps it at most cell_wide (8.8). + */ +inline constexpr ParamInfo PARAM_INFO[] = { + { E_Param::Dots, E_ElementKind::Meter, "dots", 0, 32, 10 }, + { E_Param::DotSize, E_ElementKind::Meter, "dot_size", 2, 64, 7 }, + { E_Param::DotGap, E_ElementKind::Meter, "dot_gap", 0, 64, 3 }, + { E_Param::BarWide, E_ElementKind::Meter, "bar_wide", 0, 640, 0 }, + { E_Param::Counter, E_ElementKind::Meter, "counter", 0, 2, 1 }, + { E_Param::CounterGap, E_ElementKind::Meter, "counter_gap", 0, 64, 6 }, + { E_Param::AlphaEmpty, E_ElementKind::Meter, "alpha_empty", 0, 255, 80 }, + + { E_Param::CellWide, E_ElementKind::Strip, "cell_wide", 1, 255, 30 }, + { E_Param::CellMinWide, E_ElementKind::Strip, "cell_min_wide", 1, 255, 14 }, + { E_Param::CellTall, E_ElementKind::Strip, "cell_tall", 1, 255, 15 }, + { E_Param::CellGap, E_ElementKind::Strip, "cell_gap", 0, 64, 3 }, + { E_Param::IconPadding, E_ElementKind::Strip, "icon_padding", 0, 64, 2 }, + { E_Param::MaxWide, E_ElementKind::Strip, "max_wide", 0, 4096, 300 }, + { E_Param::AlphaPassed, E_ElementKind::Strip, "alpha_passed", 0, 255, 112 }, + { E_Param::AlphaCurrent, E_ElementKind::Strip, "alpha_current", 0, 255, 48 }, + { E_Param::AlphaFuture, E_ElementKind::Strip, "alpha_future", 0, 255, 24 }, + { E_Param::AlphaIconFuture, E_ElementKind::Strip, "alpha_icon_future", 0, 255, 80 }, + { E_Param::Frame, E_ElementKind::Strip, "frame", 0, 1, 1 }, + + { E_Param::IconTall, E_ElementKind::Icon, "icon_tall", 0, 255, 0 }, + { E_Param::IconGap, E_ElementKind::Icon, "icon_gap", 0, 64, 2 }, + + { E_Param::FlashMs, E_ElementKind::None, "flash_ms", 0, 5000, 0 }, + { E_Param::FadeMs, E_ElementKind::None, "fade_ms", 0, 5000, 0 }, + { E_Param::HoldMs, E_ElementKind::None, "hold_ms", 0, 30000, 0 }, + { E_Param::WarnAt, E_ElementKind::None, "warn_at", 0, 32767, 0 }, + { E_Param::WarnPulseMs, E_ElementKind::None, "warn_pulse_ms", 0, 5000, 0 }, + + { E_Param::Form, E_ElementKind::Meter, "form", 0, 1, 0 }, + + { E_Param::Track, E_ElementKind::Strip, "track", 0, 1, 0 }, + + { E_Param::Rows, E_ElementKind::Board, "rows", 1, 16, 3 }, + { E_Param::BoardMode, E_ElementKind::Board, "board_mode", 0, 2, 0 }, + { E_Param::RowGap, E_ElementKind::Board, "row_gap", 0, 64, 2 }, + { E_Param::ColumnGap, E_ElementKind::Board, "column_gap", 0, 64, 8 }, + { E_Param::FillAlpha, E_ElementKind::Board, "fill_alpha", 0, 255, 0 }, + { E_Param::HighlightAlpha, E_ElementKind::Board, "highlight_alpha", 0, 255, 48 }, + + { E_Param::Lines, E_ElementKind::Feed, "lines", 1, 8, 4 }, + { E_Param::LifeMs, E_ElementKind::Feed, "life_ms", 100, 30000, 5000 }, + { E_Param::LineFadeMs, E_ElementKind::Feed, "line_fade_ms", 0, 5000, 400 }, + { E_Param::Queue, E_ElementKind::Feed, "queue", 0, 1, 0 }, + { E_Param::LineGap, E_ElementKind::Feed, "line_gap", 0, 64, 2 }, + + { E_Param::AccentWide, E_ElementKind::Box, "accent_wide", 0, 64, 0 }, + { E_Param::Radius, E_ElementKind::Box, "radius", 0, 32, 0 }, +}; + +//! Returns the info of a param of the kind, or nullptr if the kind has no such param +inline const ParamInfo *FindParamInfo(E_ElementKind kind, int id) +{ + for (const ParamInfo &info : PARAM_INFO) + { + if (static_cast(info.id) == id) + return info.kind == kind || info.kind == E_ElementKind::None ? &info : nullptr; + } + + return nullptr; +} + +//! Standard HUD parts that HudState.hide hides (8.12) +enum class E_HudStd : unsigned int +{ + None = 0, + Timer = (1 << 0), //!< hud_timer modes 1-3 + NextMap = (1 << 1), //!< The hud_nextmap line + CustomTimers = (1 << 2), //!< Display of customtimer timers, the end sound still plays + Speedometer = (1 << 3), //!< hud_speedometer in its bottom position + JumpSpeed = (1 << 4), //!< hud_jumpspeed in its bottom position + All = Timer | NextMap | CustomTimers | Speedometer | JumpSpeed, +}; + +//---------------------------------------------------------------------------------------------------- +// Keys and refs +//---------------------------------------------------------------------------------------------------- + +//! Checks a column, list or element key: 1-15 characters of [a-z0-9_] +inline bool IsValidKey(const char *key) +{ + if (!key) + return false; + + size_t len = strlen(key); + return len >= 1 && len <= MAX_KEY_LEN && strspn(key, "abcdefghijklmnopqrstuvwxyz0123456789_") == len; +} + +/** + * Checks a ref of Element.select and Element.value (4.3): + * "[^](key|@name)[:cur|:max|:left]", which is at most 21 bytes, below MAX_REF_LEN; name is 1-14 characters of [a-z]. + * Built-in names are not checked against the known ones. "" is not a ref. + */ +inline bool IsValidRef(const char *ref) +{ + if (!ref) + return false; + + const char *name = ref[0] == '^' ? ref + 1 : ref; + const char *format = strchr(name, ':'); + size_t nameLen = format ? static_cast(format - name) : strlen(name); + + if (name[0] == '@') + { + if (nameLen < 2 || nameLen - 1 > MAX_BUILTIN_NAME_LEN || strspn(name + 1, "abcdefghijklmnopqrstuvwxyz") != nameLen - 1) + return false; + } + else + { + if (nameLen < 1 || nameLen > MAX_KEY_LEN || strspn(name, "abcdefghijklmnopqrstuvwxyz0123456789_") != nameLen) + return false; + } + + return !format || !strcmp(format + 1, "cur") || !strcmp(format + 1, "max") || !strcmp(format + 1, "left"); +} + +/** + * Checks whether the sprite of an Icon value is a sprite file rather than a hud.txt name (4.3): + * "sprites/.spr", up to MAX_TEXT_LEN bytes of [A-Za-z0-9_./-], without "..". + */ +inline bool IsSpriteFilePath(const char *sprite) +{ + constexpr char PREFIX[] = "sprites/"; + constexpr char SUFFIX[] = ".spr"; + constexpr size_t PREFIX_LEN = sizeof(PREFIX) - 1; + constexpr size_t SUFFIX_LEN = sizeof(SUFFIX) - 1; + size_t len = sprite ? strlen(sprite) : 0; + + return len > PREFIX_LEN + SUFFIX_LEN && len <= MAX_TEXT_LEN + && !strncmp(sprite, PREFIX, PREFIX_LEN) && !strcmp(sprite + len - SUFFIX_LEN, SUFFIX) + && !strstr(sprite, "..") + && strspn(sprite, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./-") == len; +} + +} + +#endif