Files
OpenFrontIO/src/client/graphics/PlayerIcons.ts
T
VariableVince b5ca0f9d8f Perf/refactor/fix(NameLayer): about 10% extra improvement (#3540)
## Description:

NameLayer perf part 2 after
https://github.com/openfrontio/OpenFrontIO/pull/3475 with thanks to
@scamiv. Shaves off another 10% or thereabouts, even doing something
extra for a fix (see below).

Also refactor/fixes around NameLayer and PlayerIcons, which is used by
both NameLayer and PlayerInfoOverlay, and underlying function in
GameView.

This would go well with other PR
https://github.com/openfrontio/OpenFrontIO/pull/3481, since this layer
reads multiple settings. Reasoning to not use events and instead rely on
fast caching is explained in that PR.

### Contents

- Fixes:
-- Fixes bug on .dev introduced by wrong assumption by me in previous PR
https://github.com/openfrontio/OpenFrontIO/pull/3475. displayName CAN
change during game, when Hidden Names is toggled from settings, so needs
to be put back in renderPlayerInfo.
-- Fixes longer existing bug: it was assumed Dark Mode didn't change
after creation of icon element. Now it also sets Dark Mode attribute
when updating icons elements.
-- Fixes target mark icons not being shown to team members, while the
icons were shown to normal allies. And EventsDisplay displayed message
"XX requests you attack XX" to both team members and allies already. So
why is the icon not shown to both if the message already is. While we
improve performance of GameView > PlayerView > transitiveTargets (which
is only used by NameLayer/PlayerIcons so only in this context). We can
add team members' targets to it in one go. So previously
transitiveTargets returned: your own targets and allies' targets. Now
transitiveTargets is faster and returns: your own targets and allies'
targets and team members' targets.

- NameLayer:
-- renderLayer: for target icons, getPlayerIcons used to fetch
myPlayer.transitiveTargets each time. While that doesn't change per
player we're rendering for. So now, we fetch myPlayer.transitiveTargets
once per call to renderPlayerInfo, which passes it on to getPlayerIcons.
So now we check it 1x each 100ms (renderCheckRate) inside of
renderLayer. Instead of up to 100s of times each 500ms
(renderRefreshRate) inside of getPlayerIcons inside of renderPlayerInfo
loop.
-- createBasePlayerElement and renderPlayerInfo: use cloneNode where
possible with templates
-- createPlayerElement: only find the elements and set font and flag.
Leave the rest to renderLayer > renderPlayerInfo which fills displayName
and troops and font color very soon after anyway. I haven't noticed a
difference in testing.
-- cache game.config() and others
-- renderPlayerInfo: remove check if render.flagDiv exists, we know it
exists. Check if fontColor changed before assigning it (it never
changes, currently, be it dark mode or light mode). Don't check if
troops or size changes, that happens so often that the overhead for
checking would be smaller than the win, probably.
-- We don't require nameLocation to be changed to change scale (see
previous Namelayer perf PR for the reason). But it seems good to check
if the transform changed before 'overwriting' it, so do that now
instead.
-- Remove Alliance icon DOM traversals. Only do it once, for each time
an alliance icon is displayed. To this end, also made NameLayer more
agnostic on Alliance icon stuff. By moving more code to PlayerIcons. See
below.
-- Use cached allianceDuration instead of fetching this static value
every time
-- Re-use from PlayerIcons: ALLIANCE_ICON_ID, TRAITOR_ICON_ID etc
-- create more sub-functions to make the icons loop in renderLayer more
readable: handleEmojiIcon, handleAllianceIcons,
createOrUpdateIconElement (createIconElement already existed, now
combined), handleTraitorIcon.
For Alliance icons, this was already done in PlayerIcons.ts through
createAllianceProgressIcon (now createAllianceProgressIconRefs), and
more now to skip some DOM traversals. But most of this belongs in
NameLayer itself when it comes to seperation of concern.
- cache dark mode (as boolean and as string)
- use dark mode to update (alliance) icons too, not only on create,
since the setting can change after icon element creation and before it
is removed
-- for getPlayerIcons, add this.alliancesDisabled. If disabled,
getPlayerIcons won't fetch Alliance icon and Alliance Request icon.

- PlayerIcons:
-- use cloneNode where possible
-- added check for alliances disabled: then skip alliance (request) icon
checks
-- See point under NameLayer about the move of Alliance icon code to
PlayerIcons. To make NameLayer even more agnostic on it and keep it in
one place.
-- getPlayerIcons: skip creating a new Set from
myPlayer.transitiveTargets() each time getPlayerIcons is called. One
allocation less. Just do .includes on the returned array. Probably just
as fast in this case, also because not many Targets are present many
times anyway.
-- getPlayerIcons: on outgoingEmojis(), use .find() instead of .filter()
since we only use the first result anyway and it saves us another
allocation.
-- getPlayerIcons: for nukes, only fetch the ones from the player we're
rendering for, not all game nukes. Also don't use .filter() and just a
normal loop to skip an allocation. Logic outcome is the same.
-- getPlayerIcons: for target icons, it used to fetch
myPlayer.transitiveTargets each time. While that doesn't change per
player we're rendering for. So now, NameLayer fetches
myPlayer.transitiveTargets once per call to renderPlayerInfo, which
passes it on to getPlayerIcons.
-- Remove the need for querySelector and getElementsByTagName("img")
alltogether. Since this would be done for every time an alliance was
(re-)created, here in createAllianceProgressIconRefs in PlayerIcons it
makes more sense to not do DOM traversal than in createPlayerElement in
NameLayer where we only do it once per player per game anyway. We assume
updateAllianceProgressIconRefs just knows of all image names in
createAllianceProgressIconRefs. This is a bit less dynamic and
maintainable maybe, but i think worth the win. And the functions are all
one-purpose and not meant to be used dynamically by another caller
anyway.
-- So instead of updateAllianceProgressIconRefs looping through
refs.images, now just update the different images each. See point above.

- PlayerInfoOverlay: also re-use the new exported consts from
PlayerIcons. Since we put those in PlayerIcons anyway, need to be
consistent. Even though PlayerInfoOverlay is outside of the scope of
this PR otherwise.
-- for getPlayerIcons, add this.alliancesDisabled here too. If disabled,
getPlayerIcons won't fetch Alliance icon and Alliance Request icon. We
also send includeAllianceIcon = false, which means Alliance icon will
already be excluded but Alliance Request icon is normally still fetched
and shown.

- GameView > PlayerView: for transitiveTargets (only used in
NameLayer/PlayerIcons so only in this context), improve performance. It
did several allocations. Now it loops directly over the arrays we need.
Also (as mentioned under Fixes) previously transitiveTargets returned:
your own targets and allies' targets. Now transitiveTargets is faster
and returns: your own targets and allies' targets and team members'
targets.


**BEFORE**

![BEFORE](https://github.com/user-attachments/assets/02ff167f-7978-4968-a26e-0c64bf4fb2f3)

**AFTER** (including now getting team members' targets for
myPlayer.transitiveTargets)

![AFTER](https://github.com/user-attachments/assets/1b81f9cc-bb8b-4d6b-97e4-f6db3802e55c)

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced

## Please put your Discord username so you can be contacted if a bug or
regression is found:

tryout33
2026-04-06 20:36:23 -07:00

347 lines
10 KiB
TypeScript

import { assetUrl } from "../../core/AssetUrls";
import { AllPlayers, Nukes } from "../../core/game/Game";
import { GameView, PlayerView } from "../../core/game/GameView";
const allianceIcon = assetUrl("images/AllianceIcon.svg");
const allianceIconFaded = assetUrl("images/AllianceIconFaded.svg");
const allianceRequestBlackIcon = assetUrl(
"images/AllianceRequestBlackIcon.svg",
);
const allianceRequestWhiteIcon = assetUrl(
"images/AllianceRequestWhiteIcon.svg",
);
const crownIcon = assetUrl("images/CrownIcon.svg");
const disconnectedIcon = assetUrl("images/DisconnectedIcon.svg");
const embargoBlackIcon = assetUrl("images/EmbargoBlackIcon.svg");
const embargoWhiteIcon = assetUrl("images/EmbargoWhiteIcon.svg");
const nukeRedIcon = assetUrl("images/NukeIconRed.svg");
const nukeWhiteIcon = assetUrl("images/NukeIconWhite.svg");
const questionMarkIcon = assetUrl("images/QuestionMarkIcon.svg");
const targetIcon = assetUrl("images/TargetIcon.svg");
const traitorIcon = assetUrl("images/TraitorIcon.svg");
let allianceIconTemplate: HTMLDivElement | undefined;
export const ALLIANCE_ICON_ID = "alliance" as const;
const ALLIANCE_PROGRESS_OVERLAY_CLASS = "alliance-progress-overlay";
const ALLIANCE_QUESTION_MARK_CLASS = "alliance-question-mark";
export const TRAITOR_ICON_ID = "traitor" as const;
const CROWN_ICON_ID = "crown" as const;
const DISCONNECTED_ICON_ID = "disconnected" as const;
const ALLIANCE_REQUEST_ICON_ID = "alliance-request" as const;
const TARGET_ICON_ID = "target" as const;
const EMOJI_ICON_ID = "emoji" as const;
const EMBARGO_ICON_ID = "embargo" as const;
const NUKE_ICON_ID = "nuke" as const;
export const IMAGE_ICON_KIND = "image" as const;
export const EMOJI_ICON_KIND = "emoji" as const;
export type PlayerIconId =
| typeof CROWN_ICON_ID
| typeof TRAITOR_ICON_ID
| typeof DISCONNECTED_ICON_ID
| typeof ALLIANCE_ICON_ID
| typeof ALLIANCE_REQUEST_ICON_ID
| typeof TARGET_ICON_ID
| typeof EMOJI_ICON_ID
| typeof EMBARGO_ICON_ID
| typeof NUKE_ICON_ID;
export type PlayerIconKind = typeof IMAGE_ICON_KIND | typeof EMOJI_ICON_KIND;
export type AllianceProgressIconRefs = {
wrapper: HTMLDivElement;
base: HTMLImageElement;
overlay: HTMLDivElement;
colored: HTMLImageElement;
questionMark: HTMLImageElement;
};
export interface PlayerIconDescriptor {
id: PlayerIconId;
kind: PlayerIconKind;
/** Image URL for image icons */
src?: string;
/** Text content for emoji icons */
text?: string;
/** Whether the icon should be visually centered over the name */
center?: boolean;
}
export interface PlayerIconParams {
game: GameView;
player: PlayerView;
/** Whether the alliance icon (handshake) should be included */
includeAllianceIcon: boolean;
/** Player currently in first place, used for the crown icon */
firstPlace: PlayerView | null;
alliancesDisabled: boolean;
darkMode?: boolean;
transitiveTargets?: PlayerView[];
}
export function getFirstPlacePlayer(game: GameView): PlayerView | null {
const sorted = game
.playerViews()
.sort((a, b) => b.numTilesOwned() - a.numTilesOwned());
return sorted.length > 0 ? sorted[0] : null;
}
export function getPlayerIcons(
params: PlayerIconParams,
): PlayerIconDescriptor[] {
const {
game,
player,
includeAllianceIcon,
firstPlace,
alliancesDisabled,
darkMode,
transitiveTargets,
} = params;
const myPlayer = game.myPlayer();
const userSettings = game.config().userSettings();
const isDarkMode = darkMode ?? userSettings?.darkMode() ?? false;
const emojisEnabled = userSettings?.emojis() ?? false;
const alliancesOff = alliancesDisabled ?? game.config().disableAlliances();
const icons: PlayerIconDescriptor[] = [];
// Crown icon for first place
if (player === firstPlace) {
icons.push({ id: CROWN_ICON_ID, kind: IMAGE_ICON_KIND, src: crownIcon });
}
// Traitor icon
if (player.isTraitor()) {
icons.push({
id: TRAITOR_ICON_ID,
kind: IMAGE_ICON_KIND,
src: traitorIcon,
});
}
// Disconnected icon
if (player.isDisconnected()) {
icons.push({
id: DISCONNECTED_ICON_ID,
kind: IMAGE_ICON_KIND,
src: disconnectedIcon,
});
}
if (!alliancesOff) {
// Alliance icon
if (
includeAllianceIcon &&
myPlayer !== null &&
myPlayer.isAlliedWith(player)
) {
icons.push({
id: ALLIANCE_ICON_ID,
kind: IMAGE_ICON_KIND,
src: allianceIcon,
});
}
// Alliance request icon (theme dependent)
if (myPlayer !== null && player.isRequestingAllianceWith(myPlayer)) {
const allianceRequestIcon = isDarkMode
? allianceRequestWhiteIcon
: allianceRequestBlackIcon;
icons.push({
id: ALLIANCE_REQUEST_ICON_ID,
kind: IMAGE_ICON_KIND,
src: allianceRequestIcon,
});
}
}
// Target icon (centered on the map, but regular in overlays)
const targets = transitiveTargets ?? myPlayer?.transitiveTargets() ?? [];
if (targets.includes(player)) {
icons.push({
id: TARGET_ICON_ID,
kind: IMAGE_ICON_KIND,
src: targetIcon,
center: true,
});
}
// Emoji handling
if (emojisEnabled) {
const emoji = player
.outgoingEmojis()
.find(
(e) =>
e.recipientID === AllPlayers || e.recipientID === myPlayer?.smallID(),
);
if (emoji) {
icons.push({
id: EMOJI_ICON_ID,
kind: EMOJI_ICON_KIND,
text: emoji.message,
});
}
}
// Embargo icon (theme dependent)
if (myPlayer?.hasEmbargo(player)) {
const embargoIcon = isDarkMode ? embargoWhiteIcon : embargoBlackIcon;
icons.push({
id: EMBARGO_ICON_ID,
kind: IMAGE_ICON_KIND,
src: embargoIcon,
});
}
// Nuke icon (different color depending on whether the local player is the target)
if (!myPlayer || player.id() !== myPlayer.id()) {
let hasActiveNukes = false;
let isMyPlayerTarget = false;
const playerNukes = player.units(...Nukes.types);
for (const nuke of playerNukes) {
if (nuke.isActive()) {
hasActiveNukes = true;
const detonationDst = nuke.targetTile();
if (
myPlayer &&
detonationDst &&
game.owner(detonationDst).id() === myPlayer.id()
) {
isMyPlayerTarget = true;
break;
}
}
}
if (hasActiveNukes) {
const icon = isMyPlayerTarget ? nukeRedIcon : nukeWhiteIcon;
icons.push({ id: NUKE_ICON_ID, kind: IMAGE_ICON_KIND, src: icon });
}
}
return icons;
}
export function createAllianceProgressIconRefs(
size: number,
fraction: number,
hasExtensionRequest: boolean,
darkMode: string,
): AllianceProgressIconRefs {
if (!allianceIconTemplate) {
allianceIconTemplate = document.createElement("div");
allianceIconTemplate.setAttribute("data-icon", ALLIANCE_ICON_ID);
allianceIconTemplate.style.position = "relative";
allianceIconTemplate.style.display = "inline-block";
allianceIconTemplate.style.flexShrink = "0";
const base = document.createElement("img");
base.src = allianceIconFaded;
base.style.display = "block";
allianceIconTemplate.appendChild(base);
const overlay = document.createElement("div");
overlay.className = ALLIANCE_PROGRESS_OVERLAY_CLASS;
overlay.style.position = "absolute";
overlay.style.left = "0";
overlay.style.top = "0";
overlay.style.width = "100%";
overlay.style.height = "100%";
const colored = document.createElement("img");
colored.src = allianceIcon; // green icon
colored.style.display = "block";
overlay.appendChild(colored);
allianceIconTemplate.appendChild(overlay);
const questionMark = document.createElement("img");
questionMark.className = ALLIANCE_QUESTION_MARK_CLASS;
questionMark.src = questionMarkIcon;
questionMark.style.position = "absolute";
questionMark.style.left = "0";
questionMark.style.top = "0";
questionMark.style.pointerEvents = "none";
allianceIconTemplate.appendChild(questionMark);
}
// Wrapper
const wrapper = allianceIconTemplate.cloneNode(true) as HTMLDivElement;
wrapper.setAttribute("dark-mode", darkMode);
wrapper.style.width = `${size}px`;
wrapper.style.height = `${size}px`;
// Base faded icon (full)
// No QuerySelector here since we know the structure and it avoids overhead each call
const base = wrapper.childNodes[0] as HTMLImageElement;
base.style.width = `${size}px`;
base.style.height = `${size}px`;
base.setAttribute("dark-mode", darkMode);
// Overlay container for green portion, clipped from the top via clip-path
const overlay = wrapper.childNodes[1] as HTMLDivElement;
overlay.style.clipPath = computeAllianceClipPath(fraction);
const colored = overlay.childNodes[0] as HTMLImageElement;
colored.style.width = `${size}px`;
colored.style.height = `${size}px`;
colored.setAttribute("dark-mode", darkMode);
// Question mark overlay (shown when there's a pending extension request)
const questionMark = wrapper.childNodes[2] as HTMLImageElement;
questionMark.style.width = `${size}px`;
questionMark.style.height = `${size}px`;
questionMark.style.display = hasExtensionRequest ? "block" : "none";
questionMark.setAttribute("dark-mode", darkMode);
return {
wrapper,
base,
overlay,
colored,
questionMark,
};
}
export function updateAllianceProgressIconRefs(
refs: AllianceProgressIconRefs,
size: number,
fraction: number,
hasExtensionRequest: boolean,
darkMode: string,
): void {
refs.wrapper.style.width = `${size}px`;
refs.wrapper.style.height = `${size}px`;
refs.wrapper.style.flexShrink = "0";
refs.base.style.width = `${size}px`;
refs.base.style.height = `${size}px`;
refs.base.setAttribute("dark-mode", darkMode);
refs.colored.style.width = `${size}px`;
refs.colored.style.height = `${size}px`;
refs.colored.setAttribute("dark-mode", darkMode);
refs.overlay.style.clipPath = computeAllianceClipPath(fraction);
if (!hasExtensionRequest) {
refs.questionMark.style.display = "none";
} else {
refs.questionMark.style.width = `${size}px`;
refs.questionMark.style.height = `${size}px`;
refs.questionMark.style.display = "block";
refs.questionMark.setAttribute("dark-mode", darkMode);
}
}
export function computeAllianceClipPath(fraction: number): string {
const topCut = 20 + (1 - fraction) * 80 * 0.78; // min 20%, max 82.40%
return `inset(${topCut.toFixed(2)}% -2px 0 -2px)`;
}